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::messenger::{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.
1115 // Thus, we use `#[repr(C)]` on the struct to force a suboptimal layout and check that it stays 64
1117 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1118 const _GRAPH_NODE_SMALL: usize = 64 - core::mem::size_of::<RouteGraphNode>();
1119 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1120 const _GRAPH_NODE_FIXED_SIZE: usize = core::mem::size_of::<RouteGraphNode>() - 64;
1122 /// A [`CandidateRouteHop::FirstHop`] entry.
1123 #[derive(Clone, Debug)]
1124 pub struct FirstHopCandidate<'a> {
1125 /// Channel details of the first hop
1127 /// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1128 /// has been funded and is able to pay), and accessor methods may panic otherwise.
1130 /// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1131 pub details: &'a ChannelDetails,
1132 /// The node id of the payer, which is also the source side of this candidate route hop.
1133 pub payer_node_id: &'a NodeId,
1136 /// A [`CandidateRouteHop::PublicHop`] entry.
1137 #[derive(Clone, Debug)]
1138 pub struct PublicHopCandidate<'a> {
1139 /// Information about the channel, including potentially its capacity and
1140 /// direction-specific information.
1141 pub info: DirectedChannelInfo<'a>,
1142 /// The short channel ID of the channel, i.e. the identifier by which we refer to this
1144 pub short_channel_id: u64,
1147 /// A [`CandidateRouteHop::PrivateHop`] entry.
1148 #[derive(Clone, Debug)]
1149 pub struct PrivateHopCandidate<'a> {
1150 /// Information about the private hop communicated via BOLT 11.
1151 pub hint: &'a RouteHintHop,
1152 /// Node id of the next hop in BOLT 11 route hint.
1153 pub target_node_id: &'a NodeId
1156 /// A [`CandidateRouteHop::Blinded`] entry.
1157 #[derive(Clone, Debug)]
1158 pub struct BlindedPathCandidate<'a> {
1159 /// Information about the blinded path including the fee, HTLC amount limits, and
1160 /// cryptographic material required to build an HTLC through the given path.
1161 pub hint: &'a (BlindedPayInfo, BlindedPath),
1162 /// Index of the hint in the original list of blinded hints.
1164 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1165 /// a short channel ID for this hop.
1169 /// A [`CandidateRouteHop::OneHopBlinded`] entry.
1170 #[derive(Clone, Debug)]
1171 pub struct OneHopBlindedPathCandidate<'a> {
1172 /// Information about the blinded path including the fee, HTLC amount limits, and
1173 /// cryptographic material required to build an HTLC terminating with the given path.
1175 /// Note that the [`BlindedPayInfo`] is ignored here.
1176 pub hint: &'a (BlindedPayInfo, BlindedPath),
1177 /// Index of the hint in the original list of blinded hints.
1179 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1180 /// a short channel ID for this hop.
1184 /// A wrapper around the various hop representations.
1186 /// Can be used to examine the properties of a hop,
1187 /// potentially to decide whether to include it in a route.
1188 #[derive(Clone, Debug)]
1189 pub enum CandidateRouteHop<'a> {
1190 /// A hop from the payer, where the outbound liquidity is known.
1191 FirstHop(FirstHopCandidate<'a>),
1192 /// A hop found in the [`ReadOnlyNetworkGraph`].
1193 PublicHop(PublicHopCandidate<'a>),
1194 /// A private hop communicated by the payee, generally via a BOLT 11 invoice.
1196 /// Because BOLT 11 route hints can take multiple hops to get to the destination, this may not
1197 /// terminate at the payee.
1198 PrivateHop(PrivateHopCandidate<'a>),
1199 /// A blinded path which starts with an introduction point and ultimately terminates with the
1202 /// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1203 /// `None` in this state.
1205 /// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1206 /// path, the full path is treated as a single [`CandidateRouteHop`].
1207 Blinded(BlindedPathCandidate<'a>),
1208 /// Similar to [`Self::Blinded`], but the path here only has one hop.
1210 /// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1211 /// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1212 /// payee's identity - it's the introduction point!
1214 /// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1215 /// to the hops *between* the introduction node and the destination.
1217 /// This primarily exists to track that we need to included a blinded path at the end of our
1218 /// [`Route`], even though it doesn't actually add an additional hop in the payment.
1219 OneHopBlinded(OneHopBlindedPathCandidate<'a>),
1222 impl<'a> CandidateRouteHop<'a> {
1223 /// Returns the short channel ID for this hop, if one is known.
1225 /// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1226 /// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1228 /// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1229 /// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1230 /// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1231 /// (which is always true for channels which are funded and ready for use).
1233 /// In other words, this should always return `Some` as long as the candidate hop is not a
1234 /// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1236 /// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1237 /// define a global namespace.
1239 fn short_channel_id(&self) -> Option<u64> {
1241 CandidateRouteHop::FirstHop(hop) => hop.details.get_outbound_payment_scid(),
1242 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1243 CandidateRouteHop::PrivateHop(hop) => Some(hop.hint.short_channel_id),
1244 CandidateRouteHop::Blinded(_) => None,
1245 CandidateRouteHop::OneHopBlinded(_) => None,
1249 /// Returns the globally unique short channel ID for this hop, if one is known.
1251 /// This only returns `Some` if the channel is public (either our own, or one we've learned
1252 /// from the public network graph), and thus the short channel ID we have for this channel is
1253 /// globally unique and identifies this channel in a global namespace.
1255 pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1257 CandidateRouteHop::FirstHop(hop) => if hop.details.is_public { hop.details.short_channel_id } else { None },
1258 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1259 CandidateRouteHop::PrivateHop(_) => None,
1260 CandidateRouteHop::Blinded(_) => None,
1261 CandidateRouteHop::OneHopBlinded(_) => None,
1265 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1266 fn features(&self) -> ChannelFeatures {
1268 CandidateRouteHop::FirstHop(hop) => hop.details.counterparty.features.to_context(),
1269 CandidateRouteHop::PublicHop(hop) => hop.info.channel().features.clone(),
1270 CandidateRouteHop::PrivateHop(_) => ChannelFeatures::empty(),
1271 CandidateRouteHop::Blinded(_) => ChannelFeatures::empty(),
1272 CandidateRouteHop::OneHopBlinded(_) => ChannelFeatures::empty(),
1276 /// Returns the required difference in HTLC CLTV expiry between the [`Self::source`] and the
1277 /// next-hop for an HTLC taking this hop.
1279 /// This is the time that the node(s) in this hop have to claim the HTLC on-chain if the
1280 /// next-hop goes on chain with a payment preimage.
1282 pub fn cltv_expiry_delta(&self) -> u32 {
1284 CandidateRouteHop::FirstHop(_) => 0,
1285 CandidateRouteHop::PublicHop(hop) => hop.info.direction().cltv_expiry_delta as u32,
1286 CandidateRouteHop::PrivateHop(hop) => hop.hint.cltv_expiry_delta as u32,
1287 CandidateRouteHop::Blinded(hop) => hop.hint.0.cltv_expiry_delta as u32,
1288 CandidateRouteHop::OneHopBlinded(_) => 0,
1292 /// Returns the minimum amount that can be sent over this hop, in millisatoshis.
1294 pub fn htlc_minimum_msat(&self) -> u64 {
1296 CandidateRouteHop::FirstHop(hop) => hop.details.next_outbound_htlc_minimum_msat,
1297 CandidateRouteHop::PublicHop(hop) => hop.info.direction().htlc_minimum_msat,
1298 CandidateRouteHop::PrivateHop(hop) => hop.hint.htlc_minimum_msat.unwrap_or(0),
1299 CandidateRouteHop::Blinded(hop) => hop.hint.0.htlc_minimum_msat,
1300 CandidateRouteHop::OneHopBlinded { .. } => 0,
1304 /// Returns the fees that must be paid to route an HTLC over this channel.
1306 pub fn fees(&self) -> RoutingFees {
1308 CandidateRouteHop::FirstHop(_) => RoutingFees {
1309 base_msat: 0, proportional_millionths: 0,
1311 CandidateRouteHop::PublicHop(hop) => hop.info.direction().fees,
1312 CandidateRouteHop::PrivateHop(hop) => hop.hint.fees,
1313 CandidateRouteHop::Blinded(hop) => {
1315 base_msat: hop.hint.0.fee_base_msat,
1316 proportional_millionths: hop.hint.0.fee_proportional_millionths
1319 CandidateRouteHop::OneHopBlinded(_) =>
1320 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1324 /// Fetch the effective capacity of this hop.
1326 /// Note that this may be somewhat expensive, so calls to this should be limited and results
1328 fn effective_capacity(&self) -> EffectiveCapacity {
1330 CandidateRouteHop::FirstHop(hop) => EffectiveCapacity::ExactLiquidity {
1331 liquidity_msat: hop.details.next_outbound_htlc_limit_msat,
1333 CandidateRouteHop::PublicHop(hop) => hop.info.effective_capacity(),
1334 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. }) =>
1335 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1336 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. }) =>
1337 EffectiveCapacity::Infinite,
1338 CandidateRouteHop::Blinded(hop) =>
1339 EffectiveCapacity::HintMaxHTLC { amount_msat: hop.hint.0.htlc_maximum_msat },
1340 CandidateRouteHop::OneHopBlinded(_) => EffectiveCapacity::Infinite,
1344 /// Returns an ID describing the given hop.
1346 /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1348 fn id(&self) -> CandidateHopId {
1350 CandidateRouteHop::Blinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1351 CandidateRouteHop::OneHopBlinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1352 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1355 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1357 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1363 /// Returns the source node id of current hop.
1365 /// Source node id refers to the node forwarding the HTLC through this hop.
1367 /// For [`Self::FirstHop`] we return payer's node id.
1369 pub fn source(&self) -> NodeId {
1371 CandidateRouteHop::FirstHop(hop) => *hop.payer_node_id,
1372 CandidateRouteHop::PublicHop(hop) => *hop.info.source(),
1373 CandidateRouteHop::PrivateHop(hop) => hop.hint.src_node_id.into(),
1374 CandidateRouteHop::Blinded(hop) => hop.hint.1.introduction_node_id.into(),
1375 CandidateRouteHop::OneHopBlinded(hop) => hop.hint.1.introduction_node_id.into(),
1378 /// Returns the target node id of this hop, if known.
1380 /// Target node id refers to the node receiving the HTLC after this hop.
1382 /// For [`Self::Blinded`] we return `None` because the ultimate destination after the blinded
1383 /// path is unknown.
1385 /// For [`Self::OneHopBlinded`] we return `None` because the target is the same as the source,
1386 /// and such a return value would be somewhat nonsensical.
1388 pub fn target(&self) -> Option<NodeId> {
1390 CandidateRouteHop::FirstHop(hop) => Some(hop.details.counterparty.node_id.into()),
1391 CandidateRouteHop::PublicHop(hop) => Some(*hop.info.target()),
1392 CandidateRouteHop::PrivateHop(hop) => Some(*hop.target_node_id),
1393 CandidateRouteHop::Blinded(_) => None,
1394 CandidateRouteHop::OneHopBlinded(_) => None,
1399 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1401 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1403 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1404 /// isn't guaranteed to be unique at all.
1406 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1407 /// difficult-to-use API.
1408 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1409 enum CandidateHopId {
1410 /// Contains (scid, src_node_id < target_node_id)
1412 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1417 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1418 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1420 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1421 EffectiveCapacity::Infinite => u64::max_value(),
1422 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1423 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1424 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1425 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1426 // expected to have been generated from up-to-date capacity information.
1427 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1428 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1429 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1433 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1434 -> bool where I1::Item: PartialEq<I2::Item> {
1436 let a = iter_a.next();
1437 let b = iter_b.next();
1438 if a.is_none() && b.is_none() { return true; }
1439 if a.is_none() || b.is_none() { return false; }
1440 if a.unwrap().ne(&b.unwrap()) { return false; }
1444 /// It's useful to keep track of the hops associated with the fees required to use them,
1445 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1446 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1447 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1449 #[repr(C)] // Force fields to appear in the order we define them.
1450 struct PathBuildingHop<'a> {
1451 candidate: CandidateRouteHop<'a>,
1452 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1453 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1454 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1455 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1456 /// avoid processing them again.
1457 was_processed: bool,
1458 /// Used to compare channels when choosing the for routing.
1459 /// Includes paying for the use of a hop and the following hops, as well as
1460 /// an estimated cost of reaching this hop.
1461 /// Might get stale when fees are recomputed. Primarily for internal use.
1462 total_fee_msat: u64,
1463 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1464 /// walk and may be invalid thereafter.
1465 path_htlc_minimum_msat: u64,
1466 /// All penalties incurred from this channel on the way to the destination, as calculated using
1467 /// channel scoring.
1468 path_penalty_msat: u64,
1470 // The last 16 bytes are on the next cache line by default in glibc's malloc. Thus, we should
1471 // only place fields which are not hot there. Luckily, the next three fields are only read if
1472 // we end up on the selected path, and only in the final path layout phase, so we don't care
1473 // too much if reading them is slow.
1477 /// All the fees paid *after* this channel on the way to the destination
1478 next_hops_fee_msat: u64,
1479 /// Fee paid for the use of the current channel (see candidate.fees()).
1480 /// The value will be actually deducted from the counterparty balance on the previous link.
1481 hop_use_fee_msat: u64,
1483 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1484 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1485 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1486 // value_contribution_msat, which requires tracking it here. See comments below where it is
1487 // used for more info.
1488 value_contribution_msat: u64,
1491 // Checks that the entries in the `find_route` `dist` map fit in (exactly) two standard x86-64
1492 // cache lines. Sadly, they're not guaranteed to actually lie on a cache line (and in fact,
1493 // generally won't, because at least glibc's malloc will align to a nice, big, round
1494 // boundary...plus 16), but at least it will reduce the amount of data we'll need to load.
1496 // Note that these assertions only pass on somewhat recent rustc, and thus are gated on the
1499 const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::<(NodeId, PathBuildingHop)>();
1501 const _NODE_MAP_SIZE_EXACTLY_CACHE_LINES: usize = core::mem::size_of::<(NodeId, PathBuildingHop)>() - 128;
1503 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1504 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1505 let mut debug_struct = f.debug_struct("PathBuildingHop");
1507 .field("node_id", &self.candidate.target())
1508 .field("short_channel_id", &self.candidate.short_channel_id())
1509 .field("total_fee_msat", &self.total_fee_msat)
1510 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1511 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1512 .field("total_fee_msat - (next_hops_fee_msat + hop_use_fee_msat)", &(&self.total_fee_msat - (&self.next_hops_fee_msat + &self.hop_use_fee_msat)))
1513 .field("path_penalty_msat", &self.path_penalty_msat)
1514 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1515 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1516 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1517 let debug_struct = debug_struct
1518 .field("value_contribution_msat", &self.value_contribution_msat);
1519 debug_struct.finish()
1523 // Instantiated with a list of hops with correct data in them collected during path finding,
1524 // an instance of this struct should be further modified only via given methods.
1526 struct PaymentPath<'a> {
1527 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1530 impl<'a> PaymentPath<'a> {
1531 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1532 fn get_value_msat(&self) -> u64 {
1533 self.hops.last().unwrap().0.fee_msat
1536 fn get_path_penalty_msat(&self) -> u64 {
1537 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1540 fn get_total_fee_paid_msat(&self) -> u64 {
1541 if self.hops.len() < 1 {
1545 // Can't use next_hops_fee_msat because it gets outdated.
1546 for (i, (hop, _)) in self.hops.iter().enumerate() {
1547 if i != self.hops.len() - 1 {
1548 result += hop.fee_msat;
1554 fn get_cost_msat(&self) -> u64 {
1555 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1558 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1559 // to change fees may result in an inconsistency.
1561 // Sometimes we call this function right after constructing a path which is inconsistent in
1562 // that it the value being transferred has decreased while we were doing path finding, leading
1563 // to the fees being paid not lining up with the actual limits.
1565 // Note that this function is not aware of the available_liquidity limit, and thus does not
1566 // support increasing the value being transferred beyond what was selected during the initial
1569 // Returns the amount that this path contributes to the total payment value, which may be greater
1570 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1571 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1572 let mut extra_contribution_msat = 0;
1573 let mut total_fee_paid_msat = 0 as u64;
1574 for i in (0..self.hops.len()).rev() {
1575 let last_hop = i == self.hops.len() - 1;
1577 // For non-last-hop, this value will represent the fees paid on the current hop. It
1578 // will consist of the fees for the use of the next hop, and extra fees to match
1579 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1580 let mut cur_hop_fees_msat = 0;
1582 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1585 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1586 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1587 cur_hop.path_penalty_msat += extra_contribution_msat;
1588 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1589 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1590 // set it too high just to maliciously take more fees by exploiting this
1591 // match htlc_minimum_msat logic.
1592 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1593 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1594 // Note that there is a risk that *previous hops* (those closer to us, as we go
1595 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1597 // This might make us end up with a broken route, although this should be super-rare
1598 // in practice, both because of how healthy channels look like, and how we pick
1599 // channels in add_entry.
1600 // Also, this can't be exploited more heavily than *announce a free path and fail
1602 cur_hop_transferred_amount_msat += extra_fees_msat;
1604 // We remember and return the extra fees on the final hop to allow accounting for
1605 // them in the path's value contribution.
1607 extra_contribution_msat = extra_fees_msat;
1609 total_fee_paid_msat += extra_fees_msat;
1610 cur_hop_fees_msat += extra_fees_msat;
1615 // Final hop is a special case: it usually has just value_msat (by design), but also
1616 // it still could overpay for the htlc_minimum_msat.
1617 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1619 // Propagate updated fees for the use of the channels to one hop back, where they
1620 // will be actually paid (fee_msat). The last hop is handled above separately.
1621 cur_hop.fee_msat = cur_hop_fees_msat;
1624 // Fee for the use of the current hop which will be deducted on the previous hop.
1625 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1626 // this channel is free for us.
1628 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1629 cur_hop.hop_use_fee_msat = new_fee;
1630 total_fee_paid_msat += new_fee;
1632 // It should not be possible because this function is called only to reduce the
1633 // value. In that case, compute_fee was already called with the same fees for
1634 // larger amount and there was no overflow.
1639 value_msat + extra_contribution_msat
1644 /// Calculate the fees required to route the given amount over a channel with the given fees.
1645 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1646 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1647 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1651 /// Calculate the fees required to route the given amount over a channel with the given fees,
1652 /// saturating to [`u64::max_value`].
1653 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1654 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1655 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1656 .saturating_add(channel_fees.base_msat as u64)
1659 /// The default `features` we assume for a node in a route, when no `features` are known about that
1662 /// Default features are:
1663 /// * variable_length_onion_optional
1664 fn default_node_features() -> NodeFeatures {
1665 let mut features = NodeFeatures::empty();
1666 features.set_variable_length_onion_optional();
1670 struct LoggedPayeePubkey(Option<PublicKey>);
1671 impl fmt::Display for LoggedPayeePubkey {
1672 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1675 "payee node id ".fmt(f)?;
1679 "blinded payee".fmt(f)
1685 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1686 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1687 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1689 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1690 "blinded route hint with introduction node id ".fmt(f)?;
1691 hint.1.introduction_node_id.fmt(f)?;
1692 " and blinding point ".fmt(f)?;
1693 hint.1.blinding_point.fmt(f)
1695 CandidateRouteHop::FirstHop(_) => {
1696 "first hop with SCID ".fmt(f)?;
1697 self.0.short_channel_id().unwrap().fmt(f)
1699 CandidateRouteHop::PrivateHop(_) => {
1700 "route hint with SCID ".fmt(f)?;
1701 self.0.short_channel_id().unwrap().fmt(f)
1705 self.0.short_channel_id().unwrap().fmt(f)
1712 fn sort_first_hop_channels(
1713 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1714 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1716 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1717 // most like to use.
1719 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1720 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1723 // Second, because simply always sorting in descending order would always use our largest
1724 // available outbound capacity, needlessly fragmenting our available channel capacities,
1725 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1726 // which have enough, but not too much, capacity for the payment.
1728 // Available outbound balances factor in liquidity already reserved for previously found paths.
1729 channels.sort_unstable_by(|chan_a, chan_b| {
1730 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1731 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1732 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1733 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1734 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1735 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1736 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1737 // Sort in descending order
1738 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1740 // Sort in ascending order
1741 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1746 /// Finds a route from us (payer) to the given target node (payee).
1748 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1749 /// in the given [`RouteParameters::payment_params`].
1750 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1752 /// Private routing paths between a public node and the target may be included in the `payee` field
1753 /// of [`RouteParameters::payment_params`].
1755 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1756 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1757 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1759 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1760 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1761 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1765 /// Panics if first_hops contains channels without `short_channel_id`s;
1766 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1768 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1769 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1770 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1771 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1772 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1773 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1774 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1775 ) -> Result<Route, LightningError>
1776 where L::Target: Logger, GL::Target: Logger {
1777 let graph_lock = network_graph.read_only();
1778 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1779 scorer, score_params, random_seed_bytes)?;
1780 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1784 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1785 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1786 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1787 _random_seed_bytes: &[u8; 32]
1788 ) -> Result<Route, LightningError>
1789 where L::Target: Logger {
1791 let payment_params = &route_params.payment_params;
1792 let final_value_msat = route_params.final_value_msat;
1793 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1794 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1795 // so use a dummy id for this in the blinded case.
1796 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1797 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1798 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1799 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1800 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1802 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1803 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1805 if our_node_id == maybe_dummy_payee_node_id {
1806 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1809 if final_value_msat > MAX_VALUE_MSAT {
1810 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1813 if final_value_msat == 0 {
1814 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1817 match &payment_params.payee {
1818 Payee::Clear { route_hints, node_id, .. } => {
1819 for route in route_hints.iter() {
1820 for hop in &route.0 {
1821 if hop.src_node_id == *node_id {
1822 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1827 Payee::Blinded { route_hints, .. } => {
1828 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1829 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});
1831 for (_, blinded_path) in route_hints.iter() {
1832 if blinded_path.blinded_hops.len() == 0 {
1833 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1834 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1835 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1836 } else if blinded_path.blinded_hops.len() == 1 &&
1837 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1838 && p.introduction_node_id != blinded_path.introduction_node_id)
1840 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1845 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1846 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1847 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});
1850 // The general routing idea is the following:
1851 // 1. Fill first/last hops communicated by the caller.
1852 // 2. Attempt to construct a path from payer to payee for transferring
1853 // any ~sufficient (described later) value.
1854 // If succeed, remember which channels were used and how much liquidity they have available,
1855 // so that future paths don't rely on the same liquidity.
1856 // 3. Proceed to the next step if:
1857 // - we hit the recommended target value;
1858 // - OR if we could not construct a new path. Any next attempt will fail too.
1859 // Otherwise, repeat step 2.
1860 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1861 // (not recommended value).
1862 // 5. If yes, proceed. If not, fail routing.
1863 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1864 // transferred up to the transfer target value.
1865 // 7. Reduce the value of the last path until we are sending only the target value.
1866 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1867 // them so that we're not sending two HTLCs along the same path.
1869 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1870 // distance from the payee
1872 // We are not a faithful Dijkstra's implementation because we can change values which impact
1873 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1874 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1875 // the value we are currently attempting to send over a path, we simply reduce the value being
1876 // sent along the path for any hops after that channel. This may imply that later fees (which
1877 // we've already tabulated) are lower because a smaller value is passing through the channels
1878 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1879 // channels which were selected earlier (and which may still be used for other paths without a
1880 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1883 // One potentially problematic case for this algorithm would be if there are many
1884 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1885 // graph walking), we may never find a path which is not liquidity-limited and has lower
1886 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1887 // Because we only consider paths with at least 5% of the total value being sent, the damage
1888 // from such a case should be limited, however this could be further reduced in the future by
1889 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1890 // limits for the purposes of fee calculation.
1892 // Alternatively, we could store more detailed path information in the heap (targets, below)
1893 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1894 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1895 // and practically (as we would need to store dynamically-allocated path information in heap
1896 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1897 // results of such an algorithm would likely be biased towards lower-value paths.
1899 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1900 // outside of our current search value, running a path search more times to gather candidate
1901 // paths at different values. While this may be acceptable, further path searches may increase
1902 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1903 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1904 // the same time, remaining generic across different payment values.
1906 let network_channels = network_graph.channels();
1907 let network_nodes = network_graph.nodes();
1909 if payment_params.max_path_count == 0 {
1910 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1913 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1914 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1916 let allow_mpp = if payment_params.max_path_count == 1 {
1918 } else if payment_params.payee.supports_basic_mpp() {
1920 } else if let Some(payee) = payee_node_id_opt {
1921 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1922 |info| info.features.supports_basic_mpp()))
1925 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1927 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph with a fee limit of {} msat",
1928 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
1929 if allow_mpp { "with" } else { "without" },
1930 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " },
1931 max_total_routing_fee_msat);
1934 // Prepare the data we'll use for payee-to-payer search by
1935 // inserting first hops suggested by the caller as targets.
1936 // Our search will then attempt to reach them while traversing from the payee node.
1937 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1938 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1939 if let Some(hops) = first_hops {
1941 if chan.get_outbound_payment_scid().is_none() {
1942 panic!("first_hops should be filled in with usable channels, not pending ones");
1944 if chan.counterparty.node_id == *our_node_pubkey {
1945 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1948 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1949 .or_insert(Vec::new())
1952 if first_hop_targets.is_empty() {
1953 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1957 let mut private_hop_key_cache = HashMap::with_capacity(
1958 payment_params.payee.unblinded_route_hints().iter().map(|path| path.0.len()).sum()
1961 // Because we store references to private hop node_ids in `dist`, below, we need them to exist
1962 // (as `NodeId`, not `PublicKey`) for the lifetime of `dist`. Thus, we calculate all the keys
1963 // we'll need here and simply fetch them when routing.
1964 private_hop_key_cache.insert(maybe_dummy_payee_pk, NodeId::from_pubkey(&maybe_dummy_payee_pk));
1965 for route in payment_params.payee.unblinded_route_hints().iter() {
1966 for hop in route.0.iter() {
1967 private_hop_key_cache.insert(hop.src_node_id, NodeId::from_pubkey(&hop.src_node_id));
1971 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1972 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1973 // adding duplicate entries when we find a better path to a given node.
1974 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1976 // Map from node_id to information about the best current path to that node, including feerate
1978 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1980 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1981 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1982 // htlc_minimum with extra fees while still finding a cheaper path.
1983 let mut hit_minimum_limit;
1985 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1986 // We start with a path_value of the exact amount we want, and if that generates a route we may
1987 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1988 // amount we want in total across paths, selecting the best subset at the end.
1989 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1990 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1991 let mut path_value_msat = final_value_msat;
1993 // Routing Fragmentation Mitigation heuristic:
1995 // Routing fragmentation across many payment paths increases the overall routing
1996 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1997 // Taking too many smaller paths also increases the chance of payment failure.
1998 // Thus to avoid this effect, we require from our collected links to provide
1999 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
2000 // This requirement is currently set to be 1/max_path_count of the payment
2001 // value to ensure we only ever return routes that do not violate this limit.
2002 let minimal_value_contribution_msat: u64 = if allow_mpp {
2003 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
2008 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
2009 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
2010 // drop the requirement by setting this to 0.
2011 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
2013 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
2014 // determine if the channel can be used by additional MPP paths or to inform path finding
2015 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
2016 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
2018 let mut used_liquidities: HashMap<CandidateHopId, u64> =
2019 HashMap::with_capacity(network_nodes.len());
2021 // Keeping track of how much value we already collected across other paths. Helps to decide
2022 // when we want to stop looking for new paths.
2023 let mut already_collected_value_msat = 0;
2025 for (_, channels) in first_hop_targets.iter_mut() {
2026 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
2030 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
2031 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
2033 // Remember how many candidates we ignored to allow for some logging afterwards.
2034 let mut num_ignored_value_contribution: u32 = 0;
2035 let mut num_ignored_path_length_limit: u32 = 0;
2036 let mut num_ignored_cltv_delta_limit: u32 = 0;
2037 let mut num_ignored_previously_failed: u32 = 0;
2038 let mut num_ignored_total_fee_limit: u32 = 0;
2039 let mut num_ignored_avoid_overpayment: u32 = 0;
2040 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
2042 macro_rules! add_entry {
2043 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
2044 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
2045 // since that value has to be transferred over this channel.
2046 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
2047 ( $candidate: expr, $next_hops_fee_msat: expr,
2048 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
2049 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
2050 // We "return" whether we updated the path at the end, and how much we can route via
2051 // this channel, via this:
2052 let mut hop_contribution_amt_msat = None;
2053 // Channels to self should not be used. This is more of belt-and-suspenders, because in
2054 // practice these cases should be caught earlier:
2055 // - for regular channels at channel announcement (TODO)
2056 // - for first and last hops early in get_route
2057 let src_node_id = $candidate.source();
2058 if Some(src_node_id) != $candidate.target() {
2059 let scid_opt = $candidate.short_channel_id();
2060 let effective_capacity = $candidate.effective_capacity();
2061 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
2063 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
2064 // It may be misleading because we might later choose to reduce the value transferred
2065 // over these channels, and the channel which was insufficient might become sufficient.
2066 // Worst case: we drop a good channel here because it can't cover the high following
2067 // fees caused by one expensive channel, but then this channel could have been used
2068 // if the amount being transferred over this path is lower.
2069 // We do this for now, but this is a subject for removal.
2070 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
2071 let used_liquidity_msat = used_liquidities
2072 .get(&$candidate.id())
2073 .map_or(0, |used_liquidity_msat| {
2074 available_value_contribution_msat = available_value_contribution_msat
2075 .saturating_sub(*used_liquidity_msat);
2076 *used_liquidity_msat
2079 // Verify the liquidity offered by this channel complies to the minimal contribution.
2080 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
2081 // Do not consider candidate hops that would exceed the maximum path length.
2082 let path_length_to_node = $next_hops_path_length + 1;
2083 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
2085 // Do not consider candidates that exceed the maximum total cltv expiry limit.
2086 // In order to already account for some of the privacy enhancing random CLTV
2087 // expiry delta offset we add on top later, we subtract a rough estimate
2088 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
2089 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
2090 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
2091 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
2092 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
2093 .saturating_add($candidate.cltv_expiry_delta());
2094 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
2096 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
2097 // Includes paying fees for the use of the following channels.
2098 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
2099 Some(result) => result,
2100 // Can't overflow due to how the values were computed right above.
2101 None => unreachable!(),
2103 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2104 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
2105 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
2107 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2108 let may_overpay_to_meet_path_minimum_msat =
2109 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
2110 recommended_value_msat >= $candidate.htlc_minimum_msat()) ||
2111 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
2112 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
2114 let payment_failed_on_this_channel = scid_opt.map_or(false,
2115 |scid| payment_params.previously_failed_channels.contains(&scid));
2117 let (should_log_candidate, first_hop_details) = match $candidate {
2118 CandidateRouteHop::FirstHop(hop) => (true, Some(hop.details)),
2119 CandidateRouteHop::PrivateHop(_) => (true, None),
2120 CandidateRouteHop::Blinded(_) => (true, None),
2121 CandidateRouteHop::OneHopBlinded(_) => (true, None),
2125 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
2126 // bother considering this channel. If retrying with recommended_value_msat may
2127 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
2128 // around again with a higher amount.
2129 if !contributes_sufficient_value {
2130 if should_log_candidate {
2131 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
2133 if let Some(details) = first_hop_details {
2135 "First hop candidate next_outbound_htlc_limit_msat: {}",
2136 details.next_outbound_htlc_limit_msat,
2140 num_ignored_value_contribution += 1;
2141 } else if exceeds_max_path_length {
2142 if should_log_candidate {
2143 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
2145 num_ignored_path_length_limit += 1;
2146 } else if exceeds_cltv_delta_limit {
2147 if should_log_candidate {
2148 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
2150 if let Some(_) = first_hop_details {
2152 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
2153 hop_total_cltv_delta,
2154 max_total_cltv_expiry_delta,
2158 num_ignored_cltv_delta_limit += 1;
2159 } else if payment_failed_on_this_channel {
2160 if should_log_candidate {
2161 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
2163 num_ignored_previously_failed += 1;
2164 } else if may_overpay_to_meet_path_minimum_msat {
2165 if should_log_candidate {
2167 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit.",
2168 LoggedCandidateHop(&$candidate));
2170 if let Some(details) = first_hop_details {
2172 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2173 details.next_outbound_htlc_minimum_msat,
2177 num_ignored_avoid_overpayment += 1;
2178 hit_minimum_limit = true;
2179 } else if over_path_minimum_msat {
2180 // Note that low contribution here (limited by available_liquidity_msat)
2181 // might violate htlc_minimum_msat on the hops which are next along the
2182 // payment path (upstream to the payee). To avoid that, we recompute
2183 // path fees knowing the final path contribution after constructing it.
2184 let curr_min = cmp::max(
2185 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
2187 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
2188 .saturating_add(curr_min);
2189 let hm_entry = dist.entry(src_node_id);
2190 let old_entry = hm_entry.or_insert_with(|| {
2191 // If there was previously no known way to access the source node
2192 // (recall it goes payee-to-payer) of short_channel_id, first add a
2193 // semi-dummy record just to compute the fees to reach the source node.
2194 // This will affect our decision on selecting short_channel_id
2195 // as a way to reach the $candidate.target() node.
2197 candidate: $candidate.clone(),
2199 next_hops_fee_msat: u64::max_value(),
2200 hop_use_fee_msat: u64::max_value(),
2201 total_fee_msat: u64::max_value(),
2202 path_htlc_minimum_msat,
2203 path_penalty_msat: u64::max_value(),
2204 was_processed: false,
2205 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2206 value_contribution_msat,
2210 #[allow(unused_mut)] // We only use the mut in cfg(test)
2211 let mut should_process = !old_entry.was_processed;
2212 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2214 // In test/fuzzing builds, we do extra checks to make sure the skipping
2215 // of already-seen nodes only happens in cases we expect (see below).
2216 if !should_process { should_process = true; }
2220 let mut hop_use_fee_msat = 0;
2221 let mut total_fee_msat: u64 = $next_hops_fee_msat;
2223 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2224 // will have the same effective-fee
2225 if src_node_id != our_node_id {
2226 // Note that `u64::max_value` means we'll always fail the
2227 // `old_entry.total_fee_msat > total_fee_msat` check below
2228 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
2229 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2232 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2233 if total_fee_msat > max_total_routing_fee_msat {
2234 if should_log_candidate {
2235 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2237 if let Some(_) = first_hop_details {
2239 "First hop candidate routing fee: {}. Limit: {}",
2241 max_total_routing_fee_msat,
2245 num_ignored_total_fee_limit += 1;
2247 let channel_usage = ChannelUsage {
2248 amount_msat: amount_to_transfer_over_msat,
2249 inflight_htlc_msat: used_liquidity_msat,
2252 let channel_penalty_msat =
2253 scorer.channel_penalty_msat($candidate,
2256 let path_penalty_msat = $next_hops_path_penalty_msat
2257 .saturating_add(channel_penalty_msat);
2259 // Update the way of reaching $candidate.source()
2260 // with the given short_channel_id (from $candidate.target()),
2261 // if this way is cheaper than the already known
2262 // (considering the cost to "reach" this channel from the route destination,
2263 // the cost of using this channel,
2264 // and the cost of routing to the source node of this channel).
2265 // Also, consider that htlc_minimum_msat_difference, because we might end up
2266 // paying it. Consider the following exploit:
2267 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2268 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2269 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2270 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2272 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2273 // but it may require additional tracking - we don't want to double-count
2274 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2275 // can't use something that may decrease on future hops.
2276 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2277 .saturating_add(old_entry.path_penalty_msat);
2278 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2279 .saturating_add(path_penalty_msat);
2281 if !old_entry.was_processed && new_cost < old_cost {
2282 let new_graph_node = RouteGraphNode {
2283 node_id: src_node_id,
2284 score: cmp::max(total_fee_msat, path_htlc_minimum_msat).saturating_add(path_penalty_msat),
2285 total_cltv_delta: hop_total_cltv_delta,
2286 value_contribution_msat,
2287 path_length_to_node,
2289 targets.push(new_graph_node);
2290 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2291 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2292 old_entry.total_fee_msat = total_fee_msat;
2293 old_entry.candidate = $candidate.clone();
2294 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2295 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2296 old_entry.path_penalty_msat = path_penalty_msat;
2297 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2299 old_entry.value_contribution_msat = value_contribution_msat;
2301 hop_contribution_amt_msat = Some(value_contribution_msat);
2302 } else if old_entry.was_processed && new_cost < old_cost {
2303 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2305 // If we're skipping processing a node which was previously
2306 // processed even though we found another path to it with a
2307 // cheaper fee, check that it was because the second path we
2308 // found (which we are processing now) has a lower value
2309 // contribution due to an HTLC minimum limit.
2311 // e.g. take a graph with two paths from node 1 to node 2, one
2312 // through channel A, and one through channel B. Channel A and
2313 // B are both in the to-process heap, with their scores set by
2314 // a higher htlc_minimum than fee.
2315 // Channel A is processed first, and the channels onwards from
2316 // node 1 are added to the to-process heap. Thereafter, we pop
2317 // Channel B off of the heap, note that it has a much more
2318 // restrictive htlc_maximum_msat, and recalculate the fees for
2319 // all of node 1's channels using the new, reduced, amount.
2321 // This would be bogus - we'd be selecting a higher-fee path
2322 // with a lower htlc_maximum_msat instead of the one we'd
2323 // already decided to use.
2324 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2326 value_contribution_msat + path_penalty_msat <
2327 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2334 if should_log_candidate {
2336 "Ignoring {} due to its htlc_minimum_msat limit.",
2337 LoggedCandidateHop(&$candidate));
2339 if let Some(details) = first_hop_details {
2341 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2342 details.next_outbound_htlc_minimum_msat,
2346 num_ignored_htlc_minimum_msat_limit += 1;
2350 hop_contribution_amt_msat
2354 let default_node_features = default_node_features();
2356 // Find ways (channels with destination) to reach a given node and store them
2357 // in the corresponding data structures (routing graph etc).
2358 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2359 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2360 // This data can later be helpful to optimize routing (pay lower fees).
2361 macro_rules! add_entries_to_cheapest_to_target_node {
2362 ( $node: expr, $node_id: expr, $next_hops_value_contribution: expr,
2363 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2364 let fee_to_target_msat;
2365 let next_hops_path_htlc_minimum_msat;
2366 let next_hops_path_penalty_msat;
2367 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
2368 let was_processed = elem.was_processed;
2369 elem.was_processed = true;
2370 fee_to_target_msat = elem.total_fee_msat;
2371 next_hops_path_htlc_minimum_msat = elem.path_htlc_minimum_msat;
2372 next_hops_path_penalty_msat = elem.path_penalty_msat;
2375 // Entries are added to dist in add_entry!() when there is a channel from a node.
2376 // Because there are no channels from payee, it will not have a dist entry at this point.
2377 // If we're processing any other node, it is always be the result of a channel from it.
2378 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2379 fee_to_target_msat = 0;
2380 next_hops_path_htlc_minimum_msat = 0;
2381 next_hops_path_penalty_msat = 0;
2386 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
2387 for details in first_channels {
2388 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2389 details, payer_node_id: &our_node_id,
2391 add_entry!(&candidate, fee_to_target_msat,
2392 $next_hops_value_contribution,
2393 next_hops_path_htlc_minimum_msat, next_hops_path_penalty_msat,
2394 $next_hops_cltv_delta, $next_hops_path_length);
2398 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2401 &default_node_features
2404 if !features.requires_unknown_bits() {
2405 for chan_id in $node.channels.iter() {
2406 let chan = network_channels.get(chan_id).unwrap();
2407 if !chan.features.requires_unknown_bits() {
2408 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2409 if first_hops.is_none() || *source != our_node_id {
2410 if directed_channel.direction().enabled {
2411 let candidate = CandidateRouteHop::PublicHop(PublicHopCandidate {
2412 info: directed_channel,
2413 short_channel_id: *chan_id,
2415 add_entry!(&candidate,
2417 $next_hops_value_contribution,
2418 next_hops_path_htlc_minimum_msat,
2419 next_hops_path_penalty_msat,
2420 $next_hops_cltv_delta, $next_hops_path_length);
2431 let mut payment_paths = Vec::<PaymentPath>::new();
2433 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2434 'paths_collection: loop {
2435 // For every new path, start from scratch, except for used_liquidities, which
2436 // helps to avoid reusing previously selected paths in future iterations.
2439 hit_minimum_limit = false;
2441 // If first hop is a private channel and the only way to reach the payee, this is the only
2442 // place where it could be added.
2443 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2444 for details in first_channels {
2445 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2446 details, payer_node_id: &our_node_id,
2448 let added = add_entry!(&candidate, 0, path_value_msat,
2449 0, 0u64, 0, 0).is_some();
2450 log_trace!(logger, "{} direct route to payee via {}",
2451 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2455 // Add the payee as a target, so that the payee-to-payer
2456 // search algorithm knows what to start with.
2457 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2458 // The payee is not in our network graph, so nothing to add here.
2459 // There is still a chance of reaching them via last_hops though,
2460 // so don't yet fail the payment here.
2461 // If not, targets.pop() will not even let us enter the loop in step 2.
2464 add_entries_to_cheapest_to_target_node!(node, payee, path_value_msat, 0, 0);
2469 // If a caller provided us with last hops, add them to routing targets. Since this happens
2470 // earlier than general path finding, they will be somewhat prioritized, although currently
2471 // it matters only if the fees are exactly the same.
2472 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2473 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2474 let have_intro_node_in_graph =
2475 // Only add the hops in this route to our candidate set if either
2476 // we have a direct channel to the first hop or the first hop is
2477 // in the regular network graph.
2478 first_hop_targets.get(&intro_node_id).is_some() ||
2479 network_nodes.get(&intro_node_id).is_some();
2480 if !have_intro_node_in_graph || our_node_id == intro_node_id { continue }
2481 let candidate = if hint.1.blinded_hops.len() == 1 {
2482 CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, hint_idx })
2483 } else { CandidateRouteHop::Blinded(BlindedPathCandidate { hint, hint_idx }) };
2484 let mut path_contribution_msat = path_value_msat;
2485 if let Some(hop_used_msat) = add_entry!(&candidate,
2486 0, path_contribution_msat, 0, 0_u64, 0, 0)
2488 path_contribution_msat = hop_used_msat;
2490 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2491 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2493 for details in first_channels {
2494 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2495 details, payer_node_id: &our_node_id,
2497 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2501 let path_min = candidate.htlc_minimum_msat().saturating_add(
2502 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2503 add_entry!(&first_hop_candidate, blinded_path_fee,
2504 path_contribution_msat, path_min, 0_u64, candidate.cltv_expiry_delta(),
2505 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2509 for route in payment_params.payee.unblinded_route_hints().iter()
2510 .filter(|route| !route.0.is_empty())
2512 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2513 let first_hop_src_is_reachable =
2514 // Only add the hops in this route to our candidate set if either we are part of
2515 // the first hop, we have a direct channel to the first hop, or the first hop is in
2516 // the regular network graph.
2517 our_node_id == first_hop_src_id ||
2518 first_hop_targets.get(&first_hop_src_id).is_some() ||
2519 network_nodes.get(&first_hop_src_id).is_some();
2520 if first_hop_src_is_reachable {
2521 // We start building the path from reverse, i.e., from payee
2522 // to the first RouteHintHop in the path.
2523 let hop_iter = route.0.iter().rev();
2524 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2525 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2526 let mut hop_used = true;
2527 let mut aggregate_next_hops_fee_msat: u64 = 0;
2528 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2529 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2530 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2531 let mut aggregate_next_hops_path_length: u8 = 0;
2532 let mut aggregate_path_contribution_msat = path_value_msat;
2534 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2535 let target = private_hop_key_cache.get(&prev_hop_id).unwrap();
2537 if let Some(first_channels) = first_hop_targets.get(&target) {
2538 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2539 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2540 hop.short_channel_id);
2545 let candidate = network_channels
2546 .get(&hop.short_channel_id)
2547 .and_then(|channel| channel.as_directed_to(&target))
2548 .map(|(info, _)| CandidateRouteHop::PublicHop(PublicHopCandidate {
2550 short_channel_id: hop.short_channel_id,
2552 .unwrap_or_else(|| CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: hop, target_node_id: target }));
2554 if let Some(hop_used_msat) = add_entry!(&candidate,
2555 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2556 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2557 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2559 aggregate_path_contribution_msat = hop_used_msat;
2561 // If this hop was not used then there is no use checking the preceding
2562 // hops in the RouteHint. We can break by just searching for a direct
2563 // channel between last checked hop and first_hop_targets.
2567 let used_liquidity_msat = used_liquidities
2568 .get(&candidate.id()).copied()
2570 let channel_usage = ChannelUsage {
2571 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2572 inflight_htlc_msat: used_liquidity_msat,
2573 effective_capacity: candidate.effective_capacity(),
2575 let channel_penalty_msat = scorer.channel_penalty_msat(
2576 &candidate, channel_usage, score_params
2578 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2579 .saturating_add(channel_penalty_msat);
2581 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2582 .saturating_add(hop.cltv_expiry_delta as u32);
2584 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2587 // Searching for a direct channel between last checked hop and first_hop_targets
2588 if let Some(first_channels) = first_hop_targets.get_mut(&target) {
2589 sort_first_hop_channels(first_channels, &used_liquidities,
2590 recommended_value_msat, our_node_pubkey);
2591 for details in first_channels {
2592 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2593 details, payer_node_id: &our_node_id,
2595 add_entry!(&first_hop_candidate,
2596 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2597 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2598 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2606 // In the next values of the iterator, the aggregate fees already reflects
2607 // the sum of value sent from payer (final_value_msat) and routing fees
2608 // for the last node in the RouteHint. We need to just add the fees to
2609 // route through the current node so that the preceding node (next iteration)
2611 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2612 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2613 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2615 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2616 // this route hint's source node to forward said min over this channel.
2617 aggregate_next_hops_path_htlc_minimum_msat = {
2618 let curr_htlc_min = cmp::max(
2619 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2621 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2622 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2625 if idx == route.0.len() - 1 {
2626 // The last hop in this iterator is the first hop in
2627 // overall RouteHint.
2628 // If this hop connects to a node with which we have a direct channel,
2629 // ignore the network graph and, if the last hop was added, add our
2630 // direct channel to the candidate set.
2632 // Note that we *must* check if the last hop was added as `add_entry`
2633 // always assumes that the third argument is a node to which we have a
2635 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2636 sort_first_hop_channels(first_channels, &used_liquidities,
2637 recommended_value_msat, our_node_pubkey);
2638 for details in first_channels {
2639 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2640 details, payer_node_id: &our_node_id,
2642 add_entry!(&first_hop_candidate,
2643 aggregate_next_hops_fee_msat,
2644 aggregate_path_contribution_msat,
2645 aggregate_next_hops_path_htlc_minimum_msat,
2646 aggregate_next_hops_path_penalty_msat,
2647 aggregate_next_hops_cltv_delta,
2648 aggregate_next_hops_path_length);
2656 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2658 // At this point, targets are filled with the data from first and
2659 // last hops communicated by the caller, and the payment receiver.
2660 let mut found_new_path = false;
2663 // If this loop terminates due the exhaustion of targets, two situations are possible:
2664 // - not enough outgoing liquidity:
2665 // 0 < already_collected_value_msat < final_value_msat
2666 // - enough outgoing liquidity:
2667 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2668 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2669 // paths_collection will be stopped because found_new_path==false.
2670 // This is not necessarily a routing failure.
2671 'path_construction: while let Some(RouteGraphNode { node_id, total_cltv_delta, mut value_contribution_msat, path_length_to_node, .. }) = targets.pop() {
2673 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2674 // traversing the graph and arrange the path out of what we found.
2675 if node_id == our_node_id {
2676 let mut new_entry = dist.remove(&our_node_id).unwrap();
2677 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2680 let mut features_set = false;
2681 let target = ordered_hops.last().unwrap().0.candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2682 if let Some(first_channels) = first_hop_targets.get(&target) {
2683 for details in first_channels {
2684 if let CandidateRouteHop::FirstHop(FirstHopCandidate { details: last_hop_details, .. })
2685 = ordered_hops.last().unwrap().0.candidate
2687 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2688 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2689 features_set = true;
2696 if let Some(node) = network_nodes.get(&target) {
2697 if let Some(node_info) = node.announcement_info.as_ref() {
2698 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2700 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2703 // We can fill in features for everything except hops which were
2704 // provided via the invoice we're paying. We could guess based on the
2705 // recipient's features but for now we simply avoid guessing at all.
2709 // Means we succesfully traversed from the payer to the payee, now
2710 // save this path for the payment route. Also, update the liquidity
2711 // remaining on the used hops, so that we take them into account
2712 // while looking for more paths.
2713 if target == maybe_dummy_payee_node_id {
2717 new_entry = match dist.remove(&target) {
2718 Some(payment_hop) => payment_hop,
2719 // We can't arrive at None because, if we ever add an entry to targets,
2720 // we also fill in the entry in dist (see add_entry!).
2721 None => unreachable!(),
2723 // We "propagate" the fees one hop backward (topologically) here,
2724 // so that fees paid for a HTLC forwarding on the current channel are
2725 // associated with the previous channel (where they will be subtracted).
2726 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2727 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2729 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2730 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2732 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2733 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2735 let mut payment_path = PaymentPath {hops: ordered_hops};
2737 // We could have possibly constructed a slightly inconsistent path: since we reduce
2738 // value being transferred along the way, we could have violated htlc_minimum_msat
2739 // on some channels we already passed (assuming dest->source direction). Here, we
2740 // recompute the fees again, so that if that's the case, we match the currently
2741 // underpaid htlc_minimum_msat with fees.
2742 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2743 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2744 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2746 // Since a path allows to transfer as much value as
2747 // the smallest channel it has ("bottleneck"), we should recompute
2748 // the fees so sender HTLC don't overpay fees when traversing
2749 // larger channels than the bottleneck. This may happen because
2750 // when we were selecting those channels we were not aware how much value
2751 // this path will transfer, and the relative fee for them
2752 // might have been computed considering a larger value.
2753 // Remember that we used these channels so that we don't rely
2754 // on the same liquidity in future paths.
2755 let mut prevented_redundant_path_selection = false;
2756 for (hop, _) in payment_path.hops.iter() {
2757 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2758 let used_liquidity_msat = used_liquidities
2759 .entry(hop.candidate.id())
2760 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2761 .or_insert(spent_on_hop_msat);
2762 let hop_capacity = hop.candidate.effective_capacity();
2763 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2764 if *used_liquidity_msat == hop_max_msat {
2765 // If this path used all of this channel's available liquidity, we know
2766 // this path will not be selected again in the next loop iteration.
2767 prevented_redundant_path_selection = true;
2769 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2771 if !prevented_redundant_path_selection {
2772 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2773 // we'll probably end up picking the same path again on the next iteration.
2774 // Decrease the available liquidity of a hop in the middle of the path.
2775 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2776 let exhausted = u64::max_value();
2778 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2779 LoggedCandidateHop(victim_candidate));
2780 if let Some(scid) = victim_candidate.short_channel_id() {
2781 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2782 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2786 // Track the total amount all our collected paths allow to send so that we know
2787 // when to stop looking for more paths
2788 already_collected_value_msat += value_contribution_msat;
2790 payment_paths.push(payment_path);
2791 found_new_path = true;
2792 break 'path_construction;
2795 // If we found a path back to the payee, we shouldn't try to process it again. This is
2796 // the equivalent of the `elem.was_processed` check in
2797 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2798 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2800 // Otherwise, since the current target node is not us,
2801 // keep "unrolling" the payment graph from payee to payer by
2802 // finding a way to reach the current target from the payer side.
2803 match network_nodes.get(&node_id) {
2806 add_entries_to_cheapest_to_target_node!(node, node_id,
2807 value_contribution_msat,
2808 total_cltv_delta, path_length_to_node);
2814 if !found_new_path && channel_saturation_pow_half != 0 {
2815 channel_saturation_pow_half = 0;
2816 continue 'paths_collection;
2818 // If we don't support MPP, no use trying to gather more value ever.
2819 break 'paths_collection;
2823 // Stop either when the recommended value is reached or if no new path was found in this
2825 // In the latter case, making another path finding attempt won't help,
2826 // because we deterministically terminated the search due to low liquidity.
2827 if !found_new_path && channel_saturation_pow_half != 0 {
2828 channel_saturation_pow_half = 0;
2829 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2830 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
2831 path_value_msat = recommended_value_msat;
2832 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2833 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2834 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2835 break 'paths_collection;
2836 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2837 // Further, if this was our first walk of the graph, and we weren't limited by an
2838 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2839 // limited by an htlc_minimum_msat value, find another path with a higher value,
2840 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2841 // still keeping a lower total fee than this path.
2842 if !hit_minimum_limit {
2843 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2844 break 'paths_collection;
2846 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.");
2847 path_value_msat = recommended_value_msat;
2851 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2852 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
2853 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
2854 num_ignored_total_fee_limit;
2855 if num_ignored_total > 0 {
2857 "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.",
2858 num_ignored_value_contribution, num_ignored_path_length_limit,
2859 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
2860 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
2861 num_ignored_total_fee_limit, num_ignored_total);
2865 if payment_paths.len() == 0 {
2866 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2869 if already_collected_value_msat < final_value_msat {
2870 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2874 let mut selected_route = payment_paths;
2876 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2877 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2879 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2880 // the value they contribute towards the payment amount.
2881 // We sort in descending order as we will remove from the front in `retain`, next.
2882 selected_route.sort_unstable_by(|a, b|
2883 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2884 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2887 // We should make sure that at least 1 path left.
2888 let mut paths_left = selected_route.len();
2889 selected_route.retain(|path| {
2890 if paths_left == 1 {
2893 let path_value_msat = path.get_value_msat();
2894 if path_value_msat <= overpaid_value_msat {
2895 overpaid_value_msat -= path_value_msat;
2901 debug_assert!(selected_route.len() > 0);
2903 if overpaid_value_msat != 0 {
2905 // Now, subtract the remaining overpaid value from the most-expensive path.
2906 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2907 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2908 selected_route.sort_unstable_by(|a, b| {
2909 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2910 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2911 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2913 let expensive_payment_path = selected_route.first_mut().unwrap();
2915 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2916 // can't go negative.
2917 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2918 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2922 // Sort by the path itself and combine redundant paths.
2923 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2924 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2926 selected_route.sort_unstable_by_key(|path| {
2927 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2928 debug_assert!(path.hops.len() <= key.len());
2929 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
2934 for idx in 0..(selected_route.len() - 1) {
2935 if idx + 1 >= selected_route.len() { break; }
2936 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
2937 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
2938 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2939 selected_route[idx].update_value_and_recompute_fees(new_value);
2940 selected_route.remove(idx + 1);
2944 let mut paths = Vec::new();
2945 for payment_path in selected_route {
2946 let mut hops = Vec::with_capacity(payment_path.hops.len());
2947 for (hop, node_features) in payment_path.hops.iter()
2948 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2950 let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
2951 let maybe_announced_channel = if let CandidateRouteHop::PublicHop(_) = hop.candidate {
2952 // If we sourced the hop from the graph we're sure the target node is announced.
2954 } else if let CandidateRouteHop::FirstHop(first_hop) = &hop.candidate {
2955 // If this is a first hop we also know if it's announced.
2956 first_hop.details.is_public
2958 // If we sourced it any other way, we double-check the network graph to see if
2959 // there are announced channels between the endpoints. If so, the hop might be
2960 // referring to any of the announced channels, as its `short_channel_id` might be
2961 // an alias, in which case we don't take any chances here.
2962 network_graph.node(&target).map_or(false, |hop_node|
2963 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
2964 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
2968 hops.push(RouteHop {
2969 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
2970 node_features: node_features.clone(),
2971 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2972 channel_features: hop.candidate.features(),
2973 fee_msat: hop.fee_msat,
2974 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2975 maybe_announced_channel,
2978 let mut final_cltv_delta = final_cltv_expiry_delta;
2979 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2980 if let Some(blinded_path) = h.candidate.blinded_path() {
2981 final_cltv_delta = h.candidate.cltv_expiry_delta();
2983 hops: blinded_path.blinded_hops.clone(),
2984 blinding_point: blinded_path.blinding_point,
2985 excess_final_cltv_expiry_delta: 0,
2986 final_value_msat: h.fee_msat,
2990 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2991 // applicable for the previous hop.
2992 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2993 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2996 paths.push(Path { hops, blinded_tail });
2998 // Make sure we would never create a route with more paths than we allow.
2999 debug_assert!(paths.len() <= payment_params.max_path_count.into());
3001 if let Some(node_features) = payment_params.payee.node_features() {
3002 for path in paths.iter_mut() {
3003 path.hops.last_mut().unwrap().node_features = node_features.clone();
3007 let route = Route { paths, route_params: Some(route_params.clone()) };
3009 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
3010 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
3011 if route.get_total_fees() > max_total_routing_fee_msat {
3012 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
3013 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
3017 log_info!(logger, "Got route: {}", log_route!(route));
3021 // When an adversarial intermediary node observes a payment, it may be able to infer its
3022 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
3023 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
3024 // payment path by adding a randomized 'shadow route' offset to the final hop.
3025 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
3026 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
3028 let network_channels = network_graph.channels();
3029 let network_nodes = network_graph.nodes();
3031 for path in route.paths.iter_mut() {
3032 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
3034 // Remember the last three nodes of the random walk and avoid looping back on them.
3035 // Init with the last three nodes from the actual path, if possible.
3036 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
3037 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
3038 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
3040 // Choose the last publicly known node as the starting point for the random walk.
3041 let mut cur_hop: Option<NodeId> = None;
3042 let mut path_nonce = [0u8; 12];
3043 if let Some(starting_hop) = path.hops.iter().rev()
3044 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
3045 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
3046 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
3049 // Init PRNG with the path-dependant nonce, which is static for private paths.
3050 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
3051 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
3053 // Pick a random path length in [1 .. 3]
3054 prng.process_in_place(&mut random_path_bytes);
3055 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
3057 for random_hop in 0..random_walk_length {
3058 // If we don't find a suitable offset in the public network graph, we default to
3059 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3060 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
3062 if let Some(cur_node_id) = cur_hop {
3063 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
3064 // Randomly choose the next unvisited hop.
3065 prng.process_in_place(&mut random_path_bytes);
3066 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
3067 .checked_rem(cur_node.channels.len())
3068 .and_then(|index| cur_node.channels.get(index))
3069 .and_then(|id| network_channels.get(id)) {
3070 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
3071 if !nodes_to_avoid.iter().any(|x| x == next_id) {
3072 nodes_to_avoid[random_hop] = *next_id;
3073 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
3074 cur_hop = Some(*next_id);
3081 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
3082 .checked_add(random_hop_offset)
3083 .unwrap_or(shadow_ctlv_expiry_delta_offset);
3086 // Limit the total offset to reduce the worst-case locked liquidity timevalue
3087 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
3088 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
3090 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
3091 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3092 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
3093 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
3094 max_path_offset = cmp::max(
3095 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
3096 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
3097 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
3099 // Add 'shadow' CLTV offset to the final hop
3100 if let Some(tail) = path.blinded_tail.as_mut() {
3101 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
3102 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
3104 if let Some(last_hop) = path.hops.last_mut() {
3105 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
3106 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
3111 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
3112 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
3114 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
3115 pub fn build_route_from_hops<L: Deref, GL: Deref>(
3116 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3117 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
3118 ) -> Result<Route, LightningError>
3119 where L::Target: Logger, GL::Target: Logger {
3120 let graph_lock = network_graph.read_only();
3121 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
3122 &graph_lock, logger, random_seed_bytes)?;
3123 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
3127 fn build_route_from_hops_internal<L: Deref>(
3128 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3129 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
3130 ) -> Result<Route, LightningError> where L::Target: Logger {
3133 our_node_id: NodeId,
3134 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
3137 impl ScoreLookUp for HopScorer {
3138 type ScoreParams = ();
3139 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
3140 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
3142 let mut cur_id = self.our_node_id;
3143 for i in 0..self.hop_ids.len() {
3144 if let Some(next_id) = self.hop_ids[i] {
3145 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
3157 impl<'a> Writeable for HopScorer {
3159 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
3164 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
3165 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
3168 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
3169 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
3170 for i in 0..hops.len() {
3171 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
3174 let scorer = HopScorer { our_node_id, hop_ids };
3176 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
3181 use crate::blinded_path::{BlindedHop, BlindedPath};
3182 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
3183 use crate::routing::utxo::UtxoResult;
3184 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
3185 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
3186 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop, PublicHopCandidate};
3187 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
3188 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
3189 use crate::chain::transaction::OutPoint;
3190 use crate::sign::EntropySource;
3191 use crate::ln::ChannelId;
3192 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
3193 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
3194 use crate::ln::channelmanager;
3195 use crate::offers::invoice::BlindedPayInfo;
3196 use crate::util::config::UserConfig;
3197 use crate::util::test_utils as ln_test_utils;
3198 use crate::util::chacha20::ChaCha20;
3199 use crate::util::ser::{Readable, Writeable};
3201 use crate::util::ser::Writer;
3203 use bitcoin::hashes::Hash;
3204 use bitcoin::network::constants::Network;
3205 use bitcoin::blockdata::constants::ChainHash;
3206 use bitcoin::blockdata::script::Builder;
3207 use bitcoin::blockdata::opcodes;
3208 use bitcoin::blockdata::transaction::TxOut;
3209 use bitcoin::hashes::hex::FromHex;
3210 use bitcoin::secp256k1::{PublicKey,SecretKey};
3211 use bitcoin::secp256k1::Secp256k1;
3213 use crate::io::Cursor;
3214 use crate::prelude::*;
3215 use crate::sync::Arc;
3217 use core::convert::TryInto;
3219 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3220 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
3221 channelmanager::ChannelDetails {
3222 channel_id: ChannelId::new_zero(),
3223 counterparty: channelmanager::ChannelCounterparty {
3226 unspendable_punishment_reserve: 0,
3227 forwarding_info: None,
3228 outbound_htlc_minimum_msat: None,
3229 outbound_htlc_maximum_msat: None,
3231 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3234 outbound_scid_alias: None,
3235 inbound_scid_alias: None,
3236 channel_value_satoshis: 0,
3239 outbound_capacity_msat,
3240 next_outbound_htlc_limit_msat: outbound_capacity_msat,
3241 next_outbound_htlc_minimum_msat: 0,
3242 inbound_capacity_msat: 42,
3243 unspendable_punishment_reserve: None,
3244 confirmations_required: None,
3245 confirmations: None,
3246 force_close_spend_delay: None,
3247 is_outbound: true, is_channel_ready: true,
3248 is_usable: true, is_public: true,
3249 inbound_htlc_minimum_msat: None,
3250 inbound_htlc_maximum_msat: None,
3252 feerate_sat_per_1000_weight: None,
3253 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
3258 fn simple_route_test() {
3259 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3260 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3261 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3262 let scorer = ln_test_utils::TestScorer::new();
3263 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3264 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3266 // Simple route to 2 via 1
3268 let route_params = RouteParameters::from_payment_params_and_value(
3269 payment_params.clone(), 0);
3270 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3271 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3272 &Default::default(), &random_seed_bytes) {
3273 assert_eq!(err, "Cannot send a payment of 0 msat");
3274 } else { panic!(); }
3276 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3277 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3278 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3279 assert_eq!(route.paths[0].hops.len(), 2);
3281 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3282 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3283 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3284 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3285 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3286 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3288 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3289 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3290 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3291 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3292 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3293 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3297 fn invalid_first_hop_test() {
3298 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3299 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3300 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3301 let scorer = ln_test_utils::TestScorer::new();
3302 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3303 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3305 // Simple route to 2 via 1
3307 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3309 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3310 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3311 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3312 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3313 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3314 } else { panic!(); }
3316 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3317 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3318 assert_eq!(route.paths[0].hops.len(), 2);
3322 fn htlc_minimum_test() {
3323 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3324 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3325 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3326 let scorer = ln_test_utils::TestScorer::new();
3327 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3328 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3330 // Simple route to 2 via 1
3332 // Disable other paths
3333 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3334 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3335 short_channel_id: 12,
3337 flags: 2, // to disable
3338 cltv_expiry_delta: 0,
3339 htlc_minimum_msat: 0,
3340 htlc_maximum_msat: MAX_VALUE_MSAT,
3342 fee_proportional_millionths: 0,
3343 excess_data: Vec::new()
3345 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3346 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3347 short_channel_id: 3,
3349 flags: 2, // to disable
3350 cltv_expiry_delta: 0,
3351 htlc_minimum_msat: 0,
3352 htlc_maximum_msat: MAX_VALUE_MSAT,
3354 fee_proportional_millionths: 0,
3355 excess_data: Vec::new()
3357 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3358 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3359 short_channel_id: 13,
3361 flags: 2, // to disable
3362 cltv_expiry_delta: 0,
3363 htlc_minimum_msat: 0,
3364 htlc_maximum_msat: MAX_VALUE_MSAT,
3366 fee_proportional_millionths: 0,
3367 excess_data: Vec::new()
3369 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3370 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3371 short_channel_id: 6,
3373 flags: 2, // to disable
3374 cltv_expiry_delta: 0,
3375 htlc_minimum_msat: 0,
3376 htlc_maximum_msat: MAX_VALUE_MSAT,
3378 fee_proportional_millionths: 0,
3379 excess_data: Vec::new()
3381 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3382 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3383 short_channel_id: 7,
3385 flags: 2, // to disable
3386 cltv_expiry_delta: 0,
3387 htlc_minimum_msat: 0,
3388 htlc_maximum_msat: MAX_VALUE_MSAT,
3390 fee_proportional_millionths: 0,
3391 excess_data: Vec::new()
3394 // Check against amount_to_transfer_over_msat.
3395 // Set minimal HTLC of 200_000_000 msat.
3396 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3397 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3398 short_channel_id: 2,
3401 cltv_expiry_delta: 0,
3402 htlc_minimum_msat: 200_000_000,
3403 htlc_maximum_msat: MAX_VALUE_MSAT,
3405 fee_proportional_millionths: 0,
3406 excess_data: Vec::new()
3409 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3411 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3412 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3413 short_channel_id: 4,
3416 cltv_expiry_delta: 0,
3417 htlc_minimum_msat: 0,
3418 htlc_maximum_msat: 199_999_999,
3420 fee_proportional_millionths: 0,
3421 excess_data: Vec::new()
3424 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3425 let route_params = RouteParameters::from_payment_params_and_value(
3426 payment_params, 199_999_999);
3427 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3428 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3429 &Default::default(), &random_seed_bytes) {
3430 assert_eq!(err, "Failed to find a path to the given destination");
3431 } else { panic!(); }
3433 // Lift the restriction on the first hop.
3434 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3435 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3436 short_channel_id: 2,
3439 cltv_expiry_delta: 0,
3440 htlc_minimum_msat: 0,
3441 htlc_maximum_msat: MAX_VALUE_MSAT,
3443 fee_proportional_millionths: 0,
3444 excess_data: Vec::new()
3447 // A payment above the minimum should pass
3448 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3449 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3450 assert_eq!(route.paths[0].hops.len(), 2);
3454 fn htlc_minimum_overpay_test() {
3455 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3456 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3457 let config = UserConfig::default();
3458 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3459 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3461 let scorer = ln_test_utils::TestScorer::new();
3462 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3463 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3465 // A route to node#2 via two paths.
3466 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3467 // Thus, they can't send 60 without overpaying.
3468 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3469 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3470 short_channel_id: 2,
3473 cltv_expiry_delta: 0,
3474 htlc_minimum_msat: 35_000,
3475 htlc_maximum_msat: 40_000,
3477 fee_proportional_millionths: 0,
3478 excess_data: Vec::new()
3480 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3481 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3482 short_channel_id: 12,
3485 cltv_expiry_delta: 0,
3486 htlc_minimum_msat: 35_000,
3487 htlc_maximum_msat: 40_000,
3489 fee_proportional_millionths: 0,
3490 excess_data: Vec::new()
3494 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3495 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3496 short_channel_id: 13,
3499 cltv_expiry_delta: 0,
3500 htlc_minimum_msat: 0,
3501 htlc_maximum_msat: MAX_VALUE_MSAT,
3503 fee_proportional_millionths: 0,
3504 excess_data: Vec::new()
3506 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3507 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3508 short_channel_id: 4,
3511 cltv_expiry_delta: 0,
3512 htlc_minimum_msat: 0,
3513 htlc_maximum_msat: MAX_VALUE_MSAT,
3515 fee_proportional_millionths: 0,
3516 excess_data: Vec::new()
3519 // Disable other paths
3520 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3521 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3522 short_channel_id: 1,
3524 flags: 2, // to disable
3525 cltv_expiry_delta: 0,
3526 htlc_minimum_msat: 0,
3527 htlc_maximum_msat: MAX_VALUE_MSAT,
3529 fee_proportional_millionths: 0,
3530 excess_data: Vec::new()
3533 let mut route_params = RouteParameters::from_payment_params_and_value(
3534 payment_params.clone(), 60_000);
3535 route_params.max_total_routing_fee_msat = Some(15_000);
3536 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3537 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3538 // Overpay fees to hit htlc_minimum_msat.
3539 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3540 // TODO: this could be better balanced to overpay 10k and not 15k.
3541 assert_eq!(overpaid_fees, 15_000);
3543 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3544 // while taking even more fee to match htlc_minimum_msat.
3545 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3546 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3547 short_channel_id: 12,
3550 cltv_expiry_delta: 0,
3551 htlc_minimum_msat: 65_000,
3552 htlc_maximum_msat: 80_000,
3554 fee_proportional_millionths: 0,
3555 excess_data: Vec::new()
3557 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3558 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3559 short_channel_id: 2,
3562 cltv_expiry_delta: 0,
3563 htlc_minimum_msat: 0,
3564 htlc_maximum_msat: MAX_VALUE_MSAT,
3566 fee_proportional_millionths: 0,
3567 excess_data: Vec::new()
3569 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3570 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3571 short_channel_id: 4,
3574 cltv_expiry_delta: 0,
3575 htlc_minimum_msat: 0,
3576 htlc_maximum_msat: MAX_VALUE_MSAT,
3578 fee_proportional_millionths: 100_000,
3579 excess_data: Vec::new()
3582 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3583 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3584 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3585 assert_eq!(route.paths.len(), 1);
3586 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3587 let fees = route.paths[0].hops[0].fee_msat;
3588 assert_eq!(fees, 5_000);
3590 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3591 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3592 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3593 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3594 // the other channel.
3595 assert_eq!(route.paths.len(), 1);
3596 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3597 let fees = route.paths[0].hops[0].fee_msat;
3598 assert_eq!(fees, 5_000);
3602 fn htlc_minimum_recipient_overpay_test() {
3603 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3604 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3605 let config = UserConfig::default();
3606 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3607 let scorer = ln_test_utils::TestScorer::new();
3608 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3609 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3611 // Route to node2 over a single path which requires overpaying the recipient themselves.
3613 // First disable all paths except the us -> node1 -> node2 path
3614 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3615 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3616 short_channel_id: 13,
3619 cltv_expiry_delta: 0,
3620 htlc_minimum_msat: 0,
3621 htlc_maximum_msat: 0,
3623 fee_proportional_millionths: 0,
3624 excess_data: Vec::new()
3627 // Set channel 4 to free but with a high htlc_minimum_msat
3628 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3629 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3630 short_channel_id: 4,
3633 cltv_expiry_delta: 0,
3634 htlc_minimum_msat: 15_000,
3635 htlc_maximum_msat: MAX_VALUE_MSAT,
3637 fee_proportional_millionths: 0,
3638 excess_data: Vec::new()
3641 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3642 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3643 // what we try to find a route for, so this test only just happens to work out to exactly
3645 let mut route_params = RouteParameters::from_payment_params_and_value(
3646 payment_params.clone(), 5_000);
3647 route_params.max_total_routing_fee_msat = Some(9_999);
3648 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3649 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3650 &Default::default(), &random_seed_bytes) {
3651 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3652 } else { panic!(); }
3654 let mut route_params = RouteParameters::from_payment_params_and_value(
3655 payment_params.clone(), 5_000);
3656 route_params.max_total_routing_fee_msat = Some(10_000);
3657 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3658 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3659 assert_eq!(route.get_total_fees(), 10_000);
3663 fn disable_channels_test() {
3664 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3665 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3666 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3667 let scorer = ln_test_utils::TestScorer::new();
3668 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3669 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3671 // // Disable channels 4 and 12 by flags=2
3672 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3673 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3674 short_channel_id: 4,
3676 flags: 2, // to disable
3677 cltv_expiry_delta: 0,
3678 htlc_minimum_msat: 0,
3679 htlc_maximum_msat: MAX_VALUE_MSAT,
3681 fee_proportional_millionths: 0,
3682 excess_data: Vec::new()
3684 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3685 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3686 short_channel_id: 12,
3688 flags: 2, // to disable
3689 cltv_expiry_delta: 0,
3690 htlc_minimum_msat: 0,
3691 htlc_maximum_msat: MAX_VALUE_MSAT,
3693 fee_proportional_millionths: 0,
3694 excess_data: Vec::new()
3697 // If all the channels require some features we don't understand, route should fail
3698 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3699 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3700 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3701 &Default::default(), &random_seed_bytes) {
3702 assert_eq!(err, "Failed to find a path to the given destination");
3703 } else { panic!(); }
3705 // If we specify a channel to node7, that overrides our local channel view and that gets used
3706 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3707 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3708 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3709 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3710 &Default::default(), &random_seed_bytes).unwrap();
3711 assert_eq!(route.paths[0].hops.len(), 2);
3713 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3714 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3715 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3716 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3717 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3718 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3720 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3721 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3722 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3723 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3724 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3725 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3729 fn disable_node_test() {
3730 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3731 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3732 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3733 let scorer = ln_test_utils::TestScorer::new();
3734 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3735 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3737 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3738 let mut unknown_features = NodeFeatures::empty();
3739 unknown_features.set_unknown_feature_required();
3740 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3741 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3742 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3744 // If all nodes require some features we don't understand, route should fail
3745 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3746 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3747 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3748 &Default::default(), &random_seed_bytes) {
3749 assert_eq!(err, "Failed to find a path to the given destination");
3750 } else { panic!(); }
3752 // If we specify a channel to node7, that overrides our local channel view and that gets used
3753 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3754 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3755 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3756 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3757 &Default::default(), &random_seed_bytes).unwrap();
3758 assert_eq!(route.paths[0].hops.len(), 2);
3760 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3761 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3762 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3763 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3764 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3765 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3767 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3768 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3769 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3770 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3771 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3772 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3774 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3775 // naively) assume that the user checked the feature bits on the invoice, which override
3776 // the node_announcement.
3780 fn our_chans_test() {
3781 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3782 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3783 let scorer = ln_test_utils::TestScorer::new();
3784 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3785 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3787 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3788 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3789 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3790 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3791 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3792 assert_eq!(route.paths[0].hops.len(), 3);
3794 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3795 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3796 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3797 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3798 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3799 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3801 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3802 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3803 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3804 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3805 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3806 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3808 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3809 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3810 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3811 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3812 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3813 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3815 // If we specify a channel to node7, that overrides our local channel view and that gets used
3816 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3817 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3818 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3819 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3820 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3821 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3822 &Default::default(), &random_seed_bytes).unwrap();
3823 assert_eq!(route.paths[0].hops.len(), 2);
3825 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3826 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3827 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3828 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3829 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3830 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3832 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3833 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3834 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3835 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3836 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3837 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3840 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3841 let zero_fees = RoutingFees {
3843 proportional_millionths: 0,
3845 vec![RouteHint(vec![RouteHintHop {
3846 src_node_id: nodes[3],
3847 short_channel_id: 8,
3849 cltv_expiry_delta: (8 << 4) | 1,
3850 htlc_minimum_msat: None,
3851 htlc_maximum_msat: None,
3853 ]), RouteHint(vec![RouteHintHop {
3854 src_node_id: nodes[4],
3855 short_channel_id: 9,
3858 proportional_millionths: 0,
3860 cltv_expiry_delta: (9 << 4) | 1,
3861 htlc_minimum_msat: None,
3862 htlc_maximum_msat: None,
3863 }]), RouteHint(vec![RouteHintHop {
3864 src_node_id: nodes[5],
3865 short_channel_id: 10,
3867 cltv_expiry_delta: (10 << 4) | 1,
3868 htlc_minimum_msat: None,
3869 htlc_maximum_msat: None,
3873 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3874 let zero_fees = RoutingFees {
3876 proportional_millionths: 0,
3878 vec![RouteHint(vec![RouteHintHop {
3879 src_node_id: nodes[2],
3880 short_channel_id: 5,
3883 proportional_millionths: 0,
3885 cltv_expiry_delta: (5 << 4) | 1,
3886 htlc_minimum_msat: None,
3887 htlc_maximum_msat: None,
3889 src_node_id: nodes[3],
3890 short_channel_id: 8,
3892 cltv_expiry_delta: (8 << 4) | 1,
3893 htlc_minimum_msat: None,
3894 htlc_maximum_msat: None,
3896 ]), RouteHint(vec![RouteHintHop {
3897 src_node_id: nodes[4],
3898 short_channel_id: 9,
3901 proportional_millionths: 0,
3903 cltv_expiry_delta: (9 << 4) | 1,
3904 htlc_minimum_msat: None,
3905 htlc_maximum_msat: None,
3906 }]), RouteHint(vec![RouteHintHop {
3907 src_node_id: nodes[5],
3908 short_channel_id: 10,
3910 cltv_expiry_delta: (10 << 4) | 1,
3911 htlc_minimum_msat: None,
3912 htlc_maximum_msat: None,
3917 fn partial_route_hint_test() {
3918 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3919 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3920 let scorer = ln_test_utils::TestScorer::new();
3921 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3922 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3924 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3925 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3926 // RouteHint may be partially used by the algo to build the best path.
3928 // First check that last hop can't have its source as the payee.
3929 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3930 src_node_id: nodes[6],
3931 short_channel_id: 8,
3934 proportional_millionths: 0,
3936 cltv_expiry_delta: (8 << 4) | 1,
3937 htlc_minimum_msat: None,
3938 htlc_maximum_msat: None,
3941 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3942 invalid_last_hops.push(invalid_last_hop);
3944 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3945 .with_route_hints(invalid_last_hops).unwrap();
3946 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3947 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3948 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3949 &Default::default(), &random_seed_bytes) {
3950 assert_eq!(err, "Route hint cannot have the payee as the source.");
3951 } else { panic!(); }
3954 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3955 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3956 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3957 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3958 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3959 assert_eq!(route.paths[0].hops.len(), 5);
3961 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3962 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3963 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3964 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3965 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3966 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3968 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3969 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3970 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3971 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3972 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3973 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3975 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3976 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3977 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3978 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3979 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3980 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3982 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3983 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3984 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3985 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3986 // If we have a peer in the node map, we'll use their features here since we don't have
3987 // a way of figuring out their features from the invoice:
3988 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3989 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3991 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3992 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3993 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3994 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3995 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3996 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3999 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4000 let zero_fees = RoutingFees {
4002 proportional_millionths: 0,
4004 vec![RouteHint(vec![RouteHintHop {
4005 src_node_id: nodes[3],
4006 short_channel_id: 8,
4008 cltv_expiry_delta: (8 << 4) | 1,
4009 htlc_minimum_msat: None,
4010 htlc_maximum_msat: None,
4011 }]), RouteHint(vec![
4013 ]), RouteHint(vec![RouteHintHop {
4014 src_node_id: nodes[5],
4015 short_channel_id: 10,
4017 cltv_expiry_delta: (10 << 4) | 1,
4018 htlc_minimum_msat: None,
4019 htlc_maximum_msat: None,
4024 fn ignores_empty_last_hops_test() {
4025 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4026 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4027 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
4028 let scorer = ln_test_utils::TestScorer::new();
4029 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4030 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4032 // Test handling of an empty RouteHint passed in Invoice.
4033 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4034 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4035 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4036 assert_eq!(route.paths[0].hops.len(), 5);
4038 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4039 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4040 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4041 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4042 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4043 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4045 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4046 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4047 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4048 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4049 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4050 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4052 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4053 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4054 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4055 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4056 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4057 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4059 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4060 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4061 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4062 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4063 // If we have a peer in the node map, we'll use their features here since we don't have
4064 // a way of figuring out their features from the invoice:
4065 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4066 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4068 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4069 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4070 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4071 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4072 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4073 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4076 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
4078 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
4079 let zero_fees = RoutingFees {
4081 proportional_millionths: 0,
4083 vec![RouteHint(vec![RouteHintHop {
4084 src_node_id: hint_hops[0],
4085 short_channel_id: 0xff00,
4088 proportional_millionths: 0,
4090 cltv_expiry_delta: (5 << 4) | 1,
4091 htlc_minimum_msat: None,
4092 htlc_maximum_msat: None,
4094 src_node_id: hint_hops[1],
4095 short_channel_id: 0xff01,
4097 cltv_expiry_delta: (8 << 4) | 1,
4098 htlc_minimum_msat: None,
4099 htlc_maximum_msat: None,
4104 fn multi_hint_last_hops_test() {
4105 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4106 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4107 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
4108 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4109 let scorer = ln_test_utils::TestScorer::new();
4110 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4111 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4112 // Test through channels 2, 3, 0xff00, 0xff01.
4113 // Test shows that multiple hop hints are considered.
4115 // Disabling channels 6 & 7 by flags=2
4116 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4117 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4118 short_channel_id: 6,
4120 flags: 2, // to disable
4121 cltv_expiry_delta: 0,
4122 htlc_minimum_msat: 0,
4123 htlc_maximum_msat: MAX_VALUE_MSAT,
4125 fee_proportional_millionths: 0,
4126 excess_data: Vec::new()
4128 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4129 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4130 short_channel_id: 7,
4132 flags: 2, // to disable
4133 cltv_expiry_delta: 0,
4134 htlc_minimum_msat: 0,
4135 htlc_maximum_msat: MAX_VALUE_MSAT,
4137 fee_proportional_millionths: 0,
4138 excess_data: Vec::new()
4141 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4142 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4143 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4144 assert_eq!(route.paths[0].hops.len(), 4);
4146 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4147 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4148 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4149 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4150 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4151 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4153 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4154 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4155 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4156 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4157 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4158 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4160 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4161 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4162 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4163 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4164 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4165 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4167 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4168 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4169 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4170 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4171 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4172 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4176 fn private_multi_hint_last_hops_test() {
4177 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4178 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4180 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4181 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4183 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4184 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4185 let scorer = ln_test_utils::TestScorer::new();
4186 // Test through channels 2, 3, 0xff00, 0xff01.
4187 // Test shows that multiple hop hints are considered.
4189 // Disabling channels 6 & 7 by flags=2
4190 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4191 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4192 short_channel_id: 6,
4194 flags: 2, // to disable
4195 cltv_expiry_delta: 0,
4196 htlc_minimum_msat: 0,
4197 htlc_maximum_msat: MAX_VALUE_MSAT,
4199 fee_proportional_millionths: 0,
4200 excess_data: Vec::new()
4202 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4203 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4204 short_channel_id: 7,
4206 flags: 2, // to disable
4207 cltv_expiry_delta: 0,
4208 htlc_minimum_msat: 0,
4209 htlc_maximum_msat: MAX_VALUE_MSAT,
4211 fee_proportional_millionths: 0,
4212 excess_data: Vec::new()
4215 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4216 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4217 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4218 assert_eq!(route.paths[0].hops.len(), 4);
4220 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4221 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4222 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4223 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4224 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4225 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4227 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4228 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4229 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4230 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4231 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4232 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4234 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4235 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4236 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4237 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4238 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4239 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4241 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4242 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4243 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4244 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4245 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4246 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4249 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4250 let zero_fees = RoutingFees {
4252 proportional_millionths: 0,
4254 vec![RouteHint(vec![RouteHintHop {
4255 src_node_id: nodes[4],
4256 short_channel_id: 11,
4258 cltv_expiry_delta: (11 << 4) | 1,
4259 htlc_minimum_msat: None,
4260 htlc_maximum_msat: None,
4262 src_node_id: nodes[3],
4263 short_channel_id: 8,
4265 cltv_expiry_delta: (8 << 4) | 1,
4266 htlc_minimum_msat: None,
4267 htlc_maximum_msat: None,
4268 }]), RouteHint(vec![RouteHintHop {
4269 src_node_id: nodes[4],
4270 short_channel_id: 9,
4273 proportional_millionths: 0,
4275 cltv_expiry_delta: (9 << 4) | 1,
4276 htlc_minimum_msat: None,
4277 htlc_maximum_msat: None,
4278 }]), RouteHint(vec![RouteHintHop {
4279 src_node_id: nodes[5],
4280 short_channel_id: 10,
4282 cltv_expiry_delta: (10 << 4) | 1,
4283 htlc_minimum_msat: None,
4284 htlc_maximum_msat: None,
4289 fn last_hops_with_public_channel_test() {
4290 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4291 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4292 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4293 let scorer = ln_test_utils::TestScorer::new();
4294 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4295 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4296 // This test shows that public routes can be present in the invoice
4297 // which would be handled in the same manner.
4299 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4300 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4301 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4302 assert_eq!(route.paths[0].hops.len(), 5);
4304 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4305 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4306 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4307 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4308 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4309 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4311 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4312 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4313 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4314 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4315 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4316 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4318 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4319 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4320 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4321 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4322 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4323 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4325 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4326 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4327 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4328 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4329 // If we have a peer in the node map, we'll use their features here since we don't have
4330 // a way of figuring out their features from the invoice:
4331 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4332 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4334 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4335 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4336 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4337 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4338 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4339 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4343 fn our_chans_last_hop_connect_test() {
4344 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4345 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4346 let scorer = ln_test_utils::TestScorer::new();
4347 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4348 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4350 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4351 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4352 let mut last_hops = last_hops(&nodes);
4353 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4354 .with_route_hints(last_hops.clone()).unwrap();
4355 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4356 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4357 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4358 &Default::default(), &random_seed_bytes).unwrap();
4359 assert_eq!(route.paths[0].hops.len(), 2);
4361 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4362 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4363 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4364 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4365 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4366 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4368 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4369 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4370 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4371 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4372 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4373 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4375 last_hops[0].0[0].fees.base_msat = 1000;
4377 // Revert to via 6 as the fee on 8 goes up
4378 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4379 .with_route_hints(last_hops).unwrap();
4380 let route_params = RouteParameters::from_payment_params_and_value(
4381 payment_params.clone(), 100);
4382 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4383 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4384 assert_eq!(route.paths[0].hops.len(), 4);
4386 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4387 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4388 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4389 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4390 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4391 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4393 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4394 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4395 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4396 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4397 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4398 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4400 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4401 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4402 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4403 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4404 // If we have a peer in the node map, we'll use their features here since we don't have
4405 // a way of figuring out their features from the invoice:
4406 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4407 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4409 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4410 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4411 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4412 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4413 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4414 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4416 // ...but still use 8 for larger payments as 6 has a variable feerate
4417 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4418 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4419 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4420 assert_eq!(route.paths[0].hops.len(), 5);
4422 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4423 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4424 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4425 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4426 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4427 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4429 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4430 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4431 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4432 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4433 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4434 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4436 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4437 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4438 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4439 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4440 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4441 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4443 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4444 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4445 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4446 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4447 // If we have a peer in the node map, we'll use their features here since we don't have
4448 // a way of figuring out their features from the invoice:
4449 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4450 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4452 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4453 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4454 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4455 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4456 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4457 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4460 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> {
4461 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4462 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4463 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4465 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4466 let last_hops = RouteHint(vec![RouteHintHop {
4467 src_node_id: middle_node_id,
4468 short_channel_id: 8,
4471 proportional_millionths: last_hop_fee_prop,
4473 cltv_expiry_delta: (8 << 4) | 1,
4474 htlc_minimum_msat: None,
4475 htlc_maximum_msat: last_hop_htlc_max,
4477 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4478 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4479 let scorer = ln_test_utils::TestScorer::new();
4480 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4481 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4482 let logger = ln_test_utils::TestLogger::new();
4483 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4484 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4485 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4486 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4487 &random_seed_bytes);
4492 fn unannounced_path_test() {
4493 // We should be able to send a payment to a destination without any help of a routing graph
4494 // if we have a channel with a common counterparty that appears in the first and last hop
4496 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4498 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4499 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4500 assert_eq!(route.paths[0].hops.len(), 2);
4502 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4503 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4504 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4505 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4506 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4507 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4509 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4510 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4511 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4512 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4513 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4514 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4518 fn overflow_unannounced_path_test_liquidity_underflow() {
4519 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4520 // the last-hop had a fee which overflowed a u64, we'd panic.
4521 // This was due to us adding the first-hop from us unconditionally, causing us to think
4522 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4523 // In this test, we previously hit a subtraction underflow due to having less available
4524 // liquidity at the last hop than 0.
4525 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());
4529 fn overflow_unannounced_path_test_feerate_overflow() {
4530 // This tests for the same case as above, except instead of hitting a subtraction
4531 // underflow, we hit a case where the fee charged at a hop overflowed.
4532 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());
4536 fn available_amount_while_routing_test() {
4537 // Tests whether we choose the correct available channel amount while routing.
4539 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4540 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4541 let scorer = ln_test_utils::TestScorer::new();
4542 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4543 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4544 let config = UserConfig::default();
4545 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4546 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4549 // We will use a simple single-path route from
4550 // our node to node2 via node0: channels {1, 3}.
4552 // First disable all other paths.
4553 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4554 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4555 short_channel_id: 2,
4558 cltv_expiry_delta: 0,
4559 htlc_minimum_msat: 0,
4560 htlc_maximum_msat: 100_000,
4562 fee_proportional_millionths: 0,
4563 excess_data: Vec::new()
4565 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4566 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4567 short_channel_id: 12,
4570 cltv_expiry_delta: 0,
4571 htlc_minimum_msat: 0,
4572 htlc_maximum_msat: 100_000,
4574 fee_proportional_millionths: 0,
4575 excess_data: Vec::new()
4578 // Make the first channel (#1) very permissive,
4579 // and we will be testing all limits on the second channel.
4580 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4581 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4582 short_channel_id: 1,
4585 cltv_expiry_delta: 0,
4586 htlc_minimum_msat: 0,
4587 htlc_maximum_msat: 1_000_000_000,
4589 fee_proportional_millionths: 0,
4590 excess_data: Vec::new()
4593 // First, let's see if routing works if we have absolutely no idea about the available amount.
4594 // In this case, it should be set to 250_000 sats.
4595 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4596 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4597 short_channel_id: 3,
4600 cltv_expiry_delta: 0,
4601 htlc_minimum_msat: 0,
4602 htlc_maximum_msat: 250_000_000,
4604 fee_proportional_millionths: 0,
4605 excess_data: Vec::new()
4609 // Attempt to route more than available results in a failure.
4610 let route_params = RouteParameters::from_payment_params_and_value(
4611 payment_params.clone(), 250_000_001);
4612 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4613 &our_id, &route_params, &network_graph.read_only(), None,
4614 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4615 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4616 } else { panic!(); }
4620 // Now, attempt to route an exact amount we have should be fine.
4621 let route_params = RouteParameters::from_payment_params_and_value(
4622 payment_params.clone(), 250_000_000);
4623 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4624 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4625 assert_eq!(route.paths.len(), 1);
4626 let path = route.paths.last().unwrap();
4627 assert_eq!(path.hops.len(), 2);
4628 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4629 assert_eq!(path.final_value_msat(), 250_000_000);
4632 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4633 // Disable channel #1 and use another first hop.
4634 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4635 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4636 short_channel_id: 1,
4639 cltv_expiry_delta: 0,
4640 htlc_minimum_msat: 0,
4641 htlc_maximum_msat: 1_000_000_000,
4643 fee_proportional_millionths: 0,
4644 excess_data: Vec::new()
4647 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4648 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4651 // Attempt to route more than available results in a failure.
4652 let route_params = RouteParameters::from_payment_params_and_value(
4653 payment_params.clone(), 200_000_001);
4654 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4655 &our_id, &route_params, &network_graph.read_only(),
4656 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4657 &Default::default(), &random_seed_bytes) {
4658 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4659 } else { panic!(); }
4663 // Now, attempt to route an exact amount we have should be fine.
4664 let route_params = RouteParameters::from_payment_params_and_value(
4665 payment_params.clone(), 200_000_000);
4666 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4667 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4668 &Default::default(), &random_seed_bytes).unwrap();
4669 assert_eq!(route.paths.len(), 1);
4670 let path = route.paths.last().unwrap();
4671 assert_eq!(path.hops.len(), 2);
4672 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4673 assert_eq!(path.final_value_msat(), 200_000_000);
4676 // Enable channel #1 back.
4677 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4678 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4679 short_channel_id: 1,
4682 cltv_expiry_delta: 0,
4683 htlc_minimum_msat: 0,
4684 htlc_maximum_msat: 1_000_000_000,
4686 fee_proportional_millionths: 0,
4687 excess_data: Vec::new()
4691 // Now let's see if routing works if we know only htlc_maximum_msat.
4692 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4693 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4694 short_channel_id: 3,
4697 cltv_expiry_delta: 0,
4698 htlc_minimum_msat: 0,
4699 htlc_maximum_msat: 15_000,
4701 fee_proportional_millionths: 0,
4702 excess_data: Vec::new()
4706 // Attempt to route more than available results in a failure.
4707 let route_params = RouteParameters::from_payment_params_and_value(
4708 payment_params.clone(), 15_001);
4709 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4710 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4711 &scorer, &Default::default(), &random_seed_bytes) {
4712 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4713 } else { panic!(); }
4717 // Now, attempt to route an exact amount we have should be fine.
4718 let route_params = RouteParameters::from_payment_params_and_value(
4719 payment_params.clone(), 15_000);
4720 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4721 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4722 assert_eq!(route.paths.len(), 1);
4723 let path = route.paths.last().unwrap();
4724 assert_eq!(path.hops.len(), 2);
4725 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4726 assert_eq!(path.final_value_msat(), 15_000);
4729 // Now let's see if routing works if we know only capacity from the UTXO.
4731 // We can't change UTXO capacity on the fly, so we'll disable
4732 // the existing channel and add another one with the capacity we need.
4733 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4734 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4735 short_channel_id: 3,
4738 cltv_expiry_delta: 0,
4739 htlc_minimum_msat: 0,
4740 htlc_maximum_msat: MAX_VALUE_MSAT,
4742 fee_proportional_millionths: 0,
4743 excess_data: Vec::new()
4746 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4747 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4748 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4749 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4750 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4752 *chain_monitor.utxo_ret.lock().unwrap() =
4753 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4754 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4756 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4757 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4758 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4759 short_channel_id: 333,
4762 cltv_expiry_delta: (3 << 4) | 1,
4763 htlc_minimum_msat: 0,
4764 htlc_maximum_msat: 15_000,
4766 fee_proportional_millionths: 0,
4767 excess_data: Vec::new()
4769 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4770 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4771 short_channel_id: 333,
4774 cltv_expiry_delta: (3 << 4) | 2,
4775 htlc_minimum_msat: 0,
4776 htlc_maximum_msat: 15_000,
4778 fee_proportional_millionths: 0,
4779 excess_data: Vec::new()
4783 // Attempt to route more than available results in a failure.
4784 let route_params = RouteParameters::from_payment_params_and_value(
4785 payment_params.clone(), 15_001);
4786 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4787 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4788 &scorer, &Default::default(), &random_seed_bytes) {
4789 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4790 } else { panic!(); }
4794 // Now, attempt to route an exact amount we have should be fine.
4795 let route_params = RouteParameters::from_payment_params_and_value(
4796 payment_params.clone(), 15_000);
4797 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4798 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4799 assert_eq!(route.paths.len(), 1);
4800 let path = route.paths.last().unwrap();
4801 assert_eq!(path.hops.len(), 2);
4802 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4803 assert_eq!(path.final_value_msat(), 15_000);
4806 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4807 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4808 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4809 short_channel_id: 333,
4812 cltv_expiry_delta: 0,
4813 htlc_minimum_msat: 0,
4814 htlc_maximum_msat: 10_000,
4816 fee_proportional_millionths: 0,
4817 excess_data: Vec::new()
4821 // Attempt to route more than available results in a failure.
4822 let route_params = RouteParameters::from_payment_params_and_value(
4823 payment_params.clone(), 10_001);
4824 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4825 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4826 &scorer, &Default::default(), &random_seed_bytes) {
4827 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4828 } else { panic!(); }
4832 // Now, attempt to route an exact amount we have should be fine.
4833 let route_params = RouteParameters::from_payment_params_and_value(
4834 payment_params.clone(), 10_000);
4835 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4836 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4837 assert_eq!(route.paths.len(), 1);
4838 let path = route.paths.last().unwrap();
4839 assert_eq!(path.hops.len(), 2);
4840 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4841 assert_eq!(path.final_value_msat(), 10_000);
4846 fn available_liquidity_last_hop_test() {
4847 // Check that available liquidity properly limits the path even when only
4848 // one of the latter hops is limited.
4849 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4850 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4851 let scorer = ln_test_utils::TestScorer::new();
4852 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4853 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4854 let config = UserConfig::default();
4855 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4856 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4859 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4860 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4861 // Total capacity: 50 sats.
4863 // Disable other potential paths.
4864 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4865 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4866 short_channel_id: 2,
4869 cltv_expiry_delta: 0,
4870 htlc_minimum_msat: 0,
4871 htlc_maximum_msat: 100_000,
4873 fee_proportional_millionths: 0,
4874 excess_data: Vec::new()
4876 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4877 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4878 short_channel_id: 7,
4881 cltv_expiry_delta: 0,
4882 htlc_minimum_msat: 0,
4883 htlc_maximum_msat: 100_000,
4885 fee_proportional_millionths: 0,
4886 excess_data: Vec::new()
4891 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4892 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4893 short_channel_id: 12,
4896 cltv_expiry_delta: 0,
4897 htlc_minimum_msat: 0,
4898 htlc_maximum_msat: 100_000,
4900 fee_proportional_millionths: 0,
4901 excess_data: Vec::new()
4903 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4904 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4905 short_channel_id: 13,
4908 cltv_expiry_delta: 0,
4909 htlc_minimum_msat: 0,
4910 htlc_maximum_msat: 100_000,
4912 fee_proportional_millionths: 0,
4913 excess_data: Vec::new()
4916 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4917 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4918 short_channel_id: 6,
4921 cltv_expiry_delta: 0,
4922 htlc_minimum_msat: 0,
4923 htlc_maximum_msat: 50_000,
4925 fee_proportional_millionths: 0,
4926 excess_data: Vec::new()
4928 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4929 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4930 short_channel_id: 11,
4933 cltv_expiry_delta: 0,
4934 htlc_minimum_msat: 0,
4935 htlc_maximum_msat: 100_000,
4937 fee_proportional_millionths: 0,
4938 excess_data: Vec::new()
4941 // Attempt to route more than available results in a failure.
4942 let route_params = RouteParameters::from_payment_params_and_value(
4943 payment_params.clone(), 60_000);
4944 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4945 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4946 &scorer, &Default::default(), &random_seed_bytes) {
4947 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4948 } else { panic!(); }
4952 // Now, attempt to route 49 sats (just a bit below the capacity).
4953 let route_params = RouteParameters::from_payment_params_and_value(
4954 payment_params.clone(), 49_000);
4955 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4956 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4957 assert_eq!(route.paths.len(), 1);
4958 let mut total_amount_paid_msat = 0;
4959 for path in &route.paths {
4960 assert_eq!(path.hops.len(), 4);
4961 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4962 total_amount_paid_msat += path.final_value_msat();
4964 assert_eq!(total_amount_paid_msat, 49_000);
4968 // Attempt to route an exact amount is also fine
4969 let route_params = RouteParameters::from_payment_params_and_value(
4970 payment_params, 50_000);
4971 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4972 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4973 assert_eq!(route.paths.len(), 1);
4974 let mut total_amount_paid_msat = 0;
4975 for path in &route.paths {
4976 assert_eq!(path.hops.len(), 4);
4977 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4978 total_amount_paid_msat += path.final_value_msat();
4980 assert_eq!(total_amount_paid_msat, 50_000);
4985 fn ignore_fee_first_hop_test() {
4986 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4987 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4988 let scorer = ln_test_utils::TestScorer::new();
4989 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4990 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4991 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4993 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4994 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4995 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4996 short_channel_id: 1,
4999 cltv_expiry_delta: 0,
5000 htlc_minimum_msat: 0,
5001 htlc_maximum_msat: 100_000,
5002 fee_base_msat: 1_000_000,
5003 fee_proportional_millionths: 0,
5004 excess_data: Vec::new()
5006 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5007 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5008 short_channel_id: 3,
5011 cltv_expiry_delta: 0,
5012 htlc_minimum_msat: 0,
5013 htlc_maximum_msat: 50_000,
5015 fee_proportional_millionths: 0,
5016 excess_data: Vec::new()
5020 let route_params = RouteParameters::from_payment_params_and_value(
5021 payment_params, 50_000);
5022 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5023 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5024 assert_eq!(route.paths.len(), 1);
5025 let mut total_amount_paid_msat = 0;
5026 for path in &route.paths {
5027 assert_eq!(path.hops.len(), 2);
5028 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5029 total_amount_paid_msat += path.final_value_msat();
5031 assert_eq!(total_amount_paid_msat, 50_000);
5036 fn simple_mpp_route_test() {
5037 let (secp_ctx, _, _, _, _) = build_graph();
5038 let (_, _, _, nodes) = get_nodes(&secp_ctx);
5039 let config = UserConfig::default();
5040 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5041 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5043 do_simple_mpp_route_test(clear_payment_params);
5045 // MPP to a 1-hop blinded path for nodes[2]
5046 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
5047 let blinded_path = BlindedPath {
5048 introduction_node_id: nodes[2],
5049 blinding_point: ln_test_utils::pubkey(42),
5050 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
5052 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
5054 fee_proportional_millionths: 0,
5055 htlc_minimum_msat: 0,
5056 htlc_maximum_msat: 0,
5057 cltv_expiry_delta: 0,
5058 features: BlindedHopFeatures::empty(),
5060 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
5061 .with_bolt12_features(bolt12_features.clone()).unwrap();
5062 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
5064 // MPP to 3 2-hop blinded paths
5065 let mut blinded_path_node_0 = blinded_path.clone();
5066 blinded_path_node_0.introduction_node_id = nodes[0];
5067 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
5068 let mut node_0_payinfo = blinded_payinfo.clone();
5069 node_0_payinfo.htlc_maximum_msat = 50_000;
5071 let mut blinded_path_node_7 = blinded_path_node_0.clone();
5072 blinded_path_node_7.introduction_node_id = nodes[7];
5073 let mut node_7_payinfo = blinded_payinfo.clone();
5074 node_7_payinfo.htlc_maximum_msat = 60_000;
5076 let mut blinded_path_node_1 = blinded_path_node_0.clone();
5077 blinded_path_node_1.introduction_node_id = nodes[1];
5078 let mut node_1_payinfo = blinded_payinfo.clone();
5079 node_1_payinfo.htlc_maximum_msat = 180_000;
5081 let two_hop_blinded_payment_params = PaymentParameters::blinded(
5083 (node_0_payinfo, blinded_path_node_0),
5084 (node_7_payinfo, blinded_path_node_7),
5085 (node_1_payinfo, blinded_path_node_1)
5087 .with_bolt12_features(bolt12_features).unwrap();
5088 do_simple_mpp_route_test(two_hop_blinded_payment_params);
5092 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
5093 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5094 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5095 let scorer = ln_test_utils::TestScorer::new();
5096 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5097 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5099 // We need a route consisting of 3 paths:
5100 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5101 // To achieve this, the amount being transferred should be around
5102 // the total capacity of these 3 paths.
5104 // First, we set limits on these (previously unlimited) channels.
5105 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
5107 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5108 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5109 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5110 short_channel_id: 1,
5113 cltv_expiry_delta: 0,
5114 htlc_minimum_msat: 0,
5115 htlc_maximum_msat: 100_000,
5117 fee_proportional_millionths: 0,
5118 excess_data: Vec::new()
5120 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5121 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5122 short_channel_id: 3,
5125 cltv_expiry_delta: 0,
5126 htlc_minimum_msat: 0,
5127 htlc_maximum_msat: 50_000,
5129 fee_proportional_millionths: 0,
5130 excess_data: Vec::new()
5133 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
5134 // (total limit 60).
5135 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5136 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5137 short_channel_id: 12,
5140 cltv_expiry_delta: 0,
5141 htlc_minimum_msat: 0,
5142 htlc_maximum_msat: 60_000,
5144 fee_proportional_millionths: 0,
5145 excess_data: Vec::new()
5147 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5148 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5149 short_channel_id: 13,
5152 cltv_expiry_delta: 0,
5153 htlc_minimum_msat: 0,
5154 htlc_maximum_msat: 60_000,
5156 fee_proportional_millionths: 0,
5157 excess_data: Vec::new()
5160 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5161 // (total capacity 180 sats).
5162 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5163 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5164 short_channel_id: 2,
5167 cltv_expiry_delta: 0,
5168 htlc_minimum_msat: 0,
5169 htlc_maximum_msat: 200_000,
5171 fee_proportional_millionths: 0,
5172 excess_data: Vec::new()
5174 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5175 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5176 short_channel_id: 4,
5179 cltv_expiry_delta: 0,
5180 htlc_minimum_msat: 0,
5181 htlc_maximum_msat: 180_000,
5183 fee_proportional_millionths: 0,
5184 excess_data: Vec::new()
5188 // Attempt to route more than available results in a failure.
5189 let route_params = RouteParameters::from_payment_params_and_value(
5190 payment_params.clone(), 300_000);
5191 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5192 &our_id, &route_params, &network_graph.read_only(), None,
5193 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5194 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5195 } else { panic!(); }
5199 // Attempt to route while setting max_path_count to 0 results in a failure.
5200 let zero_payment_params = payment_params.clone().with_max_path_count(0);
5201 let route_params = RouteParameters::from_payment_params_and_value(
5202 zero_payment_params, 100);
5203 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5204 &our_id, &route_params, &network_graph.read_only(), None,
5205 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5206 assert_eq!(err, "Can't find a route with no paths allowed.");
5207 } else { panic!(); }
5211 // Attempt to route while setting max_path_count to 3 results in a failure.
5212 // This is the case because the minimal_value_contribution_msat would require each path
5213 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5214 let fail_payment_params = payment_params.clone().with_max_path_count(3);
5215 let route_params = RouteParameters::from_payment_params_and_value(
5216 fail_payment_params, 250_000);
5217 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5218 &our_id, &route_params, &network_graph.read_only(), None,
5219 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5220 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5221 } else { panic!(); }
5225 // Now, attempt to route 250 sats (just a bit below the capacity).
5226 // Our algorithm should provide us with these 3 paths.
5227 let route_params = RouteParameters::from_payment_params_and_value(
5228 payment_params.clone(), 250_000);
5229 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5230 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5231 assert_eq!(route.paths.len(), 3);
5232 let mut total_amount_paid_msat = 0;
5233 for path in &route.paths {
5234 if let Some(bt) = &path.blinded_tail {
5235 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5237 assert_eq!(path.hops.len(), 2);
5238 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5240 total_amount_paid_msat += path.final_value_msat();
5242 assert_eq!(total_amount_paid_msat, 250_000);
5246 // Attempt to route an exact amount is also fine
5247 let route_params = RouteParameters::from_payment_params_and_value(
5248 payment_params.clone(), 290_000);
5249 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5250 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5251 assert_eq!(route.paths.len(), 3);
5252 let mut total_amount_paid_msat = 0;
5253 for path in &route.paths {
5254 if payment_params.payee.blinded_route_hints().len() != 0 {
5255 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5256 if let Some(bt) = &path.blinded_tail {
5257 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5258 if bt.hops.len() > 1 {
5259 assert_eq!(path.hops.last().unwrap().pubkey,
5260 payment_params.payee.blinded_route_hints().iter()
5261 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5262 .map(|(_, p)| p.introduction_node_id).unwrap());
5264 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5267 assert_eq!(path.hops.len(), 2);
5268 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5270 total_amount_paid_msat += path.final_value_msat();
5272 assert_eq!(total_amount_paid_msat, 290_000);
5277 fn long_mpp_route_test() {
5278 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5279 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5280 let scorer = ln_test_utils::TestScorer::new();
5281 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5282 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5283 let config = UserConfig::default();
5284 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5285 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5288 // We need a route consisting of 3 paths:
5289 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5290 // Note that these paths overlap (channels 5, 12, 13).
5291 // We will route 300 sats.
5292 // Each path will have 100 sats capacity, those channels which
5293 // are used twice will have 200 sats capacity.
5295 // Disable other potential paths.
5296 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5297 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5298 short_channel_id: 2,
5301 cltv_expiry_delta: 0,
5302 htlc_minimum_msat: 0,
5303 htlc_maximum_msat: 100_000,
5305 fee_proportional_millionths: 0,
5306 excess_data: Vec::new()
5308 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5309 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5310 short_channel_id: 7,
5313 cltv_expiry_delta: 0,
5314 htlc_minimum_msat: 0,
5315 htlc_maximum_msat: 100_000,
5317 fee_proportional_millionths: 0,
5318 excess_data: Vec::new()
5321 // Path via {node0, node2} is channels {1, 3, 5}.
5322 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5323 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5324 short_channel_id: 1,
5327 cltv_expiry_delta: 0,
5328 htlc_minimum_msat: 0,
5329 htlc_maximum_msat: 100_000,
5331 fee_proportional_millionths: 0,
5332 excess_data: Vec::new()
5334 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5335 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5336 short_channel_id: 3,
5339 cltv_expiry_delta: 0,
5340 htlc_minimum_msat: 0,
5341 htlc_maximum_msat: 100_000,
5343 fee_proportional_millionths: 0,
5344 excess_data: Vec::new()
5347 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5348 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5349 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5350 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5351 short_channel_id: 5,
5354 cltv_expiry_delta: 0,
5355 htlc_minimum_msat: 0,
5356 htlc_maximum_msat: 200_000,
5358 fee_proportional_millionths: 0,
5359 excess_data: Vec::new()
5362 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5363 // Add 100 sats to the capacities of {12, 13}, because these channels
5364 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5365 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5366 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5367 short_channel_id: 12,
5370 cltv_expiry_delta: 0,
5371 htlc_minimum_msat: 0,
5372 htlc_maximum_msat: 200_000,
5374 fee_proportional_millionths: 0,
5375 excess_data: Vec::new()
5377 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5378 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5379 short_channel_id: 13,
5382 cltv_expiry_delta: 0,
5383 htlc_minimum_msat: 0,
5384 htlc_maximum_msat: 200_000,
5386 fee_proportional_millionths: 0,
5387 excess_data: Vec::new()
5390 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5391 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5392 short_channel_id: 6,
5395 cltv_expiry_delta: 0,
5396 htlc_minimum_msat: 0,
5397 htlc_maximum_msat: 100_000,
5399 fee_proportional_millionths: 0,
5400 excess_data: Vec::new()
5402 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5403 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5404 short_channel_id: 11,
5407 cltv_expiry_delta: 0,
5408 htlc_minimum_msat: 0,
5409 htlc_maximum_msat: 100_000,
5411 fee_proportional_millionths: 0,
5412 excess_data: Vec::new()
5415 // Path via {node7, node2} is channels {12, 13, 5}.
5416 // We already limited them to 200 sats (they are used twice for 100 sats).
5417 // Nothing to do here.
5420 // Attempt to route more than available results in a failure.
5421 let route_params = RouteParameters::from_payment_params_and_value(
5422 payment_params.clone(), 350_000);
5423 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5424 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5425 &scorer, &Default::default(), &random_seed_bytes) {
5426 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5427 } else { panic!(); }
5431 // Now, attempt to route 300 sats (exact amount we can route).
5432 // Our algorithm should provide us with these 3 paths, 100 sats each.
5433 let route_params = RouteParameters::from_payment_params_and_value(
5434 payment_params, 300_000);
5435 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5436 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5437 assert_eq!(route.paths.len(), 3);
5439 let mut total_amount_paid_msat = 0;
5440 for path in &route.paths {
5441 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5442 total_amount_paid_msat += path.final_value_msat();
5444 assert_eq!(total_amount_paid_msat, 300_000);
5450 fn mpp_cheaper_route_test() {
5451 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5452 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5453 let scorer = ln_test_utils::TestScorer::new();
5454 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5455 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5456 let config = UserConfig::default();
5457 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5458 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5461 // This test checks that if we have two cheaper paths and one more expensive path,
5462 // so that liquidity-wise any 2 of 3 combination is sufficient,
5463 // two cheaper paths will be taken.
5464 // These paths have equal available liquidity.
5466 // We need a combination of 3 paths:
5467 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5468 // Note that these paths overlap (channels 5, 12, 13).
5469 // Each path will have 100 sats capacity, those channels which
5470 // are used twice will have 200 sats capacity.
5472 // Disable other potential paths.
5473 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5474 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5475 short_channel_id: 2,
5478 cltv_expiry_delta: 0,
5479 htlc_minimum_msat: 0,
5480 htlc_maximum_msat: 100_000,
5482 fee_proportional_millionths: 0,
5483 excess_data: Vec::new()
5485 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5486 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5487 short_channel_id: 7,
5490 cltv_expiry_delta: 0,
5491 htlc_minimum_msat: 0,
5492 htlc_maximum_msat: 100_000,
5494 fee_proportional_millionths: 0,
5495 excess_data: Vec::new()
5498 // Path via {node0, node2} is channels {1, 3, 5}.
5499 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5500 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5501 short_channel_id: 1,
5504 cltv_expiry_delta: 0,
5505 htlc_minimum_msat: 0,
5506 htlc_maximum_msat: 100_000,
5508 fee_proportional_millionths: 0,
5509 excess_data: Vec::new()
5511 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5512 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5513 short_channel_id: 3,
5516 cltv_expiry_delta: 0,
5517 htlc_minimum_msat: 0,
5518 htlc_maximum_msat: 100_000,
5520 fee_proportional_millionths: 0,
5521 excess_data: Vec::new()
5524 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5525 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5526 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5527 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5528 short_channel_id: 5,
5531 cltv_expiry_delta: 0,
5532 htlc_minimum_msat: 0,
5533 htlc_maximum_msat: 200_000,
5535 fee_proportional_millionths: 0,
5536 excess_data: Vec::new()
5539 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5540 // Add 100 sats to the capacities of {12, 13}, because these channels
5541 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5542 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5543 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5544 short_channel_id: 12,
5547 cltv_expiry_delta: 0,
5548 htlc_minimum_msat: 0,
5549 htlc_maximum_msat: 200_000,
5551 fee_proportional_millionths: 0,
5552 excess_data: Vec::new()
5554 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5555 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5556 short_channel_id: 13,
5559 cltv_expiry_delta: 0,
5560 htlc_minimum_msat: 0,
5561 htlc_maximum_msat: 200_000,
5563 fee_proportional_millionths: 0,
5564 excess_data: Vec::new()
5567 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5568 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5569 short_channel_id: 6,
5572 cltv_expiry_delta: 0,
5573 htlc_minimum_msat: 0,
5574 htlc_maximum_msat: 100_000,
5575 fee_base_msat: 1_000,
5576 fee_proportional_millionths: 0,
5577 excess_data: Vec::new()
5579 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5580 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5581 short_channel_id: 11,
5584 cltv_expiry_delta: 0,
5585 htlc_minimum_msat: 0,
5586 htlc_maximum_msat: 100_000,
5588 fee_proportional_millionths: 0,
5589 excess_data: Vec::new()
5592 // Path via {node7, node2} is channels {12, 13, 5}.
5593 // We already limited them to 200 sats (they are used twice for 100 sats).
5594 // Nothing to do here.
5597 // Now, attempt to route 180 sats.
5598 // Our algorithm should provide us with these 2 paths.
5599 let route_params = RouteParameters::from_payment_params_and_value(
5600 payment_params, 180_000);
5601 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5602 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5603 assert_eq!(route.paths.len(), 2);
5605 let mut total_value_transferred_msat = 0;
5606 let mut total_paid_msat = 0;
5607 for path in &route.paths {
5608 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5609 total_value_transferred_msat += path.final_value_msat();
5610 for hop in &path.hops {
5611 total_paid_msat += hop.fee_msat;
5614 // If we paid fee, this would be higher.
5615 assert_eq!(total_value_transferred_msat, 180_000);
5616 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5617 assert_eq!(total_fees_paid, 0);
5622 fn fees_on_mpp_route_test() {
5623 // This test makes sure that MPP algorithm properly takes into account
5624 // fees charged on the channels, by making the fees impactful:
5625 // if the fee is not properly accounted for, the behavior is different.
5626 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5627 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5628 let scorer = ln_test_utils::TestScorer::new();
5629 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5630 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5631 let config = UserConfig::default();
5632 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5633 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5636 // We need a route consisting of 2 paths:
5637 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5638 // We will route 200 sats, Each path will have 100 sats capacity.
5640 // This test is not particularly stable: e.g.,
5641 // there's a way to route via {node0, node2, node4}.
5642 // It works while pathfinding is deterministic, but can be broken otherwise.
5643 // It's fine to ignore this concern for now.
5645 // Disable other potential paths.
5646 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5647 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5648 short_channel_id: 2,
5651 cltv_expiry_delta: 0,
5652 htlc_minimum_msat: 0,
5653 htlc_maximum_msat: 100_000,
5655 fee_proportional_millionths: 0,
5656 excess_data: Vec::new()
5659 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5660 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5661 short_channel_id: 7,
5664 cltv_expiry_delta: 0,
5665 htlc_minimum_msat: 0,
5666 htlc_maximum_msat: 100_000,
5668 fee_proportional_millionths: 0,
5669 excess_data: Vec::new()
5672 // Path via {node0, node2} is channels {1, 3, 5}.
5673 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5674 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5675 short_channel_id: 1,
5678 cltv_expiry_delta: 0,
5679 htlc_minimum_msat: 0,
5680 htlc_maximum_msat: 100_000,
5682 fee_proportional_millionths: 0,
5683 excess_data: Vec::new()
5685 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5686 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5687 short_channel_id: 3,
5690 cltv_expiry_delta: 0,
5691 htlc_minimum_msat: 0,
5692 htlc_maximum_msat: 100_000,
5694 fee_proportional_millionths: 0,
5695 excess_data: Vec::new()
5698 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5699 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5700 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5701 short_channel_id: 5,
5704 cltv_expiry_delta: 0,
5705 htlc_minimum_msat: 0,
5706 htlc_maximum_msat: 100_000,
5708 fee_proportional_millionths: 0,
5709 excess_data: Vec::new()
5712 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5713 // All channels should be 100 sats capacity. But for the fee experiment,
5714 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5715 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5716 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5717 // so no matter how large are other channels,
5718 // the whole path will be limited by 100 sats with just these 2 conditions:
5719 // - channel 12 capacity is 250 sats
5720 // - fee for channel 6 is 150 sats
5721 // Let's test this by enforcing these 2 conditions and removing other limits.
5722 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5723 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5724 short_channel_id: 12,
5727 cltv_expiry_delta: 0,
5728 htlc_minimum_msat: 0,
5729 htlc_maximum_msat: 250_000,
5731 fee_proportional_millionths: 0,
5732 excess_data: Vec::new()
5734 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5735 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5736 short_channel_id: 13,
5739 cltv_expiry_delta: 0,
5740 htlc_minimum_msat: 0,
5741 htlc_maximum_msat: MAX_VALUE_MSAT,
5743 fee_proportional_millionths: 0,
5744 excess_data: Vec::new()
5747 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5748 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5749 short_channel_id: 6,
5752 cltv_expiry_delta: 0,
5753 htlc_minimum_msat: 0,
5754 htlc_maximum_msat: MAX_VALUE_MSAT,
5755 fee_base_msat: 150_000,
5756 fee_proportional_millionths: 0,
5757 excess_data: Vec::new()
5759 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5760 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5761 short_channel_id: 11,
5764 cltv_expiry_delta: 0,
5765 htlc_minimum_msat: 0,
5766 htlc_maximum_msat: MAX_VALUE_MSAT,
5768 fee_proportional_millionths: 0,
5769 excess_data: Vec::new()
5773 // Attempt to route more than available results in a failure.
5774 let route_params = RouteParameters::from_payment_params_and_value(
5775 payment_params.clone(), 210_000);
5776 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5777 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5778 &scorer, &Default::default(), &random_seed_bytes) {
5779 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5780 } else { panic!(); }
5784 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5785 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5786 max_total_routing_fee_msat: Some(149_999) };
5787 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5788 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5789 &scorer, &Default::default(), &random_seed_bytes) {
5790 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5791 } else { panic!(); }
5795 // Now, attempt to route 200 sats (exact amount we can route).
5796 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5797 max_total_routing_fee_msat: Some(150_000) };
5798 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5799 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5800 assert_eq!(route.paths.len(), 2);
5802 let mut total_amount_paid_msat = 0;
5803 for path in &route.paths {
5804 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5805 total_amount_paid_msat += path.final_value_msat();
5807 assert_eq!(total_amount_paid_msat, 200_000);
5808 assert_eq!(route.get_total_fees(), 150_000);
5813 fn mpp_with_last_hops() {
5814 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5815 // via a single last-hop route hint, we'd fail to route if we first collected routes
5816 // totaling close but not quite enough to fund the full payment.
5818 // This was because we considered last-hop hints to have exactly the sought payment amount
5819 // instead of the amount we were trying to collect, needlessly limiting our path searching
5820 // at the very first hop.
5822 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5823 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5824 // to only have the remaining to-collect amount in available liquidity.
5826 // This bug appeared in production in some specific channel configurations.
5827 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5828 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5829 let scorer = ln_test_utils::TestScorer::new();
5830 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5831 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5832 let config = UserConfig::default();
5833 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
5834 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
5835 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5836 src_node_id: nodes[2],
5837 short_channel_id: 42,
5838 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5839 cltv_expiry_delta: 42,
5840 htlc_minimum_msat: None,
5841 htlc_maximum_msat: None,
5842 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5844 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5845 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5846 // would first use the no-fee route and then fail to find a path along the second route as
5847 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5848 // under 5% of our payment amount.
5849 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5850 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5851 short_channel_id: 1,
5854 cltv_expiry_delta: (5 << 4) | 5,
5855 htlc_minimum_msat: 0,
5856 htlc_maximum_msat: 99_000,
5857 fee_base_msat: u32::max_value(),
5858 fee_proportional_millionths: u32::max_value(),
5859 excess_data: Vec::new()
5861 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5862 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5863 short_channel_id: 2,
5866 cltv_expiry_delta: (5 << 4) | 3,
5867 htlc_minimum_msat: 0,
5868 htlc_maximum_msat: 99_000,
5869 fee_base_msat: u32::max_value(),
5870 fee_proportional_millionths: u32::max_value(),
5871 excess_data: Vec::new()
5873 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5874 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5875 short_channel_id: 4,
5878 cltv_expiry_delta: (4 << 4) | 1,
5879 htlc_minimum_msat: 0,
5880 htlc_maximum_msat: MAX_VALUE_MSAT,
5882 fee_proportional_millionths: 0,
5883 excess_data: Vec::new()
5885 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5886 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5887 short_channel_id: 13,
5889 flags: 0|2, // Channel disabled
5890 cltv_expiry_delta: (13 << 4) | 1,
5891 htlc_minimum_msat: 0,
5892 htlc_maximum_msat: MAX_VALUE_MSAT,
5894 fee_proportional_millionths: 2000000,
5895 excess_data: Vec::new()
5898 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5900 let route_params = RouteParameters::from_payment_params_and_value(
5901 payment_params, 100_000);
5902 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5903 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5904 assert_eq!(route.paths.len(), 2);
5905 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5906 // Paths are manually ordered ordered by SCID, so:
5907 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5908 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5909 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5910 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5911 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5912 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5913 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5914 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5915 assert_eq!(route.get_total_fees(), 1);
5916 assert_eq!(route.get_total_amount(), 100_000);
5920 fn drop_lowest_channel_mpp_route_test() {
5921 // This test checks that low-capacity channel is dropped when after
5922 // path finding we realize that we found more capacity than we need.
5923 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5924 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5925 let scorer = ln_test_utils::TestScorer::new();
5926 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5927 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5928 let config = UserConfig::default();
5929 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5930 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5932 .with_max_channel_saturation_power_of_half(0);
5934 // We need a route consisting of 3 paths:
5935 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5937 // The first and the second paths should be sufficient, but the third should be
5938 // cheaper, so that we select it but drop later.
5940 // First, we set limits on these (previously unlimited) channels.
5941 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5943 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5944 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5945 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5946 short_channel_id: 1,
5949 cltv_expiry_delta: 0,
5950 htlc_minimum_msat: 0,
5951 htlc_maximum_msat: 100_000,
5953 fee_proportional_millionths: 0,
5954 excess_data: Vec::new()
5956 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5957 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5958 short_channel_id: 3,
5961 cltv_expiry_delta: 0,
5962 htlc_minimum_msat: 0,
5963 htlc_maximum_msat: 50_000,
5965 fee_proportional_millionths: 0,
5966 excess_data: Vec::new()
5969 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5970 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5971 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5972 short_channel_id: 12,
5975 cltv_expiry_delta: 0,
5976 htlc_minimum_msat: 0,
5977 htlc_maximum_msat: 60_000,
5979 fee_proportional_millionths: 0,
5980 excess_data: Vec::new()
5982 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5983 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5984 short_channel_id: 13,
5987 cltv_expiry_delta: 0,
5988 htlc_minimum_msat: 0,
5989 htlc_maximum_msat: 60_000,
5991 fee_proportional_millionths: 0,
5992 excess_data: Vec::new()
5995 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5996 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5997 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5998 short_channel_id: 2,
6001 cltv_expiry_delta: 0,
6002 htlc_minimum_msat: 0,
6003 htlc_maximum_msat: 20_000,
6005 fee_proportional_millionths: 0,
6006 excess_data: Vec::new()
6008 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6009 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6010 short_channel_id: 4,
6013 cltv_expiry_delta: 0,
6014 htlc_minimum_msat: 0,
6015 htlc_maximum_msat: 20_000,
6017 fee_proportional_millionths: 0,
6018 excess_data: Vec::new()
6022 // Attempt to route more than available results in a failure.
6023 let route_params = RouteParameters::from_payment_params_and_value(
6024 payment_params.clone(), 150_000);
6025 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6026 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6027 &scorer, &Default::default(), &random_seed_bytes) {
6028 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6029 } else { panic!(); }
6033 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
6034 // Our algorithm should provide us with these 3 paths.
6035 let route_params = RouteParameters::from_payment_params_and_value(
6036 payment_params.clone(), 125_000);
6037 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6038 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6039 assert_eq!(route.paths.len(), 3);
6040 let mut total_amount_paid_msat = 0;
6041 for path in &route.paths {
6042 assert_eq!(path.hops.len(), 2);
6043 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6044 total_amount_paid_msat += path.final_value_msat();
6046 assert_eq!(total_amount_paid_msat, 125_000);
6050 // Attempt to route without the last small cheap channel
6051 let route_params = RouteParameters::from_payment_params_and_value(
6052 payment_params, 90_000);
6053 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6054 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6055 assert_eq!(route.paths.len(), 2);
6056 let mut total_amount_paid_msat = 0;
6057 for path in &route.paths {
6058 assert_eq!(path.hops.len(), 2);
6059 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6060 total_amount_paid_msat += path.final_value_msat();
6062 assert_eq!(total_amount_paid_msat, 90_000);
6067 fn min_criteria_consistency() {
6068 // Test that we don't use an inconsistent metric between updating and walking nodes during
6069 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
6070 // was updated with a different criterion from the heap sorting, resulting in loops in
6071 // calculated paths. We test for that specific case here.
6073 // We construct a network that looks like this:
6075 // node2 -1(3)2- node3
6079 // node1 -1(5)2- node4 -1(1)2- node6
6085 // We create a loop on the side of our real path - our destination is node 6, with a
6086 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
6087 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
6088 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
6089 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
6090 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
6091 // "previous hop" being set to node 3, creating a loop in the path.
6092 let secp_ctx = Secp256k1::new();
6093 let logger = Arc::new(ln_test_utils::TestLogger::new());
6094 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6095 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
6096 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6097 let scorer = ln_test_utils::TestScorer::new();
6098 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6099 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6100 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
6102 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
6103 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6104 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6105 short_channel_id: 6,
6108 cltv_expiry_delta: (6 << 4) | 0,
6109 htlc_minimum_msat: 0,
6110 htlc_maximum_msat: MAX_VALUE_MSAT,
6112 fee_proportional_millionths: 0,
6113 excess_data: Vec::new()
6115 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
6117 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6118 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6119 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6120 short_channel_id: 5,
6123 cltv_expiry_delta: (5 << 4) | 0,
6124 htlc_minimum_msat: 0,
6125 htlc_maximum_msat: MAX_VALUE_MSAT,
6127 fee_proportional_millionths: 0,
6128 excess_data: Vec::new()
6130 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
6132 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
6133 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6134 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6135 short_channel_id: 4,
6138 cltv_expiry_delta: (4 << 4) | 0,
6139 htlc_minimum_msat: 0,
6140 htlc_maximum_msat: MAX_VALUE_MSAT,
6142 fee_proportional_millionths: 0,
6143 excess_data: Vec::new()
6145 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6147 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6148 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
6149 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6150 short_channel_id: 3,
6153 cltv_expiry_delta: (3 << 4) | 0,
6154 htlc_minimum_msat: 0,
6155 htlc_maximum_msat: MAX_VALUE_MSAT,
6157 fee_proportional_millionths: 0,
6158 excess_data: Vec::new()
6160 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6162 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6163 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
6164 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6165 short_channel_id: 2,
6168 cltv_expiry_delta: (2 << 4) | 0,
6169 htlc_minimum_msat: 0,
6170 htlc_maximum_msat: MAX_VALUE_MSAT,
6172 fee_proportional_millionths: 0,
6173 excess_data: Vec::new()
6176 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6177 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6178 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6179 short_channel_id: 1,
6182 cltv_expiry_delta: (1 << 4) | 0,
6183 htlc_minimum_msat: 100,
6184 htlc_maximum_msat: MAX_VALUE_MSAT,
6186 fee_proportional_millionths: 0,
6187 excess_data: Vec::new()
6189 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6192 // Now ensure the route flows simply over nodes 1 and 4 to 6.
6193 let route_params = RouteParameters::from_payment_params_and_value(
6194 payment_params, 10_000);
6195 let route = get_route(&our_id, &route_params, &network.read_only(), None,
6196 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6197 assert_eq!(route.paths.len(), 1);
6198 assert_eq!(route.paths[0].hops.len(), 3);
6200 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6201 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6202 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6203 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6204 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6205 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6207 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6208 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6209 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6210 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6211 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6212 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6214 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6215 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6216 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6217 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6218 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6219 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6225 fn exact_fee_liquidity_limit() {
6226 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6227 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6228 // we calculated fees on a higher value, resulting in us ignoring such paths.
6229 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6230 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6231 let scorer = ln_test_utils::TestScorer::new();
6232 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6233 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6234 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6236 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6238 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6239 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6240 short_channel_id: 2,
6243 cltv_expiry_delta: 0,
6244 htlc_minimum_msat: 0,
6245 htlc_maximum_msat: 85_000,
6247 fee_proportional_millionths: 0,
6248 excess_data: Vec::new()
6251 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6252 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6253 short_channel_id: 12,
6256 cltv_expiry_delta: (4 << 4) | 1,
6257 htlc_minimum_msat: 0,
6258 htlc_maximum_msat: 270_000,
6260 fee_proportional_millionths: 1000000,
6261 excess_data: Vec::new()
6265 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6266 // 200% fee charged channel 13 in the 1-to-2 direction.
6267 let mut route_params = RouteParameters::from_payment_params_and_value(
6268 payment_params, 90_000);
6269 route_params.max_total_routing_fee_msat = Some(90_000*2);
6270 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6271 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6272 assert_eq!(route.paths.len(), 1);
6273 assert_eq!(route.paths[0].hops.len(), 2);
6275 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6276 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6277 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6278 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6279 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6280 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6282 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6283 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6284 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6285 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6286 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6287 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6292 fn htlc_max_reduction_below_min() {
6293 // Test that if, while walking the graph, we reduce the value being sent to meet an
6294 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6295 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6296 // resulting in us thinking there is no possible path, even if other paths exist.
6297 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6298 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6299 let scorer = ln_test_utils::TestScorer::new();
6300 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6301 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6302 let config = UserConfig::default();
6303 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6304 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6307 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6308 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6309 // then try to send 90_000.
6310 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6311 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6312 short_channel_id: 2,
6315 cltv_expiry_delta: 0,
6316 htlc_minimum_msat: 0,
6317 htlc_maximum_msat: 80_000,
6319 fee_proportional_millionths: 0,
6320 excess_data: Vec::new()
6322 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6323 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6324 short_channel_id: 4,
6327 cltv_expiry_delta: (4 << 4) | 1,
6328 htlc_minimum_msat: 90_000,
6329 htlc_maximum_msat: MAX_VALUE_MSAT,
6331 fee_proportional_millionths: 0,
6332 excess_data: Vec::new()
6336 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6337 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6338 // expensive) channels 12-13 path.
6339 let mut route_params = RouteParameters::from_payment_params_and_value(
6340 payment_params, 90_000);
6341 route_params.max_total_routing_fee_msat = Some(90_000*2);
6342 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6343 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6344 assert_eq!(route.paths.len(), 1);
6345 assert_eq!(route.paths[0].hops.len(), 2);
6347 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6348 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6349 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6350 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6351 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6352 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6354 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6355 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6356 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6357 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6358 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6359 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6364 fn multiple_direct_first_hops() {
6365 // Previously we'd only ever considered one first hop path per counterparty.
6366 // However, as we don't restrict users to one channel per peer, we really need to support
6367 // looking at all first hop paths.
6368 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6369 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6370 // route over multiple channels with the same first hop.
6371 let secp_ctx = Secp256k1::new();
6372 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6373 let logger = Arc::new(ln_test_utils::TestLogger::new());
6374 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6375 let scorer = ln_test_utils::TestScorer::new();
6376 let config = UserConfig::default();
6377 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6378 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6380 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6381 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6384 let route_params = RouteParameters::from_payment_params_and_value(
6385 payment_params.clone(), 100_000);
6386 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6387 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6388 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6389 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6390 assert_eq!(route.paths.len(), 1);
6391 assert_eq!(route.paths[0].hops.len(), 1);
6393 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6394 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6395 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6398 let route_params = RouteParameters::from_payment_params_and_value(
6399 payment_params.clone(), 100_000);
6400 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6401 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6402 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6403 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6404 assert_eq!(route.paths.len(), 2);
6405 assert_eq!(route.paths[0].hops.len(), 1);
6406 assert_eq!(route.paths[1].hops.len(), 1);
6408 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6409 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6411 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6412 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6414 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6415 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6419 // If we have a bunch of outbound channels to the same node, where most are not
6420 // sufficient to pay the full payment, but one is, we should default to just using the
6421 // one single channel that has sufficient balance, avoiding MPP.
6423 // If we have several options above the 3xpayment value threshold, we should pick the
6424 // smallest of them, avoiding further fragmenting our available outbound balance to
6426 let route_params = RouteParameters::from_payment_params_and_value(
6427 payment_params, 100_000);
6428 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6429 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6430 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6431 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6432 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6433 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6434 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6435 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6436 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6437 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6438 assert_eq!(route.paths.len(), 1);
6439 assert_eq!(route.paths[0].hops.len(), 1);
6441 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6442 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6443 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6448 fn prefers_shorter_route_with_higher_fees() {
6449 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6450 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6451 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6453 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6454 let scorer = ln_test_utils::TestScorer::new();
6455 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6456 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6457 let route_params = RouteParameters::from_payment_params_and_value(
6458 payment_params.clone(), 100);
6459 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6460 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6461 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6463 assert_eq!(route.get_total_fees(), 100);
6464 assert_eq!(route.get_total_amount(), 100);
6465 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6467 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6468 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6469 let scorer = FixedPenaltyScorer::with_penalty(100);
6470 let route_params = RouteParameters::from_payment_params_and_value(
6471 payment_params, 100);
6472 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6473 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6474 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6476 assert_eq!(route.get_total_fees(), 300);
6477 assert_eq!(route.get_total_amount(), 100);
6478 assert_eq!(path, vec![2, 4, 7, 10]);
6481 struct BadChannelScorer {
6482 short_channel_id: u64,
6486 impl Writeable for BadChannelScorer {
6487 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6489 impl ScoreLookUp for BadChannelScorer {
6490 type ScoreParams = ();
6491 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6492 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6496 struct BadNodeScorer {
6501 impl Writeable for BadNodeScorer {
6502 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6505 impl ScoreLookUp for BadNodeScorer {
6506 type ScoreParams = ();
6507 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6508 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6513 fn avoids_routing_through_bad_channels_and_nodes() {
6514 let (secp_ctx, network, _, _, logger) = build_graph();
6515 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6516 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6517 let network_graph = network.read_only();
6519 // A path to nodes[6] exists when no penalties are applied to any channel.
6520 let scorer = ln_test_utils::TestScorer::new();
6521 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6522 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6523 let route_params = RouteParameters::from_payment_params_and_value(
6524 payment_params, 100);
6525 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6526 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6527 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6529 assert_eq!(route.get_total_fees(), 100);
6530 assert_eq!(route.get_total_amount(), 100);
6531 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6533 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6534 let scorer = BadChannelScorer { short_channel_id: 6 };
6535 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6536 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6537 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6539 assert_eq!(route.get_total_fees(), 300);
6540 assert_eq!(route.get_total_amount(), 100);
6541 assert_eq!(path, vec![2, 4, 7, 10]);
6543 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6544 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6545 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6546 &scorer, &Default::default(), &random_seed_bytes) {
6547 Err(LightningError { err, .. } ) => {
6548 assert_eq!(err, "Failed to find a path to the given destination");
6550 Ok(_) => panic!("Expected error"),
6555 fn total_fees_single_path() {
6557 paths: vec![Path { hops: vec![
6559 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6560 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6561 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6564 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6565 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6566 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6569 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6570 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6571 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6573 ], blinded_tail: None }],
6577 assert_eq!(route.get_total_fees(), 250);
6578 assert_eq!(route.get_total_amount(), 225);
6582 fn total_fees_multi_path() {
6584 paths: vec![Path { hops: vec![
6586 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6587 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6588 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6591 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6592 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6593 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6595 ], blinded_tail: None }, Path { hops: vec![
6597 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6598 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6599 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6602 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6603 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6604 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6606 ], blinded_tail: None }],
6610 assert_eq!(route.get_total_fees(), 200);
6611 assert_eq!(route.get_total_amount(), 300);
6615 fn total_empty_route_no_panic() {
6616 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6617 // would both panic if the route was completely empty. We test to ensure they return 0
6618 // here, even though its somewhat nonsensical as a route.
6619 let route = Route { paths: Vec::new(), route_params: None };
6621 assert_eq!(route.get_total_fees(), 0);
6622 assert_eq!(route.get_total_amount(), 0);
6626 fn limits_total_cltv_delta() {
6627 let (secp_ctx, network, _, _, logger) = build_graph();
6628 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6629 let network_graph = network.read_only();
6631 let scorer = ln_test_utils::TestScorer::new();
6633 // Make sure that generally there is at least one route available
6634 let feasible_max_total_cltv_delta = 1008;
6635 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6636 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6637 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6638 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6639 let route_params = RouteParameters::from_payment_params_and_value(
6640 feasible_payment_params, 100);
6641 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6642 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6643 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6644 assert_ne!(path.len(), 0);
6646 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6647 let fail_max_total_cltv_delta = 23;
6648 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6649 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6650 let route_params = RouteParameters::from_payment_params_and_value(
6651 fail_payment_params, 100);
6652 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6653 &Default::default(), &random_seed_bytes)
6655 Err(LightningError { err, .. } ) => {
6656 assert_eq!(err, "Failed to find a path to the given destination");
6658 Ok(_) => panic!("Expected error"),
6663 fn avoids_recently_failed_paths() {
6664 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6665 // randomly inserting channels into it until we can't find a route anymore.
6666 let (secp_ctx, network, _, _, logger) = build_graph();
6667 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6668 let network_graph = network.read_only();
6670 let scorer = ln_test_utils::TestScorer::new();
6671 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6672 .with_max_path_count(1);
6673 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6674 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6676 // We should be able to find a route initially, and then after we fail a few random
6677 // channels eventually we won't be able to any longer.
6678 let route_params = RouteParameters::from_payment_params_and_value(
6679 payment_params.clone(), 100);
6680 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6681 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6683 let route_params = RouteParameters::from_payment_params_and_value(
6684 payment_params.clone(), 100);
6685 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6686 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6688 for chan in route.paths[0].hops.iter() {
6689 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6691 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6692 % route.paths[0].hops.len();
6693 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6699 fn limits_path_length() {
6700 let (secp_ctx, network, _, _, logger) = build_line_graph();
6701 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6702 let network_graph = network.read_only();
6704 let scorer = ln_test_utils::TestScorer::new();
6705 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6706 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6708 // First check we can actually create a long route on this graph.
6709 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6710 let route_params = RouteParameters::from_payment_params_and_value(
6711 feasible_payment_params, 100);
6712 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6713 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6714 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6715 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6717 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6718 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6719 let route_params = RouteParameters::from_payment_params_and_value(
6720 fail_payment_params, 100);
6721 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6722 &Default::default(), &random_seed_bytes)
6724 Err(LightningError { err, .. } ) => {
6725 assert_eq!(err, "Failed to find a path to the given destination");
6727 Ok(_) => panic!("Expected error"),
6732 fn adds_and_limits_cltv_offset() {
6733 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6734 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6736 let scorer = ln_test_utils::TestScorer::new();
6738 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6739 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6740 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6741 let route_params = RouteParameters::from_payment_params_and_value(
6742 payment_params.clone(), 100);
6743 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6744 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6745 assert_eq!(route.paths.len(), 1);
6747 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6749 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6750 let mut route_default = route.clone();
6751 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6752 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6753 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6754 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6755 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6757 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6758 let mut route_limited = route.clone();
6759 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6760 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6761 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6762 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6763 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6767 fn adds_plausible_cltv_offset() {
6768 let (secp_ctx, network, _, _, logger) = build_graph();
6769 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6770 let network_graph = network.read_only();
6771 let network_nodes = network_graph.nodes();
6772 let network_channels = network_graph.channels();
6773 let scorer = ln_test_utils::TestScorer::new();
6774 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6775 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6776 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6778 let route_params = RouteParameters::from_payment_params_and_value(
6779 payment_params.clone(), 100);
6780 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6781 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6782 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6784 let mut path_plausibility = vec![];
6786 for p in route.paths {
6787 // 1. Select random observation point
6788 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6789 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6791 prng.process_in_place(&mut random_bytes);
6792 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6793 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6795 // 2. Calculate what CLTV expiry delta we would observe there
6796 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6798 // 3. Starting from the observation point, find candidate paths
6799 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6800 candidates.push_back((observation_point, vec![]));
6802 let mut found_plausible_candidate = false;
6804 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6805 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6806 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6807 found_plausible_candidate = true;
6808 break 'candidate_loop;
6812 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6813 for channel_id in &cur_node.channels {
6814 if let Some(channel_info) = network_channels.get(&channel_id) {
6815 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6816 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6817 if cur_path_cltv_deltas.iter().sum::<u32>()
6818 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6819 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6820 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6821 candidates.push_back((*next_id, new_path_cltv_deltas));
6829 path_plausibility.push(found_plausible_candidate);
6831 assert!(path_plausibility.iter().all(|x| *x));
6835 fn builds_correct_path_from_hops() {
6836 let (secp_ctx, network, _, _, logger) = build_graph();
6837 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6838 let network_graph = network.read_only();
6840 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6841 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6843 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6844 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6845 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6846 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6847 Arc::clone(&logger), &random_seed_bytes).unwrap();
6848 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6849 assert_eq!(hops.len(), route.paths[0].hops.len());
6850 for (idx, hop_pubkey) in hops.iter().enumerate() {
6851 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6856 fn avoids_saturating_channels() {
6857 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6858 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6859 let decay_params = ProbabilisticScoringDecayParameters::default();
6860 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6862 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6863 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6864 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6865 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6866 short_channel_id: 4,
6869 cltv_expiry_delta: (4 << 4) | 1,
6870 htlc_minimum_msat: 0,
6871 htlc_maximum_msat: 250_000_000,
6873 fee_proportional_millionths: 0,
6874 excess_data: Vec::new()
6876 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6877 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6878 short_channel_id: 13,
6881 cltv_expiry_delta: (13 << 4) | 1,
6882 htlc_minimum_msat: 0,
6883 htlc_maximum_msat: 250_000_000,
6885 fee_proportional_millionths: 0,
6886 excess_data: Vec::new()
6889 let config = UserConfig::default();
6890 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6891 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6893 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6894 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6895 // 100,000 sats is less than the available liquidity on each channel, set above.
6896 let route_params = RouteParameters::from_payment_params_and_value(
6897 payment_params, 100_000_000);
6898 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6899 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6900 assert_eq!(route.paths.len(), 2);
6901 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6902 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6905 #[cfg(not(feature = "no-std"))]
6906 pub(super) fn random_init_seed() -> u64 {
6907 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6908 use core::hash::{BuildHasher, Hasher};
6909 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6910 println!("Using seed of {}", seed);
6915 #[cfg(not(feature = "no-std"))]
6916 fn generate_routes() {
6917 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6919 let logger = ln_test_utils::TestLogger::new();
6920 let graph = match super::bench_utils::read_network_graph(&logger) {
6928 let params = ProbabilisticScoringFeeParameters::default();
6929 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6930 let features = super::Bolt11InvoiceFeatures::empty();
6932 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6936 #[cfg(not(feature = "no-std"))]
6937 fn generate_routes_mpp() {
6938 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6940 let logger = ln_test_utils::TestLogger::new();
6941 let graph = match super::bench_utils::read_network_graph(&logger) {
6949 let params = ProbabilisticScoringFeeParameters::default();
6950 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6951 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
6953 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6957 #[cfg(not(feature = "no-std"))]
6958 fn generate_large_mpp_routes() {
6959 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6961 let logger = ln_test_utils::TestLogger::new();
6962 let graph = match super::bench_utils::read_network_graph(&logger) {
6970 let params = ProbabilisticScoringFeeParameters::default();
6971 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6972 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
6974 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6978 fn honors_manual_penalties() {
6979 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6980 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6982 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6983 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6985 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6986 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6988 // First check set manual penalties are returned by the scorer.
6989 let usage = ChannelUsage {
6991 inflight_htlc_msat: 0,
6992 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6994 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6995 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6996 let network_graph = network_graph.read_only();
6997 let channels = network_graph.channels();
6998 let channel = channels.get(&5).unwrap();
6999 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
7000 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop(PublicHopCandidate {
7002 short_channel_id: 5,
7004 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
7006 // Then check we can get a normal route
7007 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
7008 let route_params = RouteParameters::from_payment_params_and_value(
7009 payment_params, 100);
7010 let route = get_route(&our_id, &route_params, &network_graph, None,
7011 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
7012 assert!(route.is_ok());
7014 // Then check that we can't get a route if we ban an intermediate node.
7015 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
7016 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7017 assert!(route.is_err());
7019 // Finally make sure we can route again, when we remove the ban.
7020 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
7021 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7022 assert!(route.is_ok());
7026 fn abide_by_route_hint_max_htlc() {
7027 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
7028 // params in the final route.
7029 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7030 let netgraph = network_graph.read_only();
7031 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7032 let scorer = ln_test_utils::TestScorer::new();
7033 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7034 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7035 let config = UserConfig::default();
7037 let max_htlc_msat = 50_000;
7038 let route_hint_1 = RouteHint(vec![RouteHintHop {
7039 src_node_id: nodes[2],
7040 short_channel_id: 42,
7043 proportional_millionths: 0,
7045 cltv_expiry_delta: 10,
7046 htlc_minimum_msat: None,
7047 htlc_maximum_msat: Some(max_htlc_msat),
7049 let dest_node_id = ln_test_utils::pubkey(42);
7050 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7051 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
7052 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7055 // Make sure we'll error if our route hints don't have enough liquidity according to their
7056 // htlc_maximum_msat.
7057 let mut route_params = RouteParameters::from_payment_params_and_value(
7058 payment_params, max_htlc_msat + 1);
7059 route_params.max_total_routing_fee_msat = None;
7060 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
7061 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
7064 assert_eq!(err, "Failed to find a sufficient route to the given destination");
7065 } else { panic!(); }
7067 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
7068 let mut route_hint_2 = route_hint_1.clone();
7069 route_hint_2.0[0].short_channel_id = 43;
7070 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7071 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7072 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7074 let mut route_params = RouteParameters::from_payment_params_and_value(
7075 payment_params, max_htlc_msat + 1);
7076 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
7077 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
7078 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7079 assert_eq!(route.paths.len(), 2);
7080 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7081 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7085 fn direct_channel_to_hints_with_max_htlc() {
7086 // Check that if we have a first hop channel peer that's connected to multiple provided route
7087 // hints, that we properly split the payment between the route hints if needed.
7088 let logger = Arc::new(ln_test_utils::TestLogger::new());
7089 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7090 let scorer = ln_test_utils::TestScorer::new();
7091 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7092 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7093 let config = UserConfig::default();
7095 let our_node_id = ln_test_utils::pubkey(42);
7096 let intermed_node_id = ln_test_utils::pubkey(43);
7097 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7099 let amt_msat = 900_000;
7100 let max_htlc_msat = 500_000;
7101 let route_hint_1 = RouteHint(vec![RouteHintHop {
7102 src_node_id: intermed_node_id,
7103 short_channel_id: 44,
7106 proportional_millionths: 0,
7108 cltv_expiry_delta: 10,
7109 htlc_minimum_msat: None,
7110 htlc_maximum_msat: Some(max_htlc_msat),
7112 src_node_id: intermed_node_id,
7113 short_channel_id: 45,
7116 proportional_millionths: 0,
7118 cltv_expiry_delta: 10,
7119 htlc_minimum_msat: None,
7120 // Check that later route hint max htlcs don't override earlier ones
7121 htlc_maximum_msat: Some(max_htlc_msat - 50),
7123 let mut route_hint_2 = route_hint_1.clone();
7124 route_hint_2.0[0].short_channel_id = 46;
7125 route_hint_2.0[1].short_channel_id = 47;
7126 let dest_node_id = ln_test_utils::pubkey(44);
7127 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7128 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7129 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7132 let route_params = RouteParameters::from_payment_params_and_value(
7133 payment_params, amt_msat);
7134 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7135 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7136 &Default::default(), &random_seed_bytes).unwrap();
7137 assert_eq!(route.paths.len(), 2);
7138 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7139 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7140 assert_eq!(route.get_total_amount(), amt_msat);
7142 // Re-run but with two first hop channels connected to the same route hint peers that must be
7144 let first_hops = vec![
7145 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7146 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7148 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7149 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7150 &Default::default(), &random_seed_bytes).unwrap();
7151 assert_eq!(route.paths.len(), 2);
7152 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7153 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7154 assert_eq!(route.get_total_amount(), amt_msat);
7156 // Make sure this works for blinded route hints.
7157 let blinded_path = BlindedPath {
7158 introduction_node_id: intermed_node_id,
7159 blinding_point: ln_test_utils::pubkey(42),
7161 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
7162 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
7165 let blinded_payinfo = BlindedPayInfo {
7167 fee_proportional_millionths: 0,
7168 htlc_minimum_msat: 1,
7169 htlc_maximum_msat: max_htlc_msat,
7170 cltv_expiry_delta: 10,
7171 features: BlindedHopFeatures::empty(),
7173 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7174 let payment_params = PaymentParameters::blinded(vec![
7175 (blinded_payinfo.clone(), blinded_path.clone()),
7176 (blinded_payinfo.clone(), blinded_path.clone())])
7177 .with_bolt12_features(bolt12_features).unwrap();
7178 let route_params = RouteParameters::from_payment_params_and_value(
7179 payment_params, amt_msat);
7180 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7181 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7182 &Default::default(), &random_seed_bytes).unwrap();
7183 assert_eq!(route.paths.len(), 2);
7184 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7185 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7186 assert_eq!(route.get_total_amount(), amt_msat);
7190 fn blinded_route_ser() {
7191 let blinded_path_1 = BlindedPath {
7192 introduction_node_id: ln_test_utils::pubkey(42),
7193 blinding_point: ln_test_utils::pubkey(43),
7195 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7196 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7199 let blinded_path_2 = BlindedPath {
7200 introduction_node_id: ln_test_utils::pubkey(46),
7201 blinding_point: ln_test_utils::pubkey(47),
7203 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7204 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7207 // (De)serialize a Route with 1 blinded path out of two total paths.
7208 let mut route = Route { paths: vec![Path {
7209 hops: vec![RouteHop {
7210 pubkey: ln_test_utils::pubkey(50),
7211 node_features: NodeFeatures::empty(),
7212 short_channel_id: 42,
7213 channel_features: ChannelFeatures::empty(),
7215 cltv_expiry_delta: 0,
7216 maybe_announced_channel: true,
7218 blinded_tail: Some(BlindedTail {
7219 hops: blinded_path_1.blinded_hops,
7220 blinding_point: blinded_path_1.blinding_point,
7221 excess_final_cltv_expiry_delta: 40,
7222 final_value_msat: 100,
7224 hops: vec![RouteHop {
7225 pubkey: ln_test_utils::pubkey(51),
7226 node_features: NodeFeatures::empty(),
7227 short_channel_id: 43,
7228 channel_features: ChannelFeatures::empty(),
7230 cltv_expiry_delta: 0,
7231 maybe_announced_channel: true,
7232 }], blinded_tail: None }],
7235 let encoded_route = route.encode();
7236 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7237 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7238 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7240 // (De)serialize a Route with two paths, each containing a blinded tail.
7241 route.paths[1].blinded_tail = Some(BlindedTail {
7242 hops: blinded_path_2.blinded_hops,
7243 blinding_point: blinded_path_2.blinding_point,
7244 excess_final_cltv_expiry_delta: 41,
7245 final_value_msat: 101,
7247 let encoded_route = route.encode();
7248 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7249 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7250 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7254 fn blinded_path_inflight_processing() {
7255 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7256 // account for the blinded tail's final amount_msat.
7257 let mut inflight_htlcs = InFlightHtlcs::new();
7258 let blinded_path = BlindedPath {
7259 introduction_node_id: ln_test_utils::pubkey(43),
7260 blinding_point: ln_test_utils::pubkey(48),
7261 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7264 hops: vec![RouteHop {
7265 pubkey: ln_test_utils::pubkey(42),
7266 node_features: NodeFeatures::empty(),
7267 short_channel_id: 42,
7268 channel_features: ChannelFeatures::empty(),
7270 cltv_expiry_delta: 0,
7271 maybe_announced_channel: false,
7274 pubkey: blinded_path.introduction_node_id,
7275 node_features: NodeFeatures::empty(),
7276 short_channel_id: 43,
7277 channel_features: ChannelFeatures::empty(),
7279 cltv_expiry_delta: 0,
7280 maybe_announced_channel: false,
7282 blinded_tail: Some(BlindedTail {
7283 hops: blinded_path.blinded_hops,
7284 blinding_point: blinded_path.blinding_point,
7285 excess_final_cltv_expiry_delta: 0,
7286 final_value_msat: 200,
7289 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7290 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7291 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7295 fn blinded_path_cltv_shadow_offset() {
7296 // Make sure we add a shadow offset when sending to blinded paths.
7297 let blinded_path = BlindedPath {
7298 introduction_node_id: ln_test_utils::pubkey(43),
7299 blinding_point: ln_test_utils::pubkey(44),
7301 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7302 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7305 let mut route = Route { paths: vec![Path {
7306 hops: vec![RouteHop {
7307 pubkey: ln_test_utils::pubkey(42),
7308 node_features: NodeFeatures::empty(),
7309 short_channel_id: 42,
7310 channel_features: ChannelFeatures::empty(),
7312 cltv_expiry_delta: 0,
7313 maybe_announced_channel: false,
7316 pubkey: blinded_path.introduction_node_id,
7317 node_features: NodeFeatures::empty(),
7318 short_channel_id: 43,
7319 channel_features: ChannelFeatures::empty(),
7321 cltv_expiry_delta: 0,
7322 maybe_announced_channel: false,
7325 blinded_tail: Some(BlindedTail {
7326 hops: blinded_path.blinded_hops,
7327 blinding_point: blinded_path.blinding_point,
7328 excess_final_cltv_expiry_delta: 0,
7329 final_value_msat: 200,
7331 }], route_params: None};
7333 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7334 let (_, network_graph, _, _, _) = build_line_graph();
7335 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7336 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7337 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7341 fn simple_blinded_route_hints() {
7342 do_simple_blinded_route_hints(1);
7343 do_simple_blinded_route_hints(2);
7344 do_simple_blinded_route_hints(3);
7347 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7348 // Check that we can generate a route to a blinded path with the expected hops.
7349 let (secp_ctx, network, _, _, logger) = build_graph();
7350 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7351 let network_graph = network.read_only();
7353 let scorer = ln_test_utils::TestScorer::new();
7354 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7355 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7357 let mut blinded_path = BlindedPath {
7358 introduction_node_id: nodes[2],
7359 blinding_point: ln_test_utils::pubkey(42),
7360 blinded_hops: Vec::with_capacity(num_blinded_hops),
7362 for i in 0..num_blinded_hops {
7363 blinded_path.blinded_hops.push(
7364 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7367 let blinded_payinfo = BlindedPayInfo {
7369 fee_proportional_millionths: 500,
7370 htlc_minimum_msat: 1000,
7371 htlc_maximum_msat: 100_000_000,
7372 cltv_expiry_delta: 15,
7373 features: BlindedHopFeatures::empty(),
7376 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7377 let route_params = RouteParameters::from_payment_params_and_value(
7378 payment_params, 1001);
7379 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7380 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7381 assert_eq!(route.paths.len(), 1);
7382 assert_eq!(route.paths[0].hops.len(), 2);
7384 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7385 assert_eq!(tail.hops, blinded_path.blinded_hops);
7386 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7387 assert_eq!(tail.final_value_msat, 1001);
7389 let final_hop = route.paths[0].hops.last().unwrap();
7390 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
7391 if tail.hops.len() > 1 {
7392 assert_eq!(final_hop.fee_msat,
7393 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7394 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7396 assert_eq!(final_hop.fee_msat, 0);
7397 assert_eq!(final_hop.cltv_expiry_delta, 0);
7402 fn blinded_path_routing_errors() {
7403 // Check that we can generate a route to a blinded path with the expected hops.
7404 let (secp_ctx, network, _, _, logger) = build_graph();
7405 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7406 let network_graph = network.read_only();
7408 let scorer = ln_test_utils::TestScorer::new();
7409 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7410 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7412 let mut invalid_blinded_path = BlindedPath {
7413 introduction_node_id: nodes[2],
7414 blinding_point: ln_test_utils::pubkey(42),
7416 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7419 let blinded_payinfo = BlindedPayInfo {
7421 fee_proportional_millionths: 500,
7422 htlc_minimum_msat: 1000,
7423 htlc_maximum_msat: 100_000_000,
7424 cltv_expiry_delta: 15,
7425 features: BlindedHopFeatures::empty(),
7428 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7429 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
7430 let payment_params = PaymentParameters::blinded(vec![
7431 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7432 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7433 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7434 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7435 &scorer, &Default::default(), &random_seed_bytes)
7437 Err(LightningError { err, .. }) => {
7438 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7440 _ => panic!("Expected error")
7443 invalid_blinded_path.introduction_node_id = our_id;
7444 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7445 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7446 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7447 &Default::default(), &random_seed_bytes)
7449 Err(LightningError { err, .. }) => {
7450 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7452 _ => panic!("Expected error")
7455 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
7456 invalid_blinded_path.blinded_hops.clear();
7457 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7458 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7459 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7460 &Default::default(), &random_seed_bytes)
7462 Err(LightningError { err, .. }) => {
7463 assert_eq!(err, "0-hop blinded path provided");
7465 _ => panic!("Expected error")
7470 fn matching_intro_node_paths_provided() {
7471 // Check that if multiple blinded paths with the same intro node are provided in payment
7472 // parameters, we'll return the correct paths in the resulting MPP route.
7473 let (secp_ctx, network, _, _, logger) = build_graph();
7474 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7475 let network_graph = network.read_only();
7477 let scorer = ln_test_utils::TestScorer::new();
7478 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7479 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7480 let config = UserConfig::default();
7482 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7483 let blinded_path_1 = BlindedPath {
7484 introduction_node_id: nodes[2],
7485 blinding_point: ln_test_utils::pubkey(42),
7487 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7488 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7491 let blinded_payinfo_1 = BlindedPayInfo {
7493 fee_proportional_millionths: 0,
7494 htlc_minimum_msat: 0,
7495 htlc_maximum_msat: 30_000,
7496 cltv_expiry_delta: 0,
7497 features: BlindedHopFeatures::empty(),
7500 let mut blinded_path_2 = blinded_path_1.clone();
7501 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7502 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7503 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7505 let blinded_hints = vec![
7506 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7507 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7509 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7510 .with_bolt12_features(bolt12_features).unwrap();
7512 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7513 route_params.max_total_routing_fee_msat = Some(100_000);
7514 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7515 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7516 assert_eq!(route.paths.len(), 2);
7517 let mut total_amount_paid_msat = 0;
7518 for path in route.paths.into_iter() {
7519 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7520 if let Some(bt) = &path.blinded_tail {
7521 assert_eq!(bt.blinding_point,
7522 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7523 .map(|(_, bp)| bp.blinding_point).unwrap());
7524 } else { panic!(); }
7525 total_amount_paid_msat += path.final_value_msat();
7527 assert_eq!(total_amount_paid_msat, 100_000);
7531 fn direct_to_intro_node() {
7532 // This previously caused a debug panic in the router when asserting
7533 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7534 // direct channels we failed to account for the fee charged for use of the blinded path.
7537 // node0 -1(1)2 - node1
7538 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7539 // doesn't account for the blinded path fee.
7541 let secp_ctx = Secp256k1::new();
7542 let logger = Arc::new(ln_test_utils::TestLogger::new());
7543 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7544 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7545 let scorer = ln_test_utils::TestScorer::new();
7546 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7547 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7549 let amt_msat = 10_000_000;
7550 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7551 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7552 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7553 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7554 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7555 short_channel_id: 1,
7558 cltv_expiry_delta: 42,
7559 htlc_minimum_msat: 1_000,
7560 htlc_maximum_msat: 10_000_000,
7562 fee_proportional_millionths: 0,
7563 excess_data: Vec::new()
7565 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7566 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7567 short_channel_id: 1,
7570 cltv_expiry_delta: 42,
7571 htlc_minimum_msat: 1_000,
7572 htlc_maximum_msat: 10_000_000,
7574 fee_proportional_millionths: 0,
7575 excess_data: Vec::new()
7577 let first_hops = vec![
7578 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7580 let blinded_path = BlindedPath {
7581 introduction_node_id: nodes[1],
7582 blinding_point: ln_test_utils::pubkey(42),
7584 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7585 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7588 let blinded_payinfo = BlindedPayInfo {
7589 fee_base_msat: 1000,
7590 fee_proportional_millionths: 0,
7591 htlc_minimum_msat: 1000,
7592 htlc_maximum_msat: MAX_VALUE_MSAT,
7593 cltv_expiry_delta: 0,
7594 features: BlindedHopFeatures::empty(),
7596 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7598 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7600 let netgraph = network_graph.read_only();
7601 let route_params = RouteParameters::from_payment_params_and_value(
7602 payment_params.clone(), amt_msat);
7603 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7604 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7605 &Default::default(), &random_seed_bytes) {
7606 assert_eq!(err, "Failed to find a path to the given destination");
7607 } else { panic!("Expected error") }
7609 // Sending an exact amount accounting for the blinded path fee works.
7610 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7611 let route_params = RouteParameters::from_payment_params_and_value(
7612 payment_params, amt_minus_blinded_path_fee);
7613 let route = get_route(&nodes[0], &route_params, &netgraph,
7614 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7615 &Default::default(), &random_seed_bytes).unwrap();
7616 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7617 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7621 fn direct_to_matching_intro_nodes() {
7622 // This previously caused us to enter `unreachable` code in the following situation:
7623 // 1. We add a route candidate for intro_node contributing a high amount
7624 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7625 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7626 // amount, and update our route candidate for intro_node for the lower amount
7627 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7628 // lower contribution amount, but fail (this was previously caused by failure to account for
7629 // blinded path fees when adding first_hop<>intro_node candidates)
7630 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7631 // candidate still thinks its path is contributing the original higher amount. This caused us
7632 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7634 let secp_ctx = Secp256k1::new();
7635 let logger = Arc::new(ln_test_utils::TestLogger::new());
7636 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7637 let scorer = ln_test_utils::TestScorer::new();
7638 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7639 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7640 let config = UserConfig::default();
7642 // Values are taken from the fuzz input that uncovered this panic.
7643 let amt_msat = 21_7020_5185_1403_2640;
7644 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7645 let first_hops = vec![
7646 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7647 18446744073709551615)];
7649 let blinded_path = BlindedPath {
7650 introduction_node_id: nodes[1],
7651 blinding_point: ln_test_utils::pubkey(42),
7653 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7654 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7657 let blinded_payinfo = BlindedPayInfo {
7658 fee_base_msat: 5046_2720,
7659 fee_proportional_millionths: 0,
7660 htlc_minimum_msat: 4503_5996_2737_0496,
7661 htlc_maximum_msat: 45_0359_9627_3704_9600,
7662 cltv_expiry_delta: 0,
7663 features: BlindedHopFeatures::empty(),
7665 let mut blinded_hints = vec![
7666 (blinded_payinfo.clone(), blinded_path.clone()),
7667 (blinded_payinfo.clone(), blinded_path.clone()),
7669 blinded_hints[1].0.fee_base_msat = 419_4304;
7670 blinded_hints[1].0.fee_proportional_millionths = 257;
7671 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7672 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7673 blinded_hints[1].0.cltv_expiry_delta = 0;
7675 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7676 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7677 .with_bolt12_features(bolt12_features).unwrap();
7679 let netgraph = network_graph.read_only();
7680 let route_params = RouteParameters::from_payment_params_and_value(
7681 payment_params, amt_msat);
7682 let route = get_route(&nodes[0], &route_params, &netgraph,
7683 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7684 &Default::default(), &random_seed_bytes).unwrap();
7685 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7686 assert_eq!(route.get_total_amount(), amt_msat);
7690 fn we_are_intro_node_candidate_hops() {
7691 // This previously led to a panic in the router because we'd generate a Path with only a
7692 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7693 // where the origin node is the intro node. We now fully disallow considering candidate hops
7694 // where the origin node is the intro node.
7695 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7696 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7697 let scorer = ln_test_utils::TestScorer::new();
7698 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7699 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7700 let config = UserConfig::default();
7702 // Values are taken from the fuzz input that uncovered this panic.
7703 let amt_msat = 21_7020_5185_1423_0019;
7705 let blinded_path = BlindedPath {
7706 introduction_node_id: our_id,
7707 blinding_point: ln_test_utils::pubkey(42),
7709 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7710 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7713 let blinded_payinfo = BlindedPayInfo {
7714 fee_base_msat: 5052_9027,
7715 fee_proportional_millionths: 0,
7716 htlc_minimum_msat: 21_7020_5185_1423_0019,
7717 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7718 cltv_expiry_delta: 0,
7719 features: BlindedHopFeatures::empty(),
7721 let mut blinded_hints = vec![
7722 (blinded_payinfo.clone(), blinded_path.clone()),
7723 (blinded_payinfo.clone(), blinded_path.clone()),
7725 blinded_hints[1].1.introduction_node_id = nodes[6];
7727 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7728 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7729 .with_bolt12_features(bolt12_features.clone()).unwrap();
7731 let netgraph = network_graph.read_only();
7732 let route_params = RouteParameters::from_payment_params_and_value(
7733 payment_params, amt_msat);
7734 if let Err(LightningError { err, .. }) = get_route(
7735 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7737 assert_eq!(err, "Failed to find a path to the given destination");
7742 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7743 // This previously led to a debug panic in the router because we'd find an invalid Path with
7744 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7745 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7746 // the payment, when it was intended to only include the final value of the payment.
7747 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7748 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7749 let scorer = ln_test_utils::TestScorer::new();
7750 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7751 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7752 let config = UserConfig::default();
7754 // Values are taken from the fuzz input that uncovered this panic.
7755 let amt_msat = 21_7020_5185_1423_0019;
7757 let blinded_path = BlindedPath {
7758 introduction_node_id: our_id,
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: 10_4425_1395,
7767 fee_proportional_millionths: 0,
7768 htlc_minimum_msat: 21_7301_9934_9094_0931,
7769 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7770 cltv_expiry_delta: 0,
7771 features: BlindedHopFeatures::empty(),
7773 let mut blinded_hints = vec![
7774 (blinded_payinfo.clone(), blinded_path.clone()),
7775 (blinded_payinfo.clone(), blinded_path.clone()),
7776 (blinded_payinfo.clone(), blinded_path.clone()),
7778 blinded_hints[1].0.fee_base_msat = 5052_9027;
7779 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7780 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7782 blinded_hints[2].1.introduction_node_id = nodes[6];
7784 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7785 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7786 .with_bolt12_features(bolt12_features.clone()).unwrap();
7788 let netgraph = network_graph.read_only();
7789 let route_params = RouteParameters::from_payment_params_and_value(
7790 payment_params, amt_msat);
7791 if let Err(LightningError { err, .. }) = get_route(
7792 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7794 assert_eq!(err, "Failed to find a path to the given destination");
7799 fn min_htlc_overpay_violates_max_htlc() {
7800 do_min_htlc_overpay_violates_max_htlc(true);
7801 do_min_htlc_overpay_violates_max_htlc(false);
7803 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7804 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7805 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7806 // to `targets` and build an invalid path with it, and subsquently hit a debug panic asserting
7807 // that the used liquidity for a hop was less than its available liquidity limit.
7808 let secp_ctx = Secp256k1::new();
7809 let logger = Arc::new(ln_test_utils::TestLogger::new());
7810 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7811 let scorer = ln_test_utils::TestScorer::new();
7812 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7813 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7814 let config = UserConfig::default();
7816 // Values are taken from the fuzz input that uncovered this panic.
7817 let amt_msat = 7_4009_8048;
7818 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7819 let first_hop_outbound_capacity = 2_7345_2000;
7820 let first_hops = vec![get_channel_details(
7821 Some(200), nodes[0], channelmanager::provided_init_features(&config),
7822 first_hop_outbound_capacity
7825 let base_fee = 1_6778_3453;
7826 let htlc_min = 2_5165_8240;
7827 let payment_params = if blinded_payee {
7828 let blinded_path = BlindedPath {
7829 introduction_node_id: nodes[0],
7830 blinding_point: ln_test_utils::pubkey(42),
7832 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7833 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7836 let blinded_payinfo = BlindedPayInfo {
7837 fee_base_msat: base_fee,
7838 fee_proportional_millionths: 0,
7839 htlc_minimum_msat: htlc_min,
7840 htlc_maximum_msat: htlc_min * 1000,
7841 cltv_expiry_delta: 0,
7842 features: BlindedHopFeatures::empty(),
7844 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7845 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
7846 .with_bolt12_features(bolt12_features.clone()).unwrap()
7848 let route_hint = RouteHint(vec![RouteHintHop {
7849 src_node_id: nodes[0],
7850 short_channel_id: 42,
7852 base_msat: base_fee,
7853 proportional_millionths: 0,
7855 cltv_expiry_delta: 10,
7856 htlc_minimum_msat: Some(htlc_min),
7857 htlc_maximum_msat: None,
7860 PaymentParameters::from_node_id(nodes[1], 42)
7861 .with_route_hints(vec![route_hint]).unwrap()
7862 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7865 let netgraph = network_graph.read_only();
7866 let route_params = RouteParameters::from_payment_params_and_value(
7867 payment_params, amt_msat);
7868 if let Err(LightningError { err, .. }) = get_route(
7869 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7870 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7872 assert_eq!(err, "Failed to find a path to the given destination");
7877 fn previously_used_liquidity_violates_max_htlc() {
7878 do_previously_used_liquidity_violates_max_htlc(true);
7879 do_previously_used_liquidity_violates_max_htlc(false);
7882 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
7883 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
7884 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
7885 // candidate. In this case, the candidate does not have enough due to a previous path taking up
7886 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
7887 // asserting that the used liquidity for a hop was less than its available liquidity limit.
7888 let secp_ctx = Secp256k1::new();
7889 let logger = Arc::new(ln_test_utils::TestLogger::new());
7890 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7891 let scorer = ln_test_utils::TestScorer::new();
7892 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7893 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7894 let config = UserConfig::default();
7896 // Values are taken from the fuzz input that uncovered this panic.
7897 let amt_msat = 52_4288;
7898 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7899 let first_hops = vec![get_channel_details(
7900 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
7901 ), get_channel_details(
7902 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
7905 let base_fees = [0, 425_9840, 0, 0];
7906 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
7907 let payment_params = if blinded_payee {
7908 let blinded_path = BlindedPath {
7909 introduction_node_id: nodes[0],
7910 blinding_point: ln_test_utils::pubkey(42),
7912 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7913 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7916 let mut blinded_hints = Vec::new();
7917 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
7918 blinded_hints.push((BlindedPayInfo {
7919 fee_base_msat: *base_fee,
7920 fee_proportional_millionths: 0,
7921 htlc_minimum_msat: *htlc_min,
7922 htlc_maximum_msat: htlc_min * 100,
7923 cltv_expiry_delta: 10,
7924 features: BlindedHopFeatures::empty(),
7925 }, blinded_path.clone()));
7927 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7928 PaymentParameters::blinded(blinded_hints.clone())
7929 .with_bolt12_features(bolt12_features.clone()).unwrap()
7931 let mut route_hints = Vec::new();
7932 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
7933 route_hints.push(RouteHint(vec![RouteHintHop {
7934 src_node_id: nodes[0],
7935 short_channel_id: 42 + idx as u64,
7937 base_msat: *base_fee,
7938 proportional_millionths: 0,
7940 cltv_expiry_delta: 10,
7941 htlc_minimum_msat: Some(*htlc_min),
7942 htlc_maximum_msat: Some(htlc_min * 100),
7945 PaymentParameters::from_node_id(nodes[1], 42)
7946 .with_route_hints(route_hints).unwrap()
7947 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7950 let netgraph = network_graph.read_only();
7951 let route_params = RouteParameters::from_payment_params_and_value(
7952 payment_params, amt_msat);
7954 let route = get_route(
7955 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7956 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7958 assert_eq!(route.paths.len(), 1);
7959 assert_eq!(route.get_total_amount(), amt_msat);
7963 fn candidate_path_min() {
7964 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
7965 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
7966 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
7967 // would add a connecting first_hop node that did not have enough contribution amount, leading
7968 // to a debug panic upon invalid path construction.
7969 let secp_ctx = Secp256k1::new();
7970 let logger = Arc::new(ln_test_utils::TestLogger::new());
7971 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7972 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
7973 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
7974 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7975 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7976 let config = UserConfig::default();
7978 // Values are taken from the fuzz input that uncovered this panic.
7979 let amt_msat = 7_4009_8048;
7980 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
7981 let first_hops = vec![get_channel_details(
7982 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
7985 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
7986 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7987 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7988 short_channel_id: 6,
7991 cltv_expiry_delta: (6 << 4) | 0,
7992 htlc_minimum_msat: 0,
7993 htlc_maximum_msat: MAX_VALUE_MSAT,
7995 fee_proportional_millionths: 0,
7996 excess_data: Vec::new()
7998 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
8000 let htlc_min = 2_5165_8240;
8001 let blinded_hints = vec![
8003 fee_base_msat: 1_6778_3453,
8004 fee_proportional_millionths: 0,
8005 htlc_minimum_msat: htlc_min,
8006 htlc_maximum_msat: htlc_min * 100,
8007 cltv_expiry_delta: 10,
8008 features: BlindedHopFeatures::empty(),
8010 introduction_node_id: nodes[0],
8011 blinding_point: ln_test_utils::pubkey(42),
8013 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8014 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8018 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8019 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8020 .with_bolt12_features(bolt12_features.clone()).unwrap();
8021 let route_params = RouteParameters::from_payment_params_and_value(
8022 payment_params, amt_msat);
8023 let netgraph = network_graph.read_only();
8025 if let Err(LightningError { err, .. }) = get_route(
8026 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8027 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8030 assert_eq!(err, "Failed to find a path to the given destination");
8035 fn path_contribution_includes_min_htlc_overpay() {
8036 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
8037 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
8038 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
8039 // selection, both tested here.
8040 let secp_ctx = Secp256k1::new();
8041 let logger = Arc::new(ln_test_utils::TestLogger::new());
8042 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8043 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8044 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8045 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8046 let config = UserConfig::default();
8048 // Values are taken from the fuzz input that uncovered this panic.
8049 let amt_msat = 562_0000;
8050 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8051 let first_hops = vec![
8052 get_channel_details(
8053 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
8057 let htlc_mins = [49_0000, 1125_0000];
8058 let payment_params = {
8059 let blinded_path = BlindedPath {
8060 introduction_node_id: nodes[0],
8061 blinding_point: ln_test_utils::pubkey(42),
8063 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8064 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8067 let mut blinded_hints = Vec::new();
8068 for htlc_min in htlc_mins.iter() {
8069 blinded_hints.push((BlindedPayInfo {
8071 fee_proportional_millionths: 0,
8072 htlc_minimum_msat: *htlc_min,
8073 htlc_maximum_msat: *htlc_min * 100,
8074 cltv_expiry_delta: 10,
8075 features: BlindedHopFeatures::empty(),
8076 }, blinded_path.clone()));
8078 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8079 PaymentParameters::blinded(blinded_hints.clone())
8080 .with_bolt12_features(bolt12_features.clone()).unwrap()
8083 let netgraph = network_graph.read_only();
8084 let route_params = RouteParameters::from_payment_params_and_value(
8085 payment_params, amt_msat);
8086 let route = get_route(
8087 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8088 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8091 assert_eq!(route.paths.len(), 1);
8092 assert_eq!(route.get_total_amount(), amt_msat);
8096 fn first_hop_preferred_over_hint() {
8097 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
8098 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
8099 let secp_ctx = Secp256k1::new();
8100 let logger = Arc::new(ln_test_utils::TestLogger::new());
8101 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8102 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
8103 let scorer = ln_test_utils::TestScorer::new();
8104 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8105 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8106 let config = UserConfig::default();
8108 let amt_msat = 1_000_000;
8109 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
8111 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
8112 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
8113 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8114 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8115 short_channel_id: 1,
8118 cltv_expiry_delta: 42,
8119 htlc_minimum_msat: 1_000,
8120 htlc_maximum_msat: 10_000_000,
8122 fee_proportional_millionths: 0,
8123 excess_data: Vec::new()
8125 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8126 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8127 short_channel_id: 1,
8130 cltv_expiry_delta: 42,
8131 htlc_minimum_msat: 1_000,
8132 htlc_maximum_msat: 10_000_000,
8134 fee_proportional_millionths: 0,
8135 excess_data: Vec::new()
8138 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
8139 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
8140 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8141 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8142 short_channel_id: 2,
8145 cltv_expiry_delta: 42,
8146 htlc_minimum_msat: 1_000,
8147 htlc_maximum_msat: 10_000_000,
8149 fee_proportional_millionths: 0,
8150 excess_data: Vec::new()
8152 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8153 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8154 short_channel_id: 2,
8157 cltv_expiry_delta: 42,
8158 htlc_minimum_msat: 1_000,
8159 htlc_maximum_msat: 10_000_000,
8161 fee_proportional_millionths: 0,
8162 excess_data: Vec::new()
8165 let dest_node_id = nodes[2];
8167 let route_hint = RouteHint(vec![RouteHintHop {
8168 src_node_id: our_node_id,
8169 short_channel_id: 44,
8172 proportional_millionths: 0,
8174 cltv_expiry_delta: 10,
8175 htlc_minimum_msat: None,
8176 htlc_maximum_msat: Some(5_000_000),
8179 src_node_id: nodes[0],
8180 short_channel_id: 45,
8183 proportional_millionths: 0,
8185 cltv_expiry_delta: 10,
8186 htlc_minimum_msat: None,
8187 htlc_maximum_msat: None,
8190 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8191 .with_route_hints(vec![route_hint]).unwrap()
8192 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8193 let route_params = RouteParameters::from_payment_params_and_value(
8194 payment_params, amt_msat);
8196 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8198 let first_hop = get_channel_details(Some(1), nodes[0],
8199 channelmanager::provided_init_features(&config), 999_999);
8200 let first_hops = vec![first_hop];
8202 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8203 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8204 &Default::default(), &random_seed_bytes).unwrap();
8205 assert_eq!(route.paths.len(), 1);
8206 assert_eq!(route.get_total_amount(), amt_msat);
8207 assert_eq!(route.paths[0].hops.len(), 2);
8208 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8209 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8210 assert_eq!(route.get_total_fees(), 123);
8212 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8213 // for a first hop channel.
8214 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8215 first_hop.outbound_scid_alias = Some(44);
8216 let first_hops = vec![first_hop];
8218 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8219 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8220 &Default::default(), &random_seed_bytes);
8221 assert!(route_res.is_err());
8223 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8224 // use the cheaper second hop of the route hint.
8225 let mut first_hop = get_channel_details(Some(1), nodes[0],
8226 channelmanager::provided_init_features(&config), 10_000_000);
8227 first_hop.outbound_scid_alias = Some(44);
8228 let first_hops = vec![first_hop];
8230 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8231 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8232 &Default::default(), &random_seed_bytes).unwrap();
8233 assert_eq!(route.paths.len(), 1);
8234 assert_eq!(route.get_total_amount(), amt_msat);
8235 assert_eq!(route.paths[0].hops.len(), 2);
8236 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8237 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8238 assert_eq!(route.get_total_fees(), 123);
8242 fn allow_us_being_first_hint() {
8243 // Check that we consider a route hint even if we are the src of the first hop.
8244 let secp_ctx = Secp256k1::new();
8245 let logger = Arc::new(ln_test_utils::TestLogger::new());
8246 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8247 let scorer = ln_test_utils::TestScorer::new();
8248 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8249 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8250 let config = UserConfig::default();
8252 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8254 let amt_msat = 1_000_000;
8255 let dest_node_id = nodes[1];
8257 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8258 let first_hops = vec![first_hop];
8260 let route_hint = RouteHint(vec![RouteHintHop {
8261 src_node_id: our_node_id,
8262 short_channel_id: 44,
8265 proportional_millionths: 0,
8267 cltv_expiry_delta: 10,
8268 htlc_minimum_msat: None,
8269 htlc_maximum_msat: None,
8272 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8273 .with_route_hints(vec![route_hint]).unwrap()
8274 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8276 let route_params = RouteParameters::from_payment_params_and_value(
8277 payment_params, amt_msat);
8280 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8281 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8282 &Default::default(), &random_seed_bytes).unwrap();
8284 assert_eq!(route.paths.len(), 1);
8285 assert_eq!(route.get_total_amount(), amt_msat);
8286 assert_eq!(route.get_total_fees(), 0);
8287 assert_eq!(route.paths[0].hops.len(), 1);
8289 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8293 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
8294 pub(crate) mod bench_utils {
8297 use std::time::Duration;
8299 use bitcoin::hashes::Hash;
8300 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
8302 use crate::chain::transaction::OutPoint;
8303 use crate::routing::scoring::ScoreUpdate;
8304 use crate::sign::{EntropySource, KeysManager};
8305 use crate::ln::ChannelId;
8306 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
8307 use crate::ln::features::Bolt11InvoiceFeatures;
8308 use crate::routing::gossip::NetworkGraph;
8309 use crate::util::config::UserConfig;
8310 use crate::util::ser::ReadableArgs;
8311 use crate::util::test_utils::TestLogger;
8313 /// Tries to open a network graph file, or panics with a URL to fetch it.
8314 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
8315 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
8316 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
8317 .or_else(|_| { // Fall back to guessing based on the binary location
8318 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8319 let mut path = std::env::current_exe().unwrap();
8320 path.pop(); // lightning-...
8322 path.pop(); // debug
8323 path.pop(); // target
8324 path.push("lightning");
8325 path.push("net_graph-2023-01-18.bin");
8328 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8329 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8330 let mut path = std::env::current_exe().unwrap();
8331 path.pop(); // bench...
8333 path.pop(); // debug
8334 path.pop(); // target
8335 path.pop(); // bench
8336 path.push("lightning");
8337 path.push("net_graph-2023-01-18.bin");
8340 .map_err(|_| "Please fetch https://bitcoin.ninja/ldk-net_graph-v0.0.113-2023-01-18.bin and place it at lightning/net_graph-2023-01-18.bin");
8341 #[cfg(require_route_graph_test)]
8342 return Ok(res.unwrap());
8343 #[cfg(not(require_route_graph_test))]
8347 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
8348 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
8351 pub(crate) fn payer_pubkey() -> PublicKey {
8352 let secp_ctx = Secp256k1::new();
8353 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8357 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8359 channel_id: ChannelId::new_zero(),
8360 counterparty: ChannelCounterparty {
8361 features: channelmanager::provided_init_features(&UserConfig::default()),
8363 unspendable_punishment_reserve: 0,
8364 forwarding_info: None,
8365 outbound_htlc_minimum_msat: None,
8366 outbound_htlc_maximum_msat: None,
8368 funding_txo: Some(OutPoint {
8369 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8372 short_channel_id: Some(1),
8373 inbound_scid_alias: None,
8374 outbound_scid_alias: None,
8375 channel_value_satoshis: 10_000_000_000,
8377 balance_msat: 10_000_000_000,
8378 outbound_capacity_msat: 10_000_000_000,
8379 next_outbound_htlc_minimum_msat: 0,
8380 next_outbound_htlc_limit_msat: 10_000_000_000,
8381 inbound_capacity_msat: 0,
8382 unspendable_punishment_reserve: None,
8383 confirmations_required: None,
8384 confirmations: None,
8385 force_close_spend_delay: None,
8387 is_channel_ready: true,
8390 inbound_htlc_minimum_msat: None,
8391 inbound_htlc_maximum_msat: None,
8393 feerate_sat_per_1000_weight: None,
8394 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
8398 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8399 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8400 starting_amount: u64, route_count: usize,
8401 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8402 let payer = payer_pubkey();
8403 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8404 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8406 let nodes = graph.read_only().nodes().clone();
8407 let mut route_endpoints = Vec::new();
8408 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
8409 // with some routes we picked being un-routable.
8410 for _ in 0..route_count * 3 / 2 {
8412 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8413 let src = PublicKey::from_slice(nodes.unordered_keys()
8414 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8415 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8416 let dst = PublicKey::from_slice(nodes.unordered_keys()
8417 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8418 let params = PaymentParameters::from_node_id(dst, 42)
8419 .with_bolt11_features(features.clone()).unwrap();
8420 let first_hop = first_hop(src);
8421 let amt_msat = starting_amount + seed % 1_000_000;
8422 let route_params = RouteParameters::from_payment_params_and_value(
8423 params.clone(), amt_msat);
8425 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8426 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8428 // ...and seed the scorer with success and failure data...
8429 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8430 let mut score_amt = seed % 1_000_000_000;
8432 // Generate fail/success paths for a wider range of potential amounts with
8433 // MPP enabled to give us a chance to apply penalties for more potential
8435 let mpp_features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
8436 let params = PaymentParameters::from_node_id(dst, 42)
8437 .with_bolt11_features(mpp_features).unwrap();
8438 let route_params = RouteParameters::from_payment_params_and_value(
8439 params.clone(), score_amt);
8440 let route_res = get_route(&payer, &route_params, &graph.read_only(),
8441 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
8442 &random_seed_bytes);
8443 if let Ok(route) = route_res {
8444 for path in route.paths {
8445 if seed & 0x80 == 0 {
8446 scorer.payment_path_successful(&path, Duration::ZERO);
8448 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
8449 scorer.payment_path_failed(&path, short_channel_id, Duration::ZERO);
8451 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8455 // If we couldn't find a path with a higer amount, reduce and try again.
8459 route_endpoints.push((first_hop, params, amt_msat));
8465 // Because we've changed channel scores, it's possible we'll take different routes to the
8466 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
8467 // requires a too-high CLTV delta.
8468 route_endpoints.retain(|(first_hop, params, amt_msat)| {
8469 let route_params = RouteParameters::from_payment_params_and_value(
8470 params.clone(), *amt_msat);
8471 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8472 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
8474 route_endpoints.truncate(route_count);
8475 assert_eq!(route_endpoints.len(), route_count);
8483 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8484 use crate::sign::{EntropySource, KeysManager};
8485 use crate::ln::channelmanager;
8486 use crate::ln::features::Bolt11InvoiceFeatures;
8487 use crate::routing::gossip::NetworkGraph;
8488 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
8489 use crate::util::config::UserConfig;
8490 use crate::util::logger::{Logger, Record};
8491 use crate::util::test_utils::TestLogger;
8493 use criterion::Criterion;
8495 struct DummyLogger {}
8496 impl Logger for DummyLogger {
8497 fn log(&self, _record: Record) {}
8500 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8501 let logger = TestLogger::new();
8502 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8503 let scorer = FixedPenaltyScorer::with_penalty(0);
8504 generate_routes(bench, &network_graph, scorer, &Default::default(),
8505 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8508 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8509 let logger = TestLogger::new();
8510 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8511 let scorer = FixedPenaltyScorer::with_penalty(0);
8512 generate_routes(bench, &network_graph, scorer, &Default::default(),
8513 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8514 "generate_mpp_routes_with_zero_penalty_scorer");
8517 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8518 let logger = TestLogger::new();
8519 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8520 let params = ProbabilisticScoringFeeParameters::default();
8521 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8522 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8523 "generate_routes_with_probabilistic_scorer");
8526 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8527 let logger = TestLogger::new();
8528 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8529 let params = ProbabilisticScoringFeeParameters::default();
8530 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8531 generate_routes(bench, &network_graph, scorer, ¶ms,
8532 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8533 "generate_mpp_routes_with_probabilistic_scorer");
8536 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8537 let logger = TestLogger::new();
8538 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8539 let params = ProbabilisticScoringFeeParameters::default();
8540 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8541 generate_routes(bench, &network_graph, scorer, ¶ms,
8542 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8543 "generate_large_mpp_routes_with_probabilistic_scorer");
8546 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8547 let logger = TestLogger::new();
8548 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8549 let mut params = ProbabilisticScoringFeeParameters::default();
8550 params.linear_success_probability = false;
8551 let scorer = ProbabilisticScorer::new(
8552 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8553 generate_routes(bench, &network_graph, scorer, ¶ms,
8554 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8555 "generate_routes_with_nonlinear_probabilistic_scorer");
8558 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8559 let logger = TestLogger::new();
8560 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8561 let mut params = ProbabilisticScoringFeeParameters::default();
8562 params.linear_success_probability = false;
8563 let scorer = ProbabilisticScorer::new(
8564 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8565 generate_routes(bench, &network_graph, scorer, ¶ms,
8566 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8567 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8570 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8571 let logger = TestLogger::new();
8572 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8573 let mut params = ProbabilisticScoringFeeParameters::default();
8574 params.linear_success_probability = false;
8575 let scorer = ProbabilisticScorer::new(
8576 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8577 generate_routes(bench, &network_graph, scorer, ¶ms,
8578 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8579 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8582 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8583 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8584 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8585 bench_name: &'static str,
8587 let payer = bench_utils::payer_pubkey();
8588 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8589 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8591 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8592 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8594 // ...then benchmark finding paths between the nodes we learned.
8596 bench.bench_function(bench_name, |b| b.iter(|| {
8597 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8598 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8599 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8600 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());