1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The router finds paths within a [`NetworkGraph`] for a payment.
12 use bitcoin::secp256k1::{PublicKey, Secp256k1, self};
13 use bitcoin::hashes::Hash;
14 use bitcoin::hashes::sha256::Hash as Sha256;
16 use crate::blinded_path::{BlindedHop, BlindedPath};
17 use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, PaymentConstraints, PaymentRelay, ReceiveTlvs};
18 use crate::ln::PaymentHash;
19 use crate::ln::channelmanager::{ChannelDetails, PaymentId};
20 use crate::ln::features::{BlindedHopFeatures, Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
21 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
22 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice};
23 use crate::onion_message::{DefaultMessageRouter, Destination, MessageRouter, OnionMessagePath};
24 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
25 use crate::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp};
26 use crate::sign::EntropySource;
27 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
28 use crate::util::logger::{Level, Logger};
29 use crate::util::chacha20::ChaCha20;
32 use crate::prelude::*;
33 use crate::sync::Mutex;
34 use alloc::collections::BinaryHeap;
38 /// A [`Router`] implemented using [`find_route`].
39 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> where
41 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
45 random_seed_bytes: Mutex<[u8; 32]>,
48 message_router: DefaultMessageRouter<G, L>,
51 impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> DefaultRouter<G, L, S, SP, Sc> where
53 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
55 /// Creates a new router.
56 pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32], scorer: S, score_params: SP) -> Self {
57 let random_seed_bytes = Mutex::new(random_seed_bytes);
58 let message_router = DefaultMessageRouter::new(network_graph.clone());
59 Self { network_graph, logger, random_seed_bytes, scorer, score_params, message_router }
63 impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> Router for DefaultRouter<G, L, S, SP, Sc> where
65 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
70 params: &RouteParameters,
71 first_hops: Option<&[&ChannelDetails]>,
72 inflight_htlcs: InFlightHtlcs
73 ) -> Result<Route, LightningError> {
74 let random_seed_bytes = {
75 let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
76 *locked_random_seed_bytes = Sha256::hash(&*locked_random_seed_bytes).to_byte_array();
77 *locked_random_seed_bytes
80 payer, params, &self.network_graph, first_hops, &*self.logger,
81 &ScorerAccountingForInFlightHtlcs::new(self.scorer.read_lock(), &inflight_htlcs),
87 fn create_blinded_payment_paths<
88 ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
90 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
91 amount_msats: u64, entropy_source: &ES, secp_ctx: &Secp256k1<T>
92 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
93 // Limit the number of blinded paths that are computed.
94 const MAX_PAYMENT_PATHS: usize = 3;
96 // Ensure peers have at least three channels so that it is more difficult to infer the
97 // recipient's node_id.
98 const MIN_PEER_CHANNELS: usize = 3;
100 let network_graph = self.network_graph.deref().read_only();
101 let paths = first_hops.into_iter()
102 .filter(|details| details.counterparty.features.supports_route_blinding())
103 .filter(|details| amount_msats <= details.inbound_capacity_msat)
104 .filter(|details| amount_msats >= details.inbound_htlc_minimum_msat.unwrap_or(0))
105 .filter(|details| amount_msats <= details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX))
106 .filter(|details| network_graph
107 .node(&NodeId::from_pubkey(&details.counterparty.node_id))
108 .map(|node_info| node_info.channels.len() >= MIN_PEER_CHANNELS)
111 .filter_map(|details| {
112 let short_channel_id = match details.get_inbound_payment_scid() {
113 Some(short_channel_id) => short_channel_id,
116 let payment_relay: PaymentRelay = match details.counterparty.forwarding_info {
117 Some(forwarding_info) => forwarding_info.into(),
121 // Avoid exposing esoteric CLTV expiry deltas
122 let cltv_expiry_delta = match payment_relay.cltv_expiry_delta {
130 let payment_constraints = PaymentConstraints {
131 max_cltv_expiry: tlvs.payment_constraints.max_cltv_expiry + cltv_expiry_delta,
132 htlc_minimum_msat: details.inbound_htlc_minimum_msat.unwrap_or(0),
139 features: BlindedHopFeatures::empty(),
141 node_id: details.counterparty.node_id,
142 htlc_maximum_msat: details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX),
145 .map(|forward_node| {
146 BlindedPath::new_for_payment(
147 &[forward_node], recipient, tlvs.clone(), u64::MAX, entropy_source, secp_ctx
150 .take(MAX_PAYMENT_PATHS)
151 .collect::<Result<Vec<_>, _>>();
154 Ok(paths) if !paths.is_empty() => Ok(paths),
156 if network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient)) {
157 BlindedPath::one_hop_for_payment(recipient, tlvs, entropy_source, secp_ctx)
158 .map(|path| vec![path])
167 impl< G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> MessageRouter for DefaultRouter<G, L, S, SP, Sc> where
169 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
172 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
173 ) -> Result<OnionMessagePath, ()> {
174 self.message_router.find_path(sender, peers, destination)
177 fn create_blinded_paths<
178 ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
180 &self, recipient: PublicKey, peers: Vec<PublicKey>, entropy_source: &ES,
181 secp_ctx: &Secp256k1<T>
182 ) -> Result<Vec<BlindedPath>, ()> {
183 self.message_router.create_blinded_paths(recipient, peers, entropy_source, secp_ctx)
187 /// A trait defining behavior for routing a payment.
188 pub trait Router: MessageRouter {
189 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
191 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
192 /// and [`RouteParameters::final_value_msat`], respectively.
194 &self, payer: &PublicKey, route_params: &RouteParameters,
195 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
196 ) -> Result<Route, LightningError>;
198 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
200 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
201 /// and [`RouteParameters::final_value_msat`], respectively.
203 /// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
205 fn find_route_with_id(
206 &self, payer: &PublicKey, route_params: &RouteParameters,
207 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
208 _payment_hash: PaymentHash, _payment_id: PaymentId
209 ) -> Result<Route, LightningError> {
210 self.find_route(payer, route_params, first_hops, inflight_htlcs)
213 /// Creates [`BlindedPath`]s for payment to the `recipient` node. The channels in `first_hops`
214 /// are assumed to be with the `recipient`'s peers. The payment secret and any constraints are
216 fn create_blinded_payment_paths<
217 ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
219 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
220 amount_msats: u64, entropy_source: &ES, secp_ctx: &Secp256k1<T>
221 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()>;
224 /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
226 /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
229 /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
230 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> where S::Target: ScoreLookUp {
232 // Maps a channel's short channel id and its direction to the liquidity used up.
233 inflight_htlcs: &'a InFlightHtlcs,
235 impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
236 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
237 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
238 ScorerAccountingForInFlightHtlcs {
245 impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
246 type ScoreParams = <S::Target as ScoreLookUp>::ScoreParams;
247 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
248 let target = match candidate.target() {
249 Some(target) => target,
250 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
252 let short_channel_id = match candidate.short_channel_id() {
253 Some(short_channel_id) => short_channel_id,
254 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
256 let source = candidate.source();
257 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
258 &source, &target, short_channel_id
260 let usage = ChannelUsage {
261 inflight_htlc_msat: usage.inflight_htlc_msat.saturating_add(used_liquidity),
265 self.scorer.channel_penalty_msat(candidate, usage, score_params)
267 self.scorer.channel_penalty_msat(candidate, usage, score_params)
272 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
273 /// in-use channel liquidity.
275 pub struct InFlightHtlcs(
276 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
277 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
278 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
280 HashMap<(u64, bool), u64>
284 /// Constructs an empty `InFlightHtlcs`.
285 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
287 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
288 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
289 if path.hops.is_empty() { return };
291 let mut cumulative_msat = 0;
292 if let Some(tail) = &path.blinded_tail {
293 cumulative_msat += tail.final_value_msat;
296 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
297 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
298 // the router excludes the payer node. In the following lines, the payer's information is
299 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
300 // in our sliding window of two.
301 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
302 .map(|hop| hop.pubkey)
303 .chain(core::iter::once(payer_node_id));
305 // Taking the reversed vector from above, we zip it with just the reversed hops list to
306 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
307 // the total amount sent.
308 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
309 cumulative_msat += next_hop.fee_msat;
311 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
312 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
313 .or_insert(cumulative_msat);
317 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
319 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
321 .entry((channel_scid, source < target))
322 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
323 .or_insert(used_msat);
326 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
328 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
329 self.0.get(&(channel_scid, source < target)).map(|v| *v)
333 impl Writeable for InFlightHtlcs {
334 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
337 impl Readable for InFlightHtlcs {
338 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
339 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
340 Ok(Self(infight_map))
344 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
345 /// that leads to it.
346 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
347 pub struct RouteHop {
348 /// The node_id of the node at this hop.
349 pub pubkey: PublicKey,
350 /// The node_announcement features of the node at this hop. For the last hop, these may be
351 /// amended to match the features present in the invoice this node generated.
352 pub node_features: NodeFeatures,
353 /// The channel that should be used from the previous hop to reach this node.
354 pub short_channel_id: u64,
355 /// The channel_announcement features of the channel that should be used from the previous hop
356 /// to reach this node.
357 pub channel_features: ChannelFeatures,
358 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
359 /// If this is the last hop in [`Path::hops`]:
360 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
361 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
363 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
365 /// The CLTV delta added for this hop.
366 /// If this is the last hop in [`Path::hops`]:
367 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
368 /// * otherwise, this is the CLTV delta expected at the destination
370 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
371 pub cltv_expiry_delta: u32,
372 /// Indicates whether this hop is possibly announced in the public network graph.
374 /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
375 /// either know for sure it's announced in the public graph, or if any public channels exist
376 /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
377 /// the channel to be unannounced.
379 /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
380 pub maybe_announced_channel: bool,
383 impl_writeable_tlv_based!(RouteHop, {
384 (0, pubkey, required),
385 (1, maybe_announced_channel, (default_value, true)),
386 (2, node_features, required),
387 (4, short_channel_id, required),
388 (6, channel_features, required),
389 (8, fee_msat, required),
390 (10, cltv_expiry_delta, required),
393 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
394 /// their [`Bolt12Invoice`].
396 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
397 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
398 pub struct BlindedTail {
399 /// The hops of the [`BlindedPath`] provided by the recipient.
401 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
402 pub hops: Vec<BlindedHop>,
403 /// The blinding point of the [`BlindedPath`] provided by the recipient.
405 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
406 pub blinding_point: PublicKey,
407 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
408 /// inferring the destination. May be 0.
409 pub excess_final_cltv_expiry_delta: u32,
410 /// The total amount paid on this [`Path`], excluding the fees.
411 pub final_value_msat: u64,
414 impl_writeable_tlv_based!(BlindedTail, {
415 (0, hops, required_vec),
416 (2, blinding_point, required),
417 (4, excess_final_cltv_expiry_delta, required),
418 (6, final_value_msat, required),
421 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
422 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
423 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
425 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
426 pub hops: Vec<RouteHop>,
427 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
428 pub blinded_tail: Option<BlindedTail>,
432 /// Gets the fees for a given path, excluding any excess paid to the recipient.
433 pub fn fee_msat(&self) -> u64 {
434 match &self.blinded_tail {
435 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
437 // Do not count last hop of each path since that's the full value of the payment
438 self.hops.split_last().map_or(0,
439 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
444 /// Gets the total amount paid on this [`Path`], excluding the fees.
445 pub fn final_value_msat(&self) -> u64 {
446 match &self.blinded_tail {
447 Some(blinded_tail) => blinded_tail.final_value_msat,
448 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
452 /// Gets the final hop's CLTV expiry delta.
453 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
454 match &self.blinded_tail {
456 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
461 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
462 /// it can take multiple paths. Each path is composed of one or more hops through the network.
463 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
465 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
466 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
468 pub paths: Vec<Path>,
469 /// The `route_params` parameter passed to [`find_route`].
471 /// This is used by `ChannelManager` to track information which may be required for retries.
473 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
474 pub route_params: Option<RouteParameters>,
478 /// Returns the total amount of fees paid on this [`Route`].
480 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
481 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
482 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
484 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
485 pub fn get_total_fees(&self) -> u64 {
486 let overpaid_value_msat = self.route_params.as_ref()
487 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
488 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
491 /// Returns the total amount paid on this [`Route`], excluding the fees.
493 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
494 /// we had to reach the [`htlc_minimum_msat`] limits.
496 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
497 pub fn get_total_amount(&self) -> u64 {
498 self.paths.iter().map(|path| path.final_value_msat()).sum()
502 impl fmt::Display for Route {
503 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
504 log_route!(self).fmt(f)
508 const SERIALIZATION_VERSION: u8 = 1;
509 const MIN_SERIALIZATION_VERSION: u8 = 1;
511 impl Writeable for Route {
512 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
513 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
514 (self.paths.len() as u64).write(writer)?;
515 let mut blinded_tails = Vec::new();
516 for path in self.paths.iter() {
517 (path.hops.len() as u8).write(writer)?;
518 for (idx, hop) in path.hops.iter().enumerate() {
520 if let Some(blinded_tail) = &path.blinded_tail {
521 if blinded_tails.is_empty() {
522 blinded_tails = Vec::with_capacity(path.hops.len());
524 blinded_tails.push(None);
527 blinded_tails.push(Some(blinded_tail));
528 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
531 write_tlv_fields!(writer, {
532 // For compatibility with LDK versions prior to 0.0.117, we take the individual
533 // RouteParameters' fields and reconstruct them on read.
534 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
535 (2, blinded_tails, optional_vec),
536 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
537 (5, self.route_params.as_ref().map(|p| p.max_total_routing_fee_msat), option),
543 impl Readable for Route {
544 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
545 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
546 let path_count: u64 = Readable::read(reader)?;
547 if path_count == 0 { return Err(DecodeError::InvalidValue); }
548 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
549 let mut min_final_cltv_expiry_delta = u32::max_value();
550 for _ in 0..path_count {
551 let hop_count: u8 = Readable::read(reader)?;
552 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
553 for _ in 0..hop_count {
554 hops.push(Readable::read(reader)?);
556 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
557 min_final_cltv_expiry_delta =
558 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
559 paths.push(Path { hops, blinded_tail: None });
561 _init_and_read_len_prefixed_tlv_fields!(reader, {
562 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
563 (2, blinded_tails, optional_vec),
564 (3, final_value_msat, option),
565 (5, max_total_routing_fee_msat, option)
567 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
568 if blinded_tails.len() != 0 {
569 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
570 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
571 path.blinded_tail = blinded_tail_opt;
575 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
576 let route_params = match (payment_params, final_value_msat) {
577 (Some(payment_params), Some(final_value_msat)) => {
578 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
583 Ok(Route { paths, route_params })
587 /// Parameters needed to find a [`Route`].
589 /// Passed to [`find_route`] and [`build_route_from_hops`].
590 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
591 pub struct RouteParameters {
592 /// The parameters of the failed payment path.
593 pub payment_params: PaymentParameters,
595 /// The amount in msats sent on the failed payment path.
596 pub final_value_msat: u64,
598 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
600 /// This limit also applies to the total fees that may arise while retrying failed payment
603 /// Note that values below a few sats may result in some paths being spuriously ignored.
604 pub max_total_routing_fee_msat: Option<u64>,
607 impl RouteParameters {
608 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
610 /// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
611 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
612 Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
616 impl Writeable for RouteParameters {
617 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
618 write_tlv_fields!(writer, {
619 (0, self.payment_params, required),
620 (1, self.max_total_routing_fee_msat, option),
621 (2, self.final_value_msat, required),
622 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
623 // `RouteParameters` directly. For compatibility, we write it here.
624 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
630 impl Readable for RouteParameters {
631 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
632 _init_and_read_len_prefixed_tlv_fields!(reader, {
633 (0, payment_params, (required: ReadableArgs, 0)),
634 (1, max_total_routing_fee_msat, option),
635 (2, final_value_msat, required),
636 (4, final_cltv_delta, option),
638 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
639 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
640 if final_cltv_expiry_delta == &0 {
641 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
646 final_value_msat: final_value_msat.0.unwrap(),
647 max_total_routing_fee_msat,
652 /// Maximum total CTLV difference we allow for a full payment path.
653 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
655 /// Maximum number of paths we allow an (MPP) payment to have.
656 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
657 // limits, but for now more than 10 paths likely carries too much one-path failure.
658 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
660 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
662 // The median hop CLTV expiry delta currently seen in the network.
663 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
665 // During routing, we only consider paths shorter than our maximum length estimate.
666 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
667 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
668 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
670 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
671 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
672 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
673 // (payment_secret and total_msat) = 93 bytes for the final hop.
674 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
675 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
676 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
678 /// Information used to route a payment.
679 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
680 pub struct PaymentParameters {
681 /// Information about the payee, such as their features and route hints for their channels.
684 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
685 pub expiry_time: Option<u64>,
687 /// The maximum total CLTV delta we accept for the route.
688 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
689 pub max_total_cltv_expiry_delta: u32,
691 /// The maximum number of paths that may be used by (MPP) payments.
692 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
693 pub max_path_count: u8,
695 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
696 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
697 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
698 /// increasing failure probability for those paths.
700 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
701 /// restriction have been found. While paths which meet this criteria will be searched for, it
702 /// is ultimately up to the scorer to select them over other paths.
704 /// A value of 0 will allow payments up to and including a channel's total announced usable
705 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
708 pub max_channel_saturation_power_of_half: u8,
710 /// A list of SCIDs which this payment was previously attempted over and which caused the
711 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
713 pub previously_failed_channels: Vec<u64>,
716 impl Writeable for PaymentParameters {
717 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
718 let mut clear_hints = &vec![];
719 let mut blinded_hints = &vec![];
721 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
722 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
724 write_tlv_fields!(writer, {
725 (0, self.payee.node_id(), option),
726 (1, self.max_total_cltv_expiry_delta, required),
727 (2, self.payee.features(), option),
728 (3, self.max_path_count, required),
729 (4, *clear_hints, required_vec),
730 (5, self.max_channel_saturation_power_of_half, required),
731 (6, self.expiry_time, option),
732 (7, self.previously_failed_channels, required_vec),
733 (8, *blinded_hints, optional_vec),
734 (9, self.payee.final_cltv_expiry_delta(), option),
740 impl ReadableArgs<u32> for PaymentParameters {
741 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
742 _init_and_read_len_prefixed_tlv_fields!(reader, {
743 (0, payee_pubkey, option),
744 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
745 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
746 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
747 (4, clear_route_hints, required_vec),
748 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
749 (6, expiry_time, option),
750 (7, previously_failed_channels, optional_vec),
751 (8, blinded_route_hints, optional_vec),
752 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
754 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
755 let payee = if blinded_route_hints.len() != 0 {
756 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
758 route_hints: blinded_route_hints,
759 features: features.and_then(|f: Features| f.bolt12()),
763 route_hints: clear_route_hints,
764 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
765 features: features.and_then(|f| f.bolt11()),
766 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
770 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
771 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
773 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
775 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
781 impl PaymentParameters {
782 /// Creates a payee with the node id of the given `pubkey`.
784 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
786 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
788 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
790 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
791 max_path_count: DEFAULT_MAX_PATH_COUNT,
792 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
793 previously_failed_channels: Vec::new(),
797 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
799 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
802 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
803 /// whether your router will be allowed to find a multi-part route for this payment. If you
804 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
805 /// [`RecipientOnionFields::secret_only`].
807 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
808 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
809 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
810 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
811 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
814 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
815 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
816 /// [`PaymentParameters::expiry_time`].
817 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
818 Self::blinded(invoice.payment_paths().to_vec())
819 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
820 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
823 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
824 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
826 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
828 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
829 max_path_count: DEFAULT_MAX_PATH_COUNT,
830 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
831 previously_failed_channels: Vec::new(),
835 /// Includes the payee's features. Errors if the parameters were not initialized with
836 /// [`PaymentParameters::from_bolt12_invoice`].
838 /// This is not exported to bindings users since bindings don't support move semantics
839 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
841 Payee::Clear { .. } => Err(()),
842 Payee::Blinded { route_hints, .. } =>
843 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
847 /// Includes the payee's features. Errors if the parameters were initialized with
848 /// [`PaymentParameters::from_bolt12_invoice`].
850 /// This is not exported to bindings users since bindings don't support move semantics
851 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
853 Payee::Blinded { .. } => Err(()),
854 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
856 payee: Payee::Clear {
857 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
863 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
864 /// [`PaymentParameters::from_bolt12_invoice`].
866 /// This is not exported to bindings users since bindings don't support move semantics
867 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
869 Payee::Blinded { .. } => Err(()),
870 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
872 payee: Payee::Clear {
873 route_hints, node_id, features, final_cltv_expiry_delta,
879 /// Includes a payment expiration in seconds relative to the UNIX epoch.
881 /// This is not exported to bindings users since bindings don't support move semantics
882 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
883 Self { expiry_time: Some(expiry_time), ..self }
886 /// Includes a limit for the total CLTV expiry delta which is considered during routing
888 /// This is not exported to bindings users since bindings don't support move semantics
889 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
890 Self { max_total_cltv_expiry_delta, ..self }
893 /// Includes a limit for the maximum number of payment paths that may be used.
895 /// This is not exported to bindings users since bindings don't support move semantics
896 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
897 Self { max_path_count, ..self }
900 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
901 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
903 /// This is not exported to bindings users since bindings don't support move semantics
904 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
905 Self { max_channel_saturation_power_of_half, ..self }
909 /// The recipient of a payment, differing based on whether they've hidden their identity with route
911 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
913 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
914 /// will be included in the final [`Route`].
916 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
918 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
919 /// Features supported by the payee.
921 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
923 features: Option<Bolt12InvoiceFeatures>,
925 /// The recipient included these route hints in their BOLT11 invoice.
927 /// The node id of the payee.
929 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
930 route_hints: Vec<RouteHint>,
931 /// Features supported by the payee.
933 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
934 /// does not contain any features.
936 /// [`for_keysend`]: PaymentParameters::for_keysend
937 features: Option<Bolt11InvoiceFeatures>,
938 /// The minimum CLTV delta at the end of the route. This value must not be zero.
939 final_cltv_expiry_delta: u32,
944 fn node_id(&self) -> Option<PublicKey> {
946 Self::Clear { node_id, .. } => Some(*node_id),
950 fn node_features(&self) -> Option<NodeFeatures> {
952 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
953 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
956 fn supports_basic_mpp(&self) -> bool {
958 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
959 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
962 fn features(&self) -> Option<FeaturesRef> {
964 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
965 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
968 fn final_cltv_expiry_delta(&self) -> Option<u32> {
970 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
974 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
976 Self::Blinded { route_hints, .. } => &route_hints[..],
977 Self::Clear { .. } => &[]
981 fn unblinded_route_hints(&self) -> &[RouteHint] {
983 Self::Blinded { .. } => &[],
984 Self::Clear { route_hints, .. } => &route_hints[..]
989 enum FeaturesRef<'a> {
990 Bolt11(&'a Bolt11InvoiceFeatures),
991 Bolt12(&'a Bolt12InvoiceFeatures),
994 Bolt11(Bolt11InvoiceFeatures),
995 Bolt12(Bolt12InvoiceFeatures),
999 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
1001 Self::Bolt12(f) => Some(f),
1005 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
1007 Self::Bolt11(f) => Some(f),
1013 impl<'a> Writeable for FeaturesRef<'a> {
1014 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1016 Self::Bolt11(f) => Ok(f.write(w)?),
1017 Self::Bolt12(f) => Ok(f.write(w)?),
1022 impl ReadableArgs<bool> for Features {
1023 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
1024 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
1025 Ok(Self::Bolt12(Readable::read(reader)?))
1029 /// A list of hops along a payment path terminating with a channel to the recipient.
1030 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1031 pub struct RouteHint(pub Vec<RouteHintHop>);
1033 impl Writeable for RouteHint {
1034 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1035 (self.0.len() as u64).write(writer)?;
1036 for hop in self.0.iter() {
1043 impl Readable for RouteHint {
1044 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1045 let hop_count: u64 = Readable::read(reader)?;
1046 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
1047 for _ in 0..hop_count {
1048 hops.push(Readable::read(reader)?);
1054 /// A channel descriptor for a hop along a payment path.
1056 /// While this generally comes from BOLT 11's `r` field, this struct includes more fields than are
1057 /// available in BOLT 11. Thus, encoding and decoding this via `lightning-invoice` is lossy, as
1058 /// fields not supported in BOLT 11 will be stripped.
1059 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1060 pub struct RouteHintHop {
1061 /// The node_id of the non-target end of the route
1062 pub src_node_id: PublicKey,
1063 /// The short_channel_id of this channel
1064 pub short_channel_id: u64,
1065 /// The fees which must be paid to use this channel
1066 pub fees: RoutingFees,
1067 /// The difference in CLTV values between this node and the next node.
1068 pub cltv_expiry_delta: u16,
1069 /// The minimum value, in msat, which must be relayed to the next hop.
1070 pub htlc_minimum_msat: Option<u64>,
1071 /// The maximum value in msat available for routing with a single HTLC.
1072 pub htlc_maximum_msat: Option<u64>,
1075 impl_writeable_tlv_based!(RouteHintHop, {
1076 (0, src_node_id, required),
1077 (1, htlc_minimum_msat, option),
1078 (2, short_channel_id, required),
1079 (3, htlc_maximum_msat, option),
1080 (4, fees, required),
1081 (6, cltv_expiry_delta, required),
1084 #[derive(Eq, PartialEq)]
1085 #[repr(align(64))] // Force the size to 64 bytes
1086 struct RouteGraphNode {
1089 // The maximum value a yet-to-be-constructed payment path might flow through this node.
1090 // This value is upper-bounded by us by:
1091 // - how much is needed for a path being constructed
1092 // - how much value can channels following this node (up to the destination) can contribute,
1093 // considering their capacity and fees
1094 value_contribution_msat: u64,
1095 total_cltv_delta: u32,
1096 /// The number of hops walked up to this node.
1097 path_length_to_node: u8,
1100 impl cmp::Ord for RouteGraphNode {
1101 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
1102 other.score.cmp(&self.score).then_with(|| other.node_id.cmp(&self.node_id))
1106 impl cmp::PartialOrd for RouteGraphNode {
1107 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
1108 Some(self.cmp(other))
1112 // While RouteGraphNode can be laid out with fewer bytes, performance appears to be improved
1113 // substantially when it is laid out at exactly 64 bytes.
1114 const _GRAPH_NODE_SMALL: usize = 64 - core::mem::size_of::<RouteGraphNode>();
1115 const _GRAPH_NODE_FIXED_SIZE: usize = core::mem::size_of::<RouteGraphNode>() - 64;
1117 /// A [`CandidateRouteHop::FirstHop`] entry.
1118 #[derive(Clone, Debug)]
1119 pub struct CandidateFirstHop<'a> {
1120 /// Channel details of the first hop
1122 /// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1123 /// has been funded and is able to pay), and accessor methods may panic otherwise.
1125 /// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1126 pub details: &'a ChannelDetails,
1127 /// The node id of the payer, which is also the source side of this candidate route hop.
1128 pub payer_node_id: &'a NodeId,
1129 /// A unique ID which describes the payer. It will not conlict with any
1130 /// [`NodeInfo::node_counter`]s, but may be equal to one if the payer is a public node.
1131 payer_node_counter: u32,
1132 /// A unique ID which describes the first hop counterparty. It will not conlict with any
1133 /// [`NodeInfo::node_counter`]s, but may be equal to one if the counterparty is a public node.
1134 target_node_counter: u32,
1137 /// A [`CandidateRouteHop::PublicHop`] entry.
1138 #[derive(Clone, Debug)]
1139 pub struct CandidatePublicHop<'a> {
1140 /// Information about the channel, including potentially its capacity and
1141 /// direction-specific information.
1142 pub info: DirectedChannelInfo<'a>,
1143 /// The short channel ID of the channel, i.e. the identifier by which we refer to this
1145 pub short_channel_id: u64,
1148 /// A [`CandidateRouteHop::PrivateHop`] entry.
1149 #[derive(Clone, Debug)]
1150 pub struct CandidatePrivateHop<'a> {
1151 /// Information about the private hop communicated via BOLT 11.
1152 pub hint: &'a RouteHintHop,
1153 /// Node id of the next hop in BOLT 11 route hint.
1154 pub target_node_id: &'a NodeId,
1155 /// A unique ID which describes the source node of the hop (further from the payment target).
1156 /// It will not conlict with any [`NodeInfo::node_counter`]s, but may be equal to one if the
1157 /// node is a public node.
1158 source_node_counter: u32,
1159 /// A unique ID which describes the destination node of the hop (towards the payment target).
1160 /// It will not conlict with any [`NodeInfo::node_counter`]s, but may be equal to one if the
1161 /// node is a public node.
1162 target_node_counter: u32,
1166 /// A [`CandidateRouteHop::Blinded`] entry.
1167 #[derive(Clone, Debug)]
1168 pub struct CandidateBlindedPath<'a> {
1169 /// Information about the blinded path including the fee, HTLC amount limits, and
1170 /// cryptographic material required to build an HTLC through the given path.
1171 pub hint: &'a (BlindedPayInfo, BlindedPath),
1172 /// Index of the hint in the original list of blinded hints.
1174 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1175 /// a short channel ID for this hop.
1177 /// A unique ID which describes the introduction point of the blinded path.
1178 /// It will not conlict with any [`NodeInfo::node_counter`]s, but will generally be equal to
1179 /// one from the public network graph (assuming the introduction point is a public node).
1180 source_node_counter: u32,
1183 /// A [`CandidateRouteHop::OneHopBlinded`] entry.
1184 #[derive(Clone, Debug)]
1185 pub struct CandidateOneHopBlindedPath<'a> {
1186 /// Information about the blinded path including the fee, HTLC amount limits, and
1187 /// cryptographic material required to build an HTLC terminating with the given path.
1189 /// Note that the [`BlindedPayInfo`] is ignored here.
1190 pub hint: &'a (BlindedPayInfo, BlindedPath),
1191 /// Index of the hint in the original list of blinded hints.
1193 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1194 /// a short channel ID for this hop.
1196 /// A unique ID which describes the introduction point of the blinded path.
1197 /// It will not conlict with any [`NodeInfo::node_counter`]s, but will generally be equal to
1198 /// one from the public network graph (assuming the introduction point is a public node).
1199 source_node_counter: u32,
1202 /// A wrapper around the various hop representations.
1204 /// Can be used to examine the properties of a hop,
1205 /// potentially to decide whether to include it in a route.
1206 #[derive(Clone, Debug)]
1207 pub enum CandidateRouteHop<'a> {
1208 /// A hop from the payer, where the outbound liquidity is known.
1209 FirstHop(CandidateFirstHop<'a>),
1210 /// A hop found in the [`ReadOnlyNetworkGraph`].
1211 PublicHop(CandidatePublicHop<'a>),
1212 /// A private hop communicated by the payee, generally via a BOLT 11 invoice.
1214 /// Because BOLT 11 route hints can take multiple hops to get to the destination, this may not
1215 /// terminate at the payee.
1216 PrivateHop(CandidatePrivateHop<'a>),
1217 /// A blinded path which starts with an introduction point and ultimately terminates with the
1220 /// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1221 /// `None` in this state.
1223 /// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1224 /// path, the full path is treated as a single [`CandidateRouteHop`].
1225 Blinded(CandidateBlindedPath<'a>),
1226 /// Similar to [`Self::Blinded`], but the path here only has one hop.
1228 /// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1229 /// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1230 /// payee's identity - it's the introduction point!
1232 /// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1233 /// to the hops *between* the introduction node and the destination.
1235 /// This primarily exists to track that we need to included a blinded path at the end of our
1236 /// [`Route`], even though it doesn't actually add an additional hop in the payment.
1237 OneHopBlinded(CandidateOneHopBlindedPath<'a>),
1240 impl<'a> CandidateRouteHop<'a> {
1241 /// Returns the short channel ID for this hop, if one is known.
1243 /// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1244 /// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1246 /// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1247 /// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1248 /// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1249 /// (which is always true for channels which are funded and ready for use).
1251 /// In other words, this should always return `Some` as long as the candidate hop is not a
1252 /// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1254 /// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1255 /// define a global namespace.
1257 fn short_channel_id(&self) -> Option<u64> {
1259 CandidateRouteHop::FirstHop(hop) => hop.details.get_outbound_payment_scid(),
1260 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1261 CandidateRouteHop::PrivateHop(hop) => Some(hop.hint.short_channel_id),
1262 CandidateRouteHop::Blinded(_) => None,
1263 CandidateRouteHop::OneHopBlinded(_) => None,
1267 /// Returns the globally unique short channel ID for this hop, if one is known.
1269 /// This only returns `Some` if the channel is public (either our own, or one we've learned
1270 /// from the public network graph), and thus the short channel ID we have for this channel is
1271 /// globally unique and identifies this channel in a global namespace.
1273 pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1275 CandidateRouteHop::FirstHop(hop) => if hop.details.is_public { hop.details.short_channel_id } else { None },
1276 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1277 CandidateRouteHop::PrivateHop(_) => None,
1278 CandidateRouteHop::Blinded(_) => None,
1279 CandidateRouteHop::OneHopBlinded(_) => None,
1283 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1284 fn features(&self) -> ChannelFeatures {
1286 CandidateRouteHop::FirstHop(hop) => hop.details.counterparty.features.to_context(),
1287 CandidateRouteHop::PublicHop(hop) => hop.info.channel().features.clone(),
1288 CandidateRouteHop::PrivateHop(_) => ChannelFeatures::empty(),
1289 CandidateRouteHop::Blinded(_) => ChannelFeatures::empty(),
1290 CandidateRouteHop::OneHopBlinded(_) => ChannelFeatures::empty(),
1294 /// Returns the required difference in HTLC CLTV expiry between the [`Self::source`] and the
1295 /// next-hop for an HTLC taking this hop.
1297 /// This is the time that the node(s) in this hop have to claim the HTLC on-chain if the
1298 /// next-hop goes on chain with a payment preimage.
1300 pub fn cltv_expiry_delta(&self) -> u32 {
1302 CandidateRouteHop::FirstHop(_) => 0,
1303 CandidateRouteHop::PublicHop(hop) => hop.info.direction().cltv_expiry_delta as u32,
1304 CandidateRouteHop::PrivateHop(hop) => hop.hint.cltv_expiry_delta as u32,
1305 CandidateRouteHop::Blinded(hop) => hop.hint.0.cltv_expiry_delta as u32,
1306 CandidateRouteHop::OneHopBlinded(_) => 0,
1310 /// Returns the minimum amount that can be sent over this hop, in millisatoshis.
1312 pub fn htlc_minimum_msat(&self) -> u64 {
1314 CandidateRouteHop::FirstHop(hop) => hop.details.next_outbound_htlc_minimum_msat,
1315 CandidateRouteHop::PublicHop(hop) => hop.info.direction().htlc_minimum_msat,
1316 CandidateRouteHop::PrivateHop(hop) => hop.hint.htlc_minimum_msat.unwrap_or(0),
1317 CandidateRouteHop::Blinded(hop) => hop.hint.0.htlc_minimum_msat,
1318 CandidateRouteHop::OneHopBlinded { .. } => 0,
1323 fn src_node_counter(&self) -> u32 {
1325 CandidateRouteHop::FirstHop { payer_node_counter, .. } => *payer_node_counter,
1326 CandidateRouteHop::PublicHop { info, .. } => info.source_counter(),
1327 CandidateRouteHop::PrivateHop { source_node_counter, .. } => *source_node_counter,
1328 CandidateRouteHop::Blinded { source_node_counter, .. } => *source_node_counter,
1329 CandidateRouteHop::OneHopBlinded { source_node_counter, .. } => *source_node_counter,
1334 fn target_node_counter(&self) -> Option<u32> {
1336 CandidateRouteHop::FirstHop { target_node_counter, .. } => Some(*target_node_counter),
1337 CandidateRouteHop::PublicHop { info, .. } => Some(info.target_counter()),
1338 CandidateRouteHop::PrivateHop { target_node_counter, .. } => Some(*target_node_counter),
1339 CandidateRouteHop::Blinded { .. } => None,
1340 CandidateRouteHop::OneHopBlinded { .. } => None,
1344 /// Returns the fees that must be paid to route an HTLC over this channel.
1346 pub fn fees(&self) -> RoutingFees {
1348 CandidateRouteHop::FirstHop(_) => RoutingFees {
1349 base_msat: 0, proportional_millionths: 0,
1351 CandidateRouteHop::PublicHop(hop) => hop.info.direction().fees,
1352 CandidateRouteHop::PrivateHop(hop) => hop.hint.fees,
1353 CandidateRouteHop::Blinded(hop) => {
1355 base_msat: hop.hint.0.fee_base_msat,
1356 proportional_millionths: hop.hint.0.fee_proportional_millionths
1359 CandidateRouteHop::OneHopBlinded(_) =>
1360 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1364 /// Fetch the effective capacity of this hop.
1366 /// Note that this may be somewhat expensive, so calls to this should be limited and results
1368 fn effective_capacity(&self) -> EffectiveCapacity {
1370 CandidateRouteHop::FirstHop(hop) => EffectiveCapacity::ExactLiquidity {
1371 liquidity_msat: hop.details.next_outbound_htlc_limit_msat,
1373 CandidateRouteHop::PublicHop(hop) => hop.info.effective_capacity(),
1374 CandidateRouteHop::PrivateHop(CandidatePrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. }) =>
1375 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1376 CandidateRouteHop::PrivateHop(CandidatePrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. }) =>
1377 EffectiveCapacity::Infinite,
1378 CandidateRouteHop::Blinded(hop) =>
1379 EffectiveCapacity::HintMaxHTLC { amount_msat: hop.hint.0.htlc_maximum_msat },
1380 CandidateRouteHop::OneHopBlinded(_) => EffectiveCapacity::Infinite,
1384 /// Returns an ID describing the given hop.
1386 /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1388 fn id(&self) -> CandidateHopId {
1390 CandidateRouteHop::Blinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1391 CandidateRouteHop::OneHopBlinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1392 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1395 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1397 CandidateRouteHop::Blinded(CandidateBlindedPath { hint, .. }) | CandidateRouteHop::OneHopBlinded(CandidateOneHopBlindedPath { hint, .. }) => {
1403 /// Returns the source node id of current hop.
1405 /// Source node id refers to the node forwarding the HTLC through this hop.
1407 /// For [`Self::FirstHop`] we return payer's node id.
1409 pub fn source(&self) -> NodeId {
1411 CandidateRouteHop::FirstHop(hop) => *hop.payer_node_id,
1412 CandidateRouteHop::PublicHop(hop) => *hop.info.source(),
1413 CandidateRouteHop::PrivateHop(hop) => hop.hint.src_node_id.into(),
1414 CandidateRouteHop::Blinded(hop) => hop.hint.1.introduction_node_id.into(),
1415 CandidateRouteHop::OneHopBlinded(hop) => hop.hint.1.introduction_node_id.into(),
1418 /// Returns the target node id of this hop, if known.
1420 /// Target node id refers to the node receiving the HTLC after this hop.
1422 /// For [`Self::Blinded`] we return `None` because the ultimate destination after the blinded
1423 /// path is unknown.
1425 /// For [`Self::OneHopBlinded`] we return `None` because the target is the same as the source,
1426 /// and such a return value would be somewhat nonsensical.
1428 pub fn target(&self) -> Option<NodeId> {
1430 CandidateRouteHop::FirstHop(hop) => Some(hop.details.counterparty.node_id.into()),
1431 CandidateRouteHop::PublicHop(hop) => Some(*hop.info.target()),
1432 CandidateRouteHop::PrivateHop(hop) => Some(*hop.target_node_id),
1433 CandidateRouteHop::Blinded(_) => None,
1434 CandidateRouteHop::OneHopBlinded(_) => None,
1439 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1441 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1443 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1444 /// isn't guaranteed to be unique at all.
1446 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1447 /// difficult-to-use API.
1448 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1449 enum CandidateHopId {
1450 /// Contains (scid, src_node_id < target_node_id)
1452 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1457 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1458 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1460 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1461 EffectiveCapacity::Infinite => u64::max_value(),
1462 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1463 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1464 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1465 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1466 // expected to have been generated from up-to-date capacity information.
1467 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1468 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1469 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1473 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1474 -> bool where I1::Item: PartialEq<I2::Item> {
1476 let a = iter_a.next();
1477 let b = iter_b.next();
1478 if a.is_none() && b.is_none() { return true; }
1479 if a.is_none() || b.is_none() { return false; }
1480 if a.unwrap().ne(&b.unwrap()) { return false; }
1484 /// It's useful to keep track of the hops associated with the fees required to use them,
1485 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1486 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1487 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1490 struct PathBuildingHop<'a> {
1491 candidate: CandidateRouteHop<'a>,
1492 target_node_counter: Option<u32>,
1493 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1494 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1495 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1496 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1497 /// avoid processing them again.
1498 was_processed: bool,
1499 /// When processing a node as the next best-score candidate, we want to quickly check if it is
1500 /// a direct counterparty of ours, using our local channel information immediately if we can.
1502 /// In order to do so efficiently, we cache whether a node is a direct counterparty here at the
1503 /// start of a route-finding pass. Unlike all other fields in this struct, this field is never
1504 /// updated after being initialized - it is set at the start of a route-finding pass and only
1505 /// read thereafter.
1506 is_first_hop_target: bool,
1507 /// Used to compare channels when choosing the for routing.
1508 /// Includes paying for the use of a hop and the following hops, as well as
1509 /// an estimated cost of reaching this hop.
1510 /// Might get stale when fees are recomputed. Primarily for internal use.
1511 total_fee_msat: u64,
1512 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1513 /// walk and may be invalid thereafter.
1514 path_htlc_minimum_msat: u64,
1515 /// All penalties incurred from this channel on the way to the destination, as calculated using
1516 /// channel scoring.
1517 path_penalty_msat: u64,
1521 /// All the fees paid *after* this channel on the way to the destination
1522 next_hops_fee_msat: u64,
1523 /// Fee paid for the use of the current channel (see candidate.fees()).
1524 /// The value will be actually deducted from the counterparty balance on the previous link.
1525 hop_use_fee_msat: u64,
1527 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1528 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1529 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1530 // value_contribution_msat, which requires tracking it here. See comments below where it is
1531 // used for more info.
1532 value_contribution_msat: u64,
1535 const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::<Option<PathBuildingHop>>();
1536 const _NODE_MAP_SIZE_EXACTLY_TWO_CACHE_LINES: usize = core::mem::size_of::<Option<PathBuildingHop>>() - 128;
1538 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1539 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1540 let mut debug_struct = f.debug_struct("PathBuildingHop");
1542 .field("source_node_id", &self.candidate.source())
1543 .field("target_node_id", &self.candidate.target())
1544 .field("short_channel_id", &self.candidate.short_channel_id())
1545 .field("total_fee_msat", &self.total_fee_msat)
1546 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1547 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1548 .field("total_fee_msat - (next_hops_fee_msat + hop_use_fee_msat)", &(&self.total_fee_msat.saturating_sub(self.next_hops_fee_msat).saturating_sub(self.hop_use_fee_msat)))
1549 .field("path_penalty_msat", &self.path_penalty_msat)
1550 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1551 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1552 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1553 let debug_struct = debug_struct
1554 .field("value_contribution_msat", &self.value_contribution_msat);
1555 debug_struct.finish()
1559 // Instantiated with a list of hops with correct data in them collected during path finding,
1560 // an instance of this struct should be further modified only via given methods.
1562 struct PaymentPath<'a> {
1563 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1566 impl<'a> PaymentPath<'a> {
1567 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1568 fn get_value_msat(&self) -> u64 {
1569 self.hops.last().unwrap().0.fee_msat
1572 fn get_path_penalty_msat(&self) -> u64 {
1573 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1576 fn get_total_fee_paid_msat(&self) -> u64 {
1577 if self.hops.len() < 1 {
1581 // Can't use next_hops_fee_msat because it gets outdated.
1582 for (i, (hop, _)) in self.hops.iter().enumerate() {
1583 if i != self.hops.len() - 1 {
1584 result += hop.fee_msat;
1590 fn get_cost_msat(&self) -> u64 {
1591 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1594 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1595 // to change fees may result in an inconsistency.
1597 // Sometimes we call this function right after constructing a path which is inconsistent in
1598 // that it the value being transferred has decreased while we were doing path finding, leading
1599 // to the fees being paid not lining up with the actual limits.
1601 // Note that this function is not aware of the available_liquidity limit, and thus does not
1602 // support increasing the value being transferred beyond what was selected during the initial
1605 // Returns the amount that this path contributes to the total payment value, which may be greater
1606 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1607 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1608 let mut extra_contribution_msat = 0;
1609 let mut total_fee_paid_msat = 0 as u64;
1610 for i in (0..self.hops.len()).rev() {
1611 let last_hop = i == self.hops.len() - 1;
1613 // For non-last-hop, this value will represent the fees paid on the current hop. It
1614 // will consist of the fees for the use of the next hop, and extra fees to match
1615 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1616 let mut cur_hop_fees_msat = 0;
1618 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1621 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1622 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1623 cur_hop.path_penalty_msat += extra_contribution_msat;
1624 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1625 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1626 // set it too high just to maliciously take more fees by exploiting this
1627 // match htlc_minimum_msat logic.
1628 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1629 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1630 // Note that there is a risk that *previous hops* (those closer to us, as we go
1631 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1633 // This might make us end up with a broken route, although this should be super-rare
1634 // in practice, both because of how healthy channels look like, and how we pick
1635 // channels in add_entry.
1636 // Also, this can't be exploited more heavily than *announce a free path and fail
1638 cur_hop_transferred_amount_msat += extra_fees_msat;
1640 // We remember and return the extra fees on the final hop to allow accounting for
1641 // them in the path's value contribution.
1643 extra_contribution_msat = extra_fees_msat;
1645 total_fee_paid_msat += extra_fees_msat;
1646 cur_hop_fees_msat += extra_fees_msat;
1651 // Final hop is a special case: it usually has just value_msat (by design), but also
1652 // it still could overpay for the htlc_minimum_msat.
1653 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1655 // Propagate updated fees for the use of the channels to one hop back, where they
1656 // will be actually paid (fee_msat). The last hop is handled above separately.
1657 cur_hop.fee_msat = cur_hop_fees_msat;
1660 // Fee for the use of the current hop which will be deducted on the previous hop.
1661 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1662 // this channel is free for us.
1664 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1665 cur_hop.hop_use_fee_msat = new_fee;
1666 total_fee_paid_msat += new_fee;
1668 // It should not be possible because this function is called only to reduce the
1669 // value. In that case, compute_fee was already called with the same fees for
1670 // larger amount and there was no overflow.
1675 value_msat + extra_contribution_msat
1680 /// Calculate the fees required to route the given amount over a channel with the given fees.
1681 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1682 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1683 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1687 /// Calculate the fees required to route the given amount over a channel with the given fees,
1688 /// saturating to [`u64::max_value`].
1689 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1690 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1691 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1692 .saturating_add(channel_fees.base_msat as u64)
1695 /// The default `features` we assume for a node in a route, when no `features` are known about that
1698 /// Default features are:
1699 /// * variable_length_onion_optional
1700 fn default_node_features() -> NodeFeatures {
1701 let mut features = NodeFeatures::empty();
1702 features.set_variable_length_onion_optional();
1706 struct LoggedPayeePubkey(Option<PublicKey>);
1707 impl fmt::Display for LoggedPayeePubkey {
1708 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1711 "payee node id ".fmt(f)?;
1715 "blinded payee".fmt(f)
1721 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1722 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1723 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1725 CandidateRouteHop::Blinded(CandidateBlindedPath { hint, .. }) | CandidateRouteHop::OneHopBlinded(CandidateOneHopBlindedPath { hint, .. }) => {
1726 "blinded route hint with introduction node id ".fmt(f)?;
1727 hint.1.introduction_node_id.fmt(f)?;
1728 " and blinding point ".fmt(f)?;
1729 hint.1.blinding_point.fmt(f)
1731 CandidateRouteHop::FirstHop(_) => {
1732 "first hop with SCID ".fmt(f)?;
1733 self.0.short_channel_id().unwrap().fmt(f)
1735 CandidateRouteHop::PrivateHop(_) => {
1736 "route hint with SCID ".fmt(f)?;
1737 self.0.short_channel_id().unwrap().fmt(f)
1741 self.0.short_channel_id().unwrap().fmt(f)
1748 fn sort_first_hop_channels(
1749 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1750 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1752 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1753 // most like to use.
1755 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1756 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1759 // Second, because simply always sorting in descending order would always use our largest
1760 // available outbound capacity, needlessly fragmenting our available channel capacities,
1761 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1762 // which have enough, but not too much, capacity for the payment.
1764 // Available outbound balances factor in liquidity already reserved for previously found paths.
1765 channels.sort_unstable_by(|chan_a, chan_b| {
1766 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1767 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1768 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1769 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1770 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1771 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1772 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1773 // Sort in descending order
1774 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1776 // Sort in ascending order
1777 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1782 /// Finds a route from us (payer) to the given target node (payee).
1784 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1785 /// in the given [`RouteParameters::payment_params`].
1786 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1788 /// Private routing paths between a public node and the target may be included in the `payee` field
1789 /// of [`RouteParameters::payment_params`].
1791 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1792 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1793 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1795 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1796 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1797 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1801 /// Panics if first_hops contains channels without `short_channel_id`s;
1802 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1804 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1805 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1806 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1807 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1808 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1809 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1810 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1811 ) -> Result<Route, LightningError>
1812 where L::Target: Logger, GL::Target: Logger {
1813 let graph_lock = network_graph.read_only();
1814 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1815 scorer, score_params, random_seed_bytes)?;
1816 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1820 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1821 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1822 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1823 _random_seed_bytes: &[u8; 32]
1824 ) -> Result<Route, LightningError>
1825 where L::Target: Logger {
1827 let payment_params = &route_params.payment_params;
1828 let final_value_msat = route_params.final_value_msat;
1829 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1830 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1831 // so use a dummy id for this in the blinded case.
1832 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1833 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1834 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1835 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1836 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1838 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1839 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1841 if our_node_id == maybe_dummy_payee_node_id {
1842 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1845 if final_value_msat > MAX_VALUE_MSAT {
1846 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1849 if final_value_msat == 0 {
1850 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1853 match &payment_params.payee {
1854 Payee::Clear { route_hints, node_id, .. } => {
1855 for route in route_hints.iter() {
1856 for hop in &route.0 {
1857 if hop.src_node_id == *node_id {
1858 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1863 Payee::Blinded { route_hints, .. } => {
1864 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1865 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});
1867 for (_, blinded_path) in route_hints.iter() {
1868 if blinded_path.blinded_hops.len() == 0 {
1869 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1870 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1871 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1872 } else if blinded_path.blinded_hops.len() == 1 &&
1873 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1874 && p.introduction_node_id != blinded_path.introduction_node_id)
1876 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1881 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1882 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1883 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});
1886 // The general routing idea is the following:
1887 // 1. Fill first/last hops communicated by the caller.
1888 // 2. Attempt to construct a path from payer to payee for transferring
1889 // any ~sufficient (described later) value.
1890 // If succeed, remember which channels were used and how much liquidity they have available,
1891 // so that future paths don't rely on the same liquidity.
1892 // 3. Proceed to the next step if:
1893 // - we hit the recommended target value;
1894 // - OR if we could not construct a new path. Any next attempt will fail too.
1895 // Otherwise, repeat step 2.
1896 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1897 // (not recommended value).
1898 // 5. If yes, proceed. If not, fail routing.
1899 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1900 // transferred up to the transfer target value.
1901 // 7. Reduce the value of the last path until we are sending only the target value.
1902 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1903 // them so that we're not sending two HTLCs along the same path.
1905 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1906 // distance from the payee
1908 // We are not a faithful Dijkstra's implementation because we can change values which impact
1909 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1910 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1911 // the value we are currently attempting to send over a path, we simply reduce the value being
1912 // sent along the path for any hops after that channel. This may imply that later fees (which
1913 // we've already tabulated) are lower because a smaller value is passing through the channels
1914 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1915 // channels which were selected earlier (and which may still be used for other paths without a
1916 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1919 // One potentially problematic case for this algorithm would be if there are many
1920 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1921 // graph walking), we may never find a path which is not liquidity-limited and has lower
1922 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1923 // Because we only consider paths with at least 5% of the total value being sent, the damage
1924 // from such a case should be limited, however this could be further reduced in the future by
1925 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1926 // limits for the purposes of fee calculation.
1928 // Alternatively, we could store more detailed path information in the heap (targets, below)
1929 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1930 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1931 // and practically (as we would need to store dynamically-allocated path information in heap
1932 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1933 // results of such an algorithm would likely be biased towards lower-value paths.
1935 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1936 // outside of our current search value, running a path search more times to gather candidate
1937 // paths at different values. While this may be acceptable, further path searches may increase
1938 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1939 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1940 // the same time, remaining generic across different payment values.
1942 let network_channels = network_graph.channels();
1943 let network_nodes = network_graph.nodes();
1945 if payment_params.max_path_count == 0 {
1946 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1949 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1950 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1952 let allow_mpp = if payment_params.max_path_count == 1 {
1954 } else if payment_params.payee.supports_basic_mpp() {
1956 } else if let Some(payee) = payee_node_id_opt {
1957 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1958 |info| info.features.supports_basic_mpp()))
1961 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1963 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph with a fee limit of {} msat",
1964 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
1965 if allow_mpp { "with" } else { "without" },
1966 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " },
1967 max_total_routing_fee_msat);
1969 let private_hop_targets_node_counter_offset = network_graph.max_node_counter() + 2;
1970 let mut private_node_id_to_node_counter = HashMap::new();
1972 let mut private_hop_key_cache = HashMap::with_capacity(
1973 payment_params.payee.unblinded_route_hints().iter().map(|path| path.0.len()).sum()
1976 // Because we store references to private hop node_ids in `dist`, below, we need them to exist
1977 // (as `NodeId`, not `PublicKey`) for the lifetime of `dist`. Thus, we calculate all the keys
1978 // we'll need here and simply fetch them when routing.
1979 let payee_node_counter = payee_node_id_opt
1980 .and_then(|payee| network_nodes.get(&payee))
1981 .map(|node| node.node_counter)
1982 .unwrap_or(private_hop_targets_node_counter_offset);
1983 private_node_id_to_node_counter.insert(maybe_dummy_payee_node_id, payee_node_counter);
1984 private_hop_key_cache.insert(maybe_dummy_payee_pk, (NodeId::from_pubkey(&maybe_dummy_payee_pk), payee_node_counter));
1986 for route in payment_params.payee.unblinded_route_hints().iter() {
1987 for hop in route.0.iter() {
1988 let hop_node_id = NodeId::from_pubkey(&hop.src_node_id);
1989 let node_counter = if let Some(node) = network_nodes.get(&hop_node_id) {
1992 let next_node_counter = private_hop_targets_node_counter_offset + private_node_id_to_node_counter.len() as u32;
1993 *private_node_id_to_node_counter.entry(hop_node_id)
1994 .or_insert(next_node_counter)
1996 private_hop_key_cache.insert(hop.src_node_id, (hop_node_id, node_counter));
2001 // Prepare the data we'll use for payee-to-payer search by
2002 // inserting first hops suggested by the caller as targets.
2003 // Our search will then attempt to reach them while traversing from the payee node.
2004 let mut first_hop_targets: HashMap<_, (Vec<&ChannelDetails>, u32)> =
2005 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
2006 if let Some(hops) = first_hops {
2008 if chan.get_outbound_payment_scid().is_none() {
2009 panic!("first_hops should be filled in with usable channels, not pending ones");
2011 if chan.counterparty.node_id == *our_node_pubkey {
2012 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
2014 let counterparty_node_id = NodeId::from_pubkey(&chan.counterparty.node_id);
2016 .entry(counterparty_node_id)
2017 .or_insert_with(|| {
2018 let node_counter = if let Some(node) = network_nodes.get(&counterparty_node_id) {
2021 let next_node_counter = private_hop_targets_node_counter_offset + private_node_id_to_node_counter.len() as u32;
2022 *private_node_id_to_node_counter.entry(counterparty_node_id)
2023 .or_insert(next_node_counter)
2025 (Vec::new(), node_counter)
2029 if first_hop_targets.is_empty() {
2030 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
2034 // The main heap containing all candidate next-hops sorted by their score (max(fee,
2035 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
2036 // adding duplicate entries when we find a better path to a given node.
2037 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
2039 // Map from node_id to information about the best current path to that node, including feerate
2041 let dist_len = private_hop_targets_node_counter_offset + private_hop_key_cache.len() as u32 + 1;
2042 let mut dist: Vec<Option<PathBuildingHop>> = vec![None; dist_len as usize];
2043 let payer_node_counter = network_nodes
2045 .map(|node| node.node_counter)
2047 private_node_id_to_node_counter.get(&our_node_id).map(|counter| *counter)
2049 .unwrap_or(network_graph.max_node_counter() + 1);
2051 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
2052 // indicating that we may wish to try again with a higher value, potentially paying to meet an
2053 // htlc_minimum with extra fees while still finding a cheaper path.
2054 let mut hit_minimum_limit;
2056 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
2057 // We start with a path_value of the exact amount we want, and if that generates a route we may
2058 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
2059 // amount we want in total across paths, selecting the best subset at the end.
2060 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
2061 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
2062 let mut path_value_msat = final_value_msat;
2064 // Routing Fragmentation Mitigation heuristic:
2066 // Routing fragmentation across many payment paths increases the overall routing
2067 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
2068 // Taking too many smaller paths also increases the chance of payment failure.
2069 // Thus to avoid this effect, we require from our collected links to provide
2070 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
2071 // This requirement is currently set to be 1/max_path_count of the payment
2072 // value to ensure we only ever return routes that do not violate this limit.
2073 let minimal_value_contribution_msat: u64 = if allow_mpp {
2074 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
2079 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
2080 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
2081 // drop the requirement by setting this to 0.
2082 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
2084 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
2085 // determine if the channel can be used by additional MPP paths or to inform path finding
2086 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
2087 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
2089 let mut used_liquidities: HashMap<CandidateHopId, u64> =
2090 HashMap::with_capacity(network_nodes.len());
2092 // Keeping track of how much value we already collected across other paths. Helps to decide
2093 // when we want to stop looking for new paths.
2094 let mut already_collected_value_msat = 0;
2096 for (_, (channels, _)) in first_hop_targets.iter_mut() {
2097 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
2101 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
2102 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
2104 // Remember how many candidates we ignored to allow for some logging afterwards.
2105 let mut num_ignored_value_contribution: u32 = 0;
2106 let mut num_ignored_path_length_limit: u32 = 0;
2107 let mut num_ignored_cltv_delta_limit: u32 = 0;
2108 let mut num_ignored_previously_failed: u32 = 0;
2109 let mut num_ignored_total_fee_limit: u32 = 0;
2110 let mut num_ignored_avoid_overpayment: u32 = 0;
2111 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
2113 macro_rules! add_entry {
2114 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
2115 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
2116 // since that value has to be transferred over this channel.
2117 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
2118 ( $candidate: expr, $next_hops_fee_msat: expr,
2119 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
2120 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
2121 // We "return" whether we updated the path at the end, and how much we can route via
2122 // this channel, via this:
2123 let mut hop_contribution_amt_msat = None;
2124 // Channels to self should not be used. This is more of belt-and-suspenders, because in
2125 // practice these cases should be caught earlier:
2126 // - for regular channels at channel announcement (TODO)
2127 // - for first and last hops early in get_route
2128 let src_node_id = $candidate.source();
2129 if Some(src_node_id) != $candidate.target() {
2130 let scid_opt = $candidate.short_channel_id();
2131 let effective_capacity = $candidate.effective_capacity();
2132 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
2134 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
2135 // It may be misleading because we might later choose to reduce the value transferred
2136 // over these channels, and the channel which was insufficient might become sufficient.
2137 // Worst case: we drop a good channel here because it can't cover the high following
2138 // fees caused by one expensive channel, but then this channel could have been used
2139 // if the amount being transferred over this path is lower.
2140 // We do this for now, but this is a subject for removal.
2141 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
2142 let used_liquidity_msat = used_liquidities
2143 .get(&$candidate.id())
2144 .map_or(0, |used_liquidity_msat| {
2145 available_value_contribution_msat = available_value_contribution_msat
2146 .saturating_sub(*used_liquidity_msat);
2147 *used_liquidity_msat
2150 // Verify the liquidity offered by this channel complies to the minimal contribution.
2151 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
2152 // Do not consider candidate hops that would exceed the maximum path length.
2153 let path_length_to_node = $next_hops_path_length + 1;
2154 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
2156 // Do not consider candidates that exceed the maximum total cltv expiry limit.
2157 // In order to already account for some of the privacy enhancing random CLTV
2158 // expiry delta offset we add on top later, we subtract a rough estimate
2159 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
2160 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
2161 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
2162 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
2163 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
2164 .saturating_add($candidate.cltv_expiry_delta());
2165 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
2167 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
2168 // Includes paying fees for the use of the following channels.
2169 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
2170 Some(result) => result,
2171 // Can't overflow due to how the values were computed right above.
2172 None => unreachable!(),
2174 let htlc_minimum_msat = $candidate.htlc_minimum_msat();
2175 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2176 let over_path_minimum_msat = amount_to_transfer_over_msat >= htlc_minimum_msat &&
2177 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
2179 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2180 let may_overpay_to_meet_path_minimum_msat =
2181 ((amount_to_transfer_over_msat < htlc_minimum_msat &&
2182 recommended_value_msat >= htlc_minimum_msat) ||
2183 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
2184 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
2186 let payment_failed_on_this_channel = scid_opt.map_or(false,
2187 |scid| payment_params.previously_failed_channels.contains(&scid));
2189 let (should_log_candidate, first_hop_details) = match $candidate {
2190 CandidateRouteHop::FirstHop(hop) => (true, Some(hop.details)),
2191 CandidateRouteHop::PrivateHop(_) => (true, None),
2192 CandidateRouteHop::Blinded(_) => (true, None),
2193 CandidateRouteHop::OneHopBlinded(_) => (true, None),
2197 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
2198 // bother considering this channel. If retrying with recommended_value_msat may
2199 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
2200 // around again with a higher amount.
2201 if !contributes_sufficient_value {
2202 if should_log_candidate {
2203 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
2205 if let Some(details) = first_hop_details {
2207 "First hop candidate next_outbound_htlc_limit_msat: {}",
2208 details.next_outbound_htlc_limit_msat,
2212 num_ignored_value_contribution += 1;
2213 } else if exceeds_max_path_length {
2214 if should_log_candidate {
2215 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
2217 num_ignored_path_length_limit += 1;
2218 } else if exceeds_cltv_delta_limit {
2219 if should_log_candidate {
2220 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
2222 if let Some(_) = first_hop_details {
2224 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
2225 hop_total_cltv_delta,
2226 max_total_cltv_expiry_delta,
2230 num_ignored_cltv_delta_limit += 1;
2231 } else if payment_failed_on_this_channel {
2232 if should_log_candidate {
2233 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
2235 num_ignored_previously_failed += 1;
2236 } else if may_overpay_to_meet_path_minimum_msat {
2237 if should_log_candidate {
2239 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit.",
2240 LoggedCandidateHop(&$candidate));
2242 if let Some(details) = first_hop_details {
2244 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2245 details.next_outbound_htlc_minimum_msat,
2249 num_ignored_avoid_overpayment += 1;
2250 hit_minimum_limit = true;
2251 } else if over_path_minimum_msat {
2252 // Note that low contribution here (limited by available_liquidity_msat)
2253 // might violate htlc_minimum_msat on the hops which are next along the
2254 // payment path (upstream to the payee). To avoid that, we recompute
2255 // path fees knowing the final path contribution after constructing it.
2256 let curr_min = cmp::max(
2257 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
2259 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
2260 .saturating_add(curr_min);
2262 let dist_entry = &mut dist[$candidate.src_node_counter() as usize];
2263 let old_entry = if let Some(hop) = dist_entry {
2266 // If there was previously no known way to access the source node
2267 // (recall it goes payee-to-payer) of short_channel_id, first add a
2268 // semi-dummy record just to compute the fees to reach the source node.
2269 // This will affect our decision on selecting short_channel_id
2270 // as a way to reach the $candidate.target() node.
2271 *dist_entry = Some(PathBuildingHop {
2272 candidate: $candidate.clone(),
2273 target_node_counter: None,
2275 next_hops_fee_msat: u64::max_value(),
2276 hop_use_fee_msat: u64::max_value(),
2277 total_fee_msat: u64::max_value(),
2278 path_htlc_minimum_msat,
2279 path_penalty_msat: u64::max_value(),
2280 was_processed: false,
2281 is_first_hop_target: false,
2282 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2283 value_contribution_msat,
2285 dist_entry.as_mut().unwrap()
2288 #[allow(unused_mut)] // We only use the mut in cfg(test)
2289 let mut should_process = !old_entry.was_processed;
2290 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2292 // In test/fuzzing builds, we do extra checks to make sure the skipping
2293 // of already-seen nodes only happens in cases we expect (see below).
2294 if !should_process { should_process = true; }
2298 let mut hop_use_fee_msat = 0;
2299 let mut total_fee_msat: u64 = $next_hops_fee_msat;
2301 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2302 // will have the same effective-fee
2303 if src_node_id != our_node_id {
2304 // Note that `u64::max_value` means we'll always fail the
2305 // `old_entry.total_fee_msat > total_fee_msat` check below
2306 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
2307 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2310 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2311 if total_fee_msat > max_total_routing_fee_msat {
2312 if should_log_candidate {
2313 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2315 if let Some(_) = first_hop_details {
2317 "First hop candidate routing fee: {}. Limit: {}",
2319 max_total_routing_fee_msat,
2323 num_ignored_total_fee_limit += 1;
2325 let channel_usage = ChannelUsage {
2326 amount_msat: amount_to_transfer_over_msat,
2327 inflight_htlc_msat: used_liquidity_msat,
2330 let channel_penalty_msat =
2331 scorer.channel_penalty_msat($candidate,
2334 let path_penalty_msat = $next_hops_path_penalty_msat
2335 .saturating_add(channel_penalty_msat);
2337 // Update the way of reaching $candidate.source()
2338 // with the given short_channel_id (from $candidate.target()),
2339 // if this way is cheaper than the already known
2340 // (considering the cost to "reach" this channel from the route destination,
2341 // the cost of using this channel,
2342 // and the cost of routing to the source node of this channel).
2343 // Also, consider that htlc_minimum_msat_difference, because we might end up
2344 // paying it. Consider the following exploit:
2345 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2346 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2347 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2348 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2350 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2351 // but it may require additional tracking - we don't want to double-count
2352 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2353 // can't use something that may decrease on future hops.
2354 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2355 .saturating_add(old_entry.path_penalty_msat);
2356 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2357 .saturating_add(path_penalty_msat);
2359 if !old_entry.was_processed && new_cost < old_cost {
2360 let new_graph_node = RouteGraphNode {
2361 node_id: src_node_id,
2362 score: cmp::max(total_fee_msat, path_htlc_minimum_msat).saturating_add(path_penalty_msat),
2363 total_cltv_delta: hop_total_cltv_delta,
2364 value_contribution_msat,
2365 path_length_to_node,
2367 targets.push(new_graph_node);
2368 old_entry.target_node_counter = $candidate.target_node_counter();
2369 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2370 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2371 old_entry.total_fee_msat = total_fee_msat;
2372 old_entry.candidate = $candidate.clone();
2373 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2374 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2375 old_entry.path_penalty_msat = path_penalty_msat;
2376 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2378 old_entry.value_contribution_msat = value_contribution_msat;
2380 hop_contribution_amt_msat = Some(value_contribution_msat);
2381 } else if old_entry.was_processed && new_cost < old_cost {
2382 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2384 // If we're skipping processing a node which was previously
2385 // processed even though we found another path to it with a
2386 // cheaper fee, check that it was because the second path we
2387 // found (which we are processing now) has a lower value
2388 // contribution due to an HTLC minimum limit.
2390 // e.g. take a graph with two paths from node 1 to node 2, one
2391 // through channel A, and one through channel B. Channel A and
2392 // B are both in the to-process heap, with their scores set by
2393 // a higher htlc_minimum than fee.
2394 // Channel A is processed first, and the channels onwards from
2395 // node 1 are added to the to-process heap. Thereafter, we pop
2396 // Channel B off of the heap, note that it has a much more
2397 // restrictive htlc_maximum_msat, and recalculate the fees for
2398 // all of node 1's channels using the new, reduced, amount.
2400 // This would be bogus - we'd be selecting a higher-fee path
2401 // with a lower htlc_maximum_msat instead of the one we'd
2402 // already decided to use.
2403 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2405 value_contribution_msat + path_penalty_msat <
2406 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2413 if should_log_candidate {
2415 "Ignoring {} due to its htlc_minimum_msat limit.",
2416 LoggedCandidateHop(&$candidate));
2418 if let Some(details) = first_hop_details {
2420 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2421 details.next_outbound_htlc_minimum_msat,
2425 num_ignored_htlc_minimum_msat_limit += 1;
2429 hop_contribution_amt_msat
2433 let default_node_features = default_node_features();
2435 // Find ways (channels with destination) to reach a given node and store them
2436 // in the corresponding data structures (routing graph etc).
2437 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2438 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2439 // This data can later be helpful to optimize routing (pay lower fees).
2440 macro_rules! add_entries_to_cheapest_to_target_node {
2441 ( $node: expr, $node_id: expr, $next_hops_value_contribution: expr,
2442 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2443 let fee_to_target_msat;
2444 let next_hops_path_htlc_minimum_msat;
2445 let next_hops_path_penalty_msat;
2446 let is_first_hop_target;
2447 let skip_node = if let Some(elem) = &mut dist[$node.node_counter as usize] {
2448 let was_processed = elem.was_processed;
2449 elem.was_processed = true;
2450 fee_to_target_msat = elem.total_fee_msat;
2451 next_hops_path_htlc_minimum_msat = elem.path_htlc_minimum_msat;
2452 next_hops_path_penalty_msat = elem.path_penalty_msat;
2453 is_first_hop_target = elem.is_first_hop_target;
2456 // Entries are added to dist in add_entry!() when there is a channel from a node.
2457 // Because there are no channels from payee, it will not have a dist entry at this point.
2458 // If we're processing any other node, it is always be the result of a channel from it.
2459 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2461 fee_to_target_msat = 0;
2462 next_hops_path_htlc_minimum_msat = 0;
2463 next_hops_path_penalty_msat = 0;
2464 is_first_hop_target = false;
2469 if is_first_hop_target {
2470 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get(&$node_id) {
2471 for details in first_channels {
2472 debug_assert_eq!(*peer_node_counter, $node.node_counter);
2473 let candidate = CandidateRouteHop::FirstHop(CandidateFirstHop {
2474 details, payer_node_id: &our_node_id, payer_node_counter,
2475 target_node_counter: $node.node_counter,
2477 add_entry!(&candidate, fee_to_target_msat,
2478 $next_hops_value_contribution,
2479 next_hops_path_htlc_minimum_msat, next_hops_path_penalty_msat,
2480 $next_hops_cltv_delta, $next_hops_path_length);
2485 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2488 &default_node_features
2491 if !features.requires_unknown_bits() {
2492 for chan_id in $node.channels.iter() {
2493 let chan = network_channels.get(chan_id).unwrap();
2494 if !chan.features.requires_unknown_bits() {
2495 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2496 if first_hops.is_none() || *source != our_node_id {
2497 if directed_channel.direction().enabled {
2498 let candidate = CandidateRouteHop::PublicHop(CandidatePublicHop {
2499 info: directed_channel,
2500 short_channel_id: *chan_id,
2502 add_entry!(&candidate,
2504 $next_hops_value_contribution,
2505 next_hops_path_htlc_minimum_msat,
2506 next_hops_path_penalty_msat,
2507 $next_hops_cltv_delta, $next_hops_path_length);
2518 let mut payment_paths = Vec::<PaymentPath>::new();
2520 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2521 'paths_collection: loop {
2522 // For every new path, start from scratch, except for used_liquidities, which
2523 // helps to avoid reusing previously selected paths in future iterations.
2525 for e in dist.iter_mut() {
2528 for (node_id, (chans, peer_node_counter)) in first_hop_targets.iter() {
2529 // In order to avoid looking up whether each node is a first-hop target, we store a
2530 // dummy entry in dist for each first-hop target, allowing us to do this lookup for
2531 // free since we're already looking at the `was_processed` flag.
2533 // Note that all the fields (except `is_first_hop_target`) will be overwritten whenever
2534 // we find a path to the target, so are left as dummies here.
2535 dist[*peer_node_counter as usize] = Some(PathBuildingHop {
2536 candidate: CandidateRouteHop::FirstHop {
2538 payer_node_id: &our_node_id,
2539 target_node_counter: u32::max_value(),
2540 payer_node_counter: u32::max_value(),
2542 target_node_counter: None,
2544 next_hops_fee_msat: u64::max_value(),
2545 hop_use_fee_msat: u64::max_value(),
2546 total_fee_msat: u64::max_value(),
2547 path_htlc_minimum_msat: u64::max_value(),
2548 path_penalty_msat: u64::max_value(),
2549 was_processed: false,
2550 is_first_hop_target: true,
2551 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2552 value_contribution_msat: 0,
2555 hit_minimum_limit = false;
2557 // If first hop is a private channel and the only way to reach the payee, this is the only
2558 // place where it could be added.
2559 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|(first_channels, peer_node_counter)| {
2560 debug_assert_eq!(*peer_node_counter, payee_node_counter);
2561 for details in first_channels {
2562 let candidate = CandidateRouteHop::FirstHop(CandidateFirstHop {
2563 details, payer_node_id: &our_node_id, payer_node_counter,
2564 target_node_counter: payee_node_counter,
2566 let added = add_entry!(&candidate, 0, path_value_msat,
2567 0, 0u64, 0, 0).is_some();
2568 log_trace!(logger, "{} direct route to payee via {}",
2569 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2573 // Add the payee as a target, so that the payee-to-payer
2574 // search algorithm knows what to start with.
2575 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2576 // The payee is not in our network graph, so nothing to add here.
2577 // There is still a chance of reaching them via last_hops though,
2578 // so don't yet fail the payment here.
2579 // If not, targets.pop() will not even let us enter the loop in step 2.
2582 add_entries_to_cheapest_to_target_node!(node, payee, path_value_msat, 0, 0);
2587 // If a caller provided us with last hops, add them to routing targets. Since this happens
2588 // earlier than general path finding, they will be somewhat prioritized, although currently
2589 // it matters only if the fees are exactly the same.
2590 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2591 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2592 let intro_node_counter_opt =
2593 // Only add the hops in this route to our candidate set if either
2594 // we have a direct channel to the first hop or the first hop is
2595 // in the regular network graph.
2596 network_nodes.get(&intro_node_id).map(|node| node.node_counter)
2598 first_hop_targets.get(&intro_node_id).map(|(_, node_counter)| *node_counter)
2600 if intro_node_counter_opt.is_none() || our_node_id == intro_node_id { continue }
2601 let candidate = if hint.1.blinded_hops.len() == 1 {
2602 CandidateRouteHop::OneHopBlinded(CandidateOneHopBlindedPath {
2605 source_node_counter: intro_node_counter_opt.unwrap(),
2608 CandidateRouteHop::Blinded(CandidateBlindedPath {
2611 source_node_counter: intro_node_counter_opt.unwrap(),
2614 let mut path_contribution_msat = path_value_msat;
2615 if let Some(hop_used_msat) = add_entry!(&candidate,
2616 0, path_contribution_msat, 0, 0_u64, 0, 0)
2618 path_contribution_msat = hop_used_msat;
2620 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2621 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2623 for details in first_channels {
2624 let first_hop_candidate = CandidateRouteHop::FirstHop(CandidateFirstHop {
2625 details, payer_node_id: &our_node_id, payer_node_counter,
2626 target_node_counter: *peer_node_counter,
2628 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2632 let path_min = candidate.htlc_minimum_msat().saturating_add(
2633 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2634 add_entry!(&first_hop_candidate, blinded_path_fee,
2635 path_contribution_msat, path_min, 0_u64, candidate.cltv_expiry_delta(),
2636 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2640 for route in payment_params.payee.unblinded_route_hints().iter()
2641 .filter(|route| !route.0.is_empty())
2643 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2644 let first_hop_src_is_reachable =
2645 // Only add the hops in this route to our candidate set if either we are part of
2646 // the first hop, we have a direct channel to the first hop, or the first hop is in
2647 // the regular network graph.
2648 our_node_id == first_hop_src_id ||
2649 first_hop_targets.get(&first_hop_src_id).is_some() ||
2650 network_nodes.get(&first_hop_src_id).is_some();
2651 if first_hop_src_is_reachable {
2652 // We start building the path from reverse, i.e., from payee
2653 // to the first RouteHintHop in the path.
2654 let hop_iter = route.0.iter().rev();
2655 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2656 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2657 let mut hop_used = true;
2658 let mut aggregate_next_hops_fee_msat: u64 = 0;
2659 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2660 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2661 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2662 let mut aggregate_next_hops_path_length: u8 = 0;
2663 let mut aggregate_path_contribution_msat = path_value_msat;
2665 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2666 let (target, private_target_node_counter) = private_hop_key_cache.get(&prev_hop_id).unwrap();
2667 let (_src_id, private_source_node_counter) = private_hop_key_cache.get(&hop.src_node_id).unwrap();
2669 if let Some((first_channels, _)) = first_hop_targets.get(&target) {
2670 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2671 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2672 hop.short_channel_id);
2677 let candidate = network_channels
2678 .get(&hop.short_channel_id)
2679 .and_then(|channel| channel.as_directed_to(&target))
2680 .map(|(info, _)| CandidateRouteHop::PublicHop(CandidatePublicHop {
2682 short_channel_id: hop.short_channel_id,
2684 .unwrap_or_else(|| CandidateRouteHop::PrivateHop(CandidatePrivateHop {
2685 hint: hop, target_node_id: target,
2686 source_node_counter: *private_source_node_counter,
2687 target_node_counter: *private_target_node_counter,
2690 if let Some(hop_used_msat) = add_entry!(&candidate,
2691 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2692 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2693 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2695 aggregate_path_contribution_msat = hop_used_msat;
2697 // If this hop was not used then there is no use checking the preceding
2698 // hops in the RouteHint. We can break by just searching for a direct
2699 // channel between last checked hop and first_hop_targets.
2703 let used_liquidity_msat = used_liquidities
2704 .get(&candidate.id()).copied()
2706 let channel_usage = ChannelUsage {
2707 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2708 inflight_htlc_msat: used_liquidity_msat,
2709 effective_capacity: candidate.effective_capacity(),
2711 let channel_penalty_msat = scorer.channel_penalty_msat(
2712 &candidate, channel_usage, score_params
2714 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2715 .saturating_add(channel_penalty_msat);
2717 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2718 .saturating_add(hop.cltv_expiry_delta as u32);
2720 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2723 // Searching for a direct channel between last checked hop and first_hop_targets
2724 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get_mut(&target) {
2725 sort_first_hop_channels(first_channels, &used_liquidities,
2726 recommended_value_msat, our_node_pubkey);
2727 for details in first_channels {
2728 let first_hop_candidate = CandidateRouteHop::FirstHop(CandidateFirstHop {
2729 details, payer_node_id: &our_node_id, payer_node_counter,
2730 target_node_counter: *peer_node_counter,
2732 add_entry!(&first_hop_candidate,
2733 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2734 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2735 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2743 // In the next values of the iterator, the aggregate fees already reflects
2744 // the sum of value sent from payer (final_value_msat) and routing fees
2745 // for the last node in the RouteHint. We need to just add the fees to
2746 // route through the current node so that the preceding node (next iteration)
2748 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2749 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2750 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2752 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2753 // this route hint's source node to forward said min over this channel.
2754 aggregate_next_hops_path_htlc_minimum_msat = {
2755 let curr_htlc_min = cmp::max(
2756 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2758 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2759 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2762 if idx == route.0.len() - 1 {
2763 // The last hop in this iterator is the first hop in
2764 // overall RouteHint.
2765 // If this hop connects to a node with which we have a direct channel,
2766 // ignore the network graph and, if the last hop was added, add our
2767 // direct channel to the candidate set.
2769 // Note that we *must* check if the last hop was added as `add_entry`
2770 // always assumes that the third argument is a node to which we have a
2772 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2773 sort_first_hop_channels(first_channels, &used_liquidities,
2774 recommended_value_msat, our_node_pubkey);
2775 for details in first_channels {
2776 let first_hop_candidate = CandidateRouteHop::FirstHop(CandidateFirstHop {
2777 details, payer_node_id: &our_node_id, payer_node_counter,
2778 target_node_counter: *peer_node_counter,
2780 add_entry!(&first_hop_candidate,
2781 aggregate_next_hops_fee_msat,
2782 aggregate_path_contribution_msat,
2783 aggregate_next_hops_path_htlc_minimum_msat,
2784 aggregate_next_hops_path_penalty_msat,
2785 aggregate_next_hops_cltv_delta,
2786 aggregate_next_hops_path_length);
2794 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2796 // At this point, targets are filled with the data from first and
2797 // last hops communicated by the caller, and the payment receiver.
2798 let mut found_new_path = false;
2801 // If this loop terminates due the exhaustion of targets, two situations are possible:
2802 // - not enough outgoing liquidity:
2803 // 0 < already_collected_value_msat < final_value_msat
2804 // - enough outgoing liquidity:
2805 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2806 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2807 // paths_collection will be stopped because found_new_path==false.
2808 // This is not necessarily a routing failure.
2809 'path_construction: while let Some(RouteGraphNode { node_id, total_cltv_delta, mut value_contribution_msat, path_length_to_node, .. }) = targets.pop() {
2811 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2812 // traversing the graph and arrange the path out of what we found.
2813 if node_id == our_node_id {
2814 let mut new_entry = dist[payer_node_counter as usize].take().unwrap();
2815 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2818 let mut features_set = false;
2819 let candidate = &ordered_hops.last().unwrap().0.candidate;
2820 let target = candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2821 let target_node_counter = candidate.target_node_counter();
2822 if let Some((first_channels, _)) = first_hop_targets.get(&target) {
2823 for details in first_channels {
2824 if let CandidateRouteHop::FirstHop(CandidateFirstHop { details: last_hop_details, .. })
2825 = ordered_hops.last().unwrap().0.candidate
2827 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2828 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2829 features_set = true;
2836 if let Some(node) = network_nodes.get(&target) {
2837 if let Some(node_info) = node.announcement_info.as_ref() {
2838 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2840 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2843 // We can fill in features for everything except hops which were
2844 // provided via the invoice we're paying. We could guess based on the
2845 // recipient's features but for now we simply avoid guessing at all.
2849 // Means we succesfully traversed from the payer to the payee, now
2850 // save this path for the payment route. Also, update the liquidity
2851 // remaining on the used hops, so that we take them into account
2852 // while looking for more paths.
2853 if target_node_counter.is_none() {
2856 if target_node_counter == Some(payee_node_counter) { break 'path_walk; }
2858 new_entry = match dist[target_node_counter.unwrap() as usize].take() {
2859 Some(payment_hop) => payment_hop,
2860 // We can't arrive at None because, if we ever add an entry to targets,
2861 // we also fill in the entry in dist (see add_entry!).
2862 None => unreachable!(),
2864 // We "propagate" the fees one hop backward (topologically) here,
2865 // so that fees paid for a HTLC forwarding on the current channel are
2866 // associated with the previous channel (where they will be subtracted).
2867 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2868 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2870 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2871 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2873 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2874 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2876 let mut payment_path = PaymentPath {hops: ordered_hops};
2878 // We could have possibly constructed a slightly inconsistent path: since we reduce
2879 // value being transferred along the way, we could have violated htlc_minimum_msat
2880 // on some channels we already passed (assuming dest->source direction). Here, we
2881 // recompute the fees again, so that if that's the case, we match the currently
2882 // underpaid htlc_minimum_msat with fees.
2883 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2884 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2885 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2887 // Since a path allows to transfer as much value as
2888 // the smallest channel it has ("bottleneck"), we should recompute
2889 // the fees so sender HTLC don't overpay fees when traversing
2890 // larger channels than the bottleneck. This may happen because
2891 // when we were selecting those channels we were not aware how much value
2892 // this path will transfer, and the relative fee for them
2893 // might have been computed considering a larger value.
2894 // Remember that we used these channels so that we don't rely
2895 // on the same liquidity in future paths.
2896 let mut prevented_redundant_path_selection = false;
2897 for (hop, _) in payment_path.hops.iter() {
2898 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2899 let used_liquidity_msat = used_liquidities
2900 .entry(hop.candidate.id())
2901 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2902 .or_insert(spent_on_hop_msat);
2903 let hop_capacity = hop.candidate.effective_capacity();
2904 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2905 if *used_liquidity_msat == hop_max_msat {
2906 // If this path used all of this channel's available liquidity, we know
2907 // this path will not be selected again in the next loop iteration.
2908 prevented_redundant_path_selection = true;
2910 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2912 if !prevented_redundant_path_selection {
2913 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2914 // we'll probably end up picking the same path again on the next iteration.
2915 // Decrease the available liquidity of a hop in the middle of the path.
2916 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2917 let exhausted = u64::max_value();
2919 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2920 LoggedCandidateHop(victim_candidate));
2921 if let Some(scid) = victim_candidate.short_channel_id() {
2922 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2923 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2927 // Track the total amount all our collected paths allow to send so that we know
2928 // when to stop looking for more paths
2929 already_collected_value_msat += value_contribution_msat;
2931 payment_paths.push(payment_path);
2932 found_new_path = true;
2933 break 'path_construction;
2936 // If we found a path back to the payee, we shouldn't try to process it again. This is
2937 // the equivalent of the `elem.was_processed` check in
2938 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2939 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2941 // Otherwise, since the current target node is not us,
2942 // keep "unrolling" the payment graph from payee to payer by
2943 // finding a way to reach the current target from the payer side.
2944 match network_nodes.get(&node_id) {
2947 add_entries_to_cheapest_to_target_node!(node, node_id,
2948 value_contribution_msat,
2949 total_cltv_delta, path_length_to_node);
2955 if !found_new_path && channel_saturation_pow_half != 0 {
2956 channel_saturation_pow_half = 0;
2957 continue 'paths_collection;
2959 // If we don't support MPP, no use trying to gather more value ever.
2960 break 'paths_collection;
2964 // Stop either when the recommended value is reached or if no new path was found in this
2966 // In the latter case, making another path finding attempt won't help,
2967 // because we deterministically terminated the search due to low liquidity.
2968 if !found_new_path && channel_saturation_pow_half != 0 {
2969 channel_saturation_pow_half = 0;
2970 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2971 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
2972 path_value_msat = recommended_value_msat;
2973 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2974 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2975 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2976 break 'paths_collection;
2977 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2978 // Further, if this was our first walk of the graph, and we weren't limited by an
2979 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2980 // limited by an htlc_minimum_msat value, find another path with a higher value,
2981 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2982 // still keeping a lower total fee than this path.
2983 if !hit_minimum_limit {
2984 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2985 break 'paths_collection;
2987 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.");
2988 path_value_msat = recommended_value_msat;
2992 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2993 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
2994 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
2995 num_ignored_total_fee_limit;
2996 if num_ignored_total > 0 {
2998 "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.",
2999 num_ignored_value_contribution, num_ignored_path_length_limit,
3000 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
3001 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
3002 num_ignored_total_fee_limit, num_ignored_total);
3006 if payment_paths.len() == 0 {
3007 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
3010 if already_collected_value_msat < final_value_msat {
3011 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
3015 let mut selected_route = payment_paths;
3017 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
3018 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
3020 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
3021 // the value they contribute towards the payment amount.
3022 // We sort in descending order as we will remove from the front in `retain`, next.
3023 selected_route.sort_unstable_by(|a, b|
3024 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
3025 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
3028 // We should make sure that at least 1 path left.
3029 let mut paths_left = selected_route.len();
3030 selected_route.retain(|path| {
3031 if paths_left == 1 {
3034 let path_value_msat = path.get_value_msat();
3035 if path_value_msat <= overpaid_value_msat {
3036 overpaid_value_msat -= path_value_msat;
3042 debug_assert!(selected_route.len() > 0);
3044 if overpaid_value_msat != 0 {
3046 // Now, subtract the remaining overpaid value from the most-expensive path.
3047 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
3048 // so that the sender pays less fees overall. And also htlc_minimum_msat.
3049 selected_route.sort_unstable_by(|a, b| {
3050 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3051 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3052 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
3054 let expensive_payment_path = selected_route.first_mut().unwrap();
3056 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
3057 // can't go negative.
3058 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
3059 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
3063 // Sort by the path itself and combine redundant paths.
3064 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
3065 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
3067 selected_route.sort_unstable_by_key(|path| {
3068 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
3069 debug_assert!(path.hops.len() <= key.len());
3070 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
3075 for idx in 0..(selected_route.len() - 1) {
3076 if idx + 1 >= selected_route.len() { break; }
3077 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
3078 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
3079 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
3080 selected_route[idx].update_value_and_recompute_fees(new_value);
3081 selected_route.remove(idx + 1);
3085 let mut paths = Vec::new();
3086 for payment_path in selected_route {
3087 let mut hops = Vec::with_capacity(payment_path.hops.len());
3088 for (hop, node_features) in payment_path.hops.iter()
3089 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
3091 let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
3092 let maybe_announced_channel = if let CandidateRouteHop::PublicHop(_) = hop.candidate {
3093 // If we sourced the hop from the graph we're sure the target node is announced.
3095 } else if let CandidateRouteHop::FirstHop(first_hop) = &hop.candidate {
3096 // If this is a first hop we also know if it's announced.
3097 first_hop.details.is_public
3099 // If we sourced it any other way, we double-check the network graph to see if
3100 // there are announced channels between the endpoints. If so, the hop might be
3101 // referring to any of the announced channels, as its `short_channel_id` might be
3102 // an alias, in which case we don't take any chances here.
3103 network_graph.node(&target).map_or(false, |hop_node|
3104 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
3105 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
3109 hops.push(RouteHop {
3110 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
3111 node_features: node_features.clone(),
3112 short_channel_id: hop.candidate.short_channel_id().unwrap(),
3113 channel_features: hop.candidate.features(),
3114 fee_msat: hop.fee_msat,
3115 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
3116 maybe_announced_channel,
3119 let mut final_cltv_delta = final_cltv_expiry_delta;
3120 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
3121 if let Some(blinded_path) = h.candidate.blinded_path() {
3122 final_cltv_delta = h.candidate.cltv_expiry_delta();
3124 hops: blinded_path.blinded_hops.clone(),
3125 blinding_point: blinded_path.blinding_point,
3126 excess_final_cltv_expiry_delta: 0,
3127 final_value_msat: h.fee_msat,
3131 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
3132 // applicable for the previous hop.
3133 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
3134 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
3137 paths.push(Path { hops, blinded_tail });
3139 // Make sure we would never create a route with more paths than we allow.
3140 debug_assert!(paths.len() <= payment_params.max_path_count.into());
3142 if let Some(node_features) = payment_params.payee.node_features() {
3143 for path in paths.iter_mut() {
3144 path.hops.last_mut().unwrap().node_features = node_features.clone();
3148 let route = Route { paths, route_params: Some(route_params.clone()) };
3150 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
3151 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
3152 if route.get_total_fees() > max_total_routing_fee_msat {
3153 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
3154 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
3158 log_info!(logger, "Got route: {}", log_route!(route));
3162 // When an adversarial intermediary node observes a payment, it may be able to infer its
3163 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
3164 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
3165 // payment path by adding a randomized 'shadow route' offset to the final hop.
3166 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
3167 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
3169 let network_channels = network_graph.channels();
3170 let network_nodes = network_graph.nodes();
3172 for path in route.paths.iter_mut() {
3173 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
3175 // Remember the last three nodes of the random walk and avoid looping back on them.
3176 // Init with the last three nodes from the actual path, if possible.
3177 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
3178 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
3179 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
3181 // Choose the last publicly known node as the starting point for the random walk.
3182 let mut cur_hop: Option<NodeId> = None;
3183 let mut path_nonce = [0u8; 12];
3184 if let Some(starting_hop) = path.hops.iter().rev()
3185 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
3186 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
3187 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
3190 // Init PRNG with the path-dependant nonce, which is static for private paths.
3191 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
3192 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
3194 // Pick a random path length in [1 .. 3]
3195 prng.process_in_place(&mut random_path_bytes);
3196 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
3198 for random_hop in 0..random_walk_length {
3199 // If we don't find a suitable offset in the public network graph, we default to
3200 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3201 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
3203 if let Some(cur_node_id) = cur_hop {
3204 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
3205 // Randomly choose the next unvisited hop.
3206 prng.process_in_place(&mut random_path_bytes);
3207 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
3208 .checked_rem(cur_node.channels.len())
3209 .and_then(|index| cur_node.channels.get(index))
3210 .and_then(|id| network_channels.get(id)) {
3211 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
3212 if !nodes_to_avoid.iter().any(|x| x == next_id) {
3213 nodes_to_avoid[random_hop] = *next_id;
3214 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
3215 cur_hop = Some(*next_id);
3222 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
3223 .checked_add(random_hop_offset)
3224 .unwrap_or(shadow_ctlv_expiry_delta_offset);
3227 // Limit the total offset to reduce the worst-case locked liquidity timevalue
3228 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
3229 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
3231 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
3232 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3233 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
3234 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
3235 max_path_offset = cmp::max(
3236 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
3237 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
3238 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
3240 // Add 'shadow' CLTV offset to the final hop
3241 if let Some(tail) = path.blinded_tail.as_mut() {
3242 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
3243 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
3245 if let Some(last_hop) = path.hops.last_mut() {
3246 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
3247 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
3252 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
3253 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
3255 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
3256 pub fn build_route_from_hops<L: Deref, GL: Deref>(
3257 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3258 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
3259 ) -> Result<Route, LightningError>
3260 where L::Target: Logger, GL::Target: Logger {
3261 let graph_lock = network_graph.read_only();
3262 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
3263 &graph_lock, logger, random_seed_bytes)?;
3264 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
3268 fn build_route_from_hops_internal<L: Deref>(
3269 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3270 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
3271 ) -> Result<Route, LightningError> where L::Target: Logger {
3274 our_node_id: NodeId,
3275 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
3278 impl ScoreLookUp for HopScorer {
3279 type ScoreParams = ();
3280 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
3281 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
3283 let mut cur_id = self.our_node_id;
3284 for i in 0..self.hop_ids.len() {
3285 if let Some(next_id) = self.hop_ids[i] {
3286 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
3298 impl<'a> Writeable for HopScorer {
3300 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
3305 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
3306 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
3309 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
3310 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
3311 for i in 0..hops.len() {
3312 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
3315 let scorer = HopScorer { our_node_id, hop_ids };
3317 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
3322 use crate::blinded_path::{BlindedHop, BlindedPath};
3323 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
3324 use crate::routing::utxo::UtxoResult;
3325 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
3326 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
3327 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop, CandidatePublicHop};
3328 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
3329 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
3330 use crate::chain::transaction::OutPoint;
3331 use crate::sign::EntropySource;
3332 use crate::ln::ChannelId;
3333 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
3334 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
3335 use crate::ln::channelmanager;
3336 use crate::offers::invoice::BlindedPayInfo;
3337 use crate::util::config::UserConfig;
3338 use crate::util::test_utils as ln_test_utils;
3339 use crate::util::chacha20::ChaCha20;
3340 use crate::util::ser::{Readable, Writeable};
3342 use crate::util::ser::Writer;
3344 use bitcoin::hashes::Hash;
3345 use bitcoin::network::constants::Network;
3346 use bitcoin::blockdata::constants::ChainHash;
3347 use bitcoin::blockdata::script::Builder;
3348 use bitcoin::blockdata::opcodes;
3349 use bitcoin::blockdata::transaction::TxOut;
3350 use bitcoin::hashes::hex::FromHex;
3351 use bitcoin::secp256k1::{PublicKey,SecretKey};
3352 use bitcoin::secp256k1::Secp256k1;
3354 use crate::io::Cursor;
3355 use crate::prelude::*;
3356 use crate::sync::Arc;
3358 use core::convert::TryInto;
3360 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3361 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
3362 channelmanager::ChannelDetails {
3363 channel_id: ChannelId::new_zero(),
3364 counterparty: channelmanager::ChannelCounterparty {
3367 unspendable_punishment_reserve: 0,
3368 forwarding_info: None,
3369 outbound_htlc_minimum_msat: None,
3370 outbound_htlc_maximum_msat: None,
3372 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3375 outbound_scid_alias: None,
3376 inbound_scid_alias: None,
3377 channel_value_satoshis: 0,
3380 outbound_capacity_msat,
3381 next_outbound_htlc_limit_msat: outbound_capacity_msat,
3382 next_outbound_htlc_minimum_msat: 0,
3383 inbound_capacity_msat: 42,
3384 unspendable_punishment_reserve: None,
3385 confirmations_required: None,
3386 confirmations: None,
3387 force_close_spend_delay: None,
3388 is_outbound: true, is_channel_ready: true,
3389 is_usable: true, is_public: true,
3390 inbound_htlc_minimum_msat: None,
3391 inbound_htlc_maximum_msat: None,
3393 feerate_sat_per_1000_weight: None,
3394 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
3399 fn simple_route_test() {
3400 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3401 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3402 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3403 let scorer = ln_test_utils::TestScorer::new();
3404 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3405 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3407 // Simple route to 2 via 1
3409 let route_params = RouteParameters::from_payment_params_and_value(
3410 payment_params.clone(), 0);
3411 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3412 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3413 &Default::default(), &random_seed_bytes) {
3414 assert_eq!(err, "Cannot send a payment of 0 msat");
3415 } else { panic!(); }
3417 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3418 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3419 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3420 assert_eq!(route.paths[0].hops.len(), 2);
3422 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3423 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3424 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3425 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3426 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3427 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3429 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3430 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3431 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3432 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3433 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3434 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3438 fn invalid_first_hop_test() {
3439 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3440 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3441 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3442 let scorer = ln_test_utils::TestScorer::new();
3443 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3444 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3446 // Simple route to 2 via 1
3448 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3450 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3451 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3452 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3453 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3454 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3455 } else { panic!(); }
3457 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3458 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3459 assert_eq!(route.paths[0].hops.len(), 2);
3463 fn htlc_minimum_test() {
3464 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3465 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3466 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3467 let scorer = ln_test_utils::TestScorer::new();
3468 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3469 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3471 // Simple route to 2 via 1
3473 // Disable other paths
3474 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3475 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3476 short_channel_id: 12,
3478 flags: 2, // to disable
3479 cltv_expiry_delta: 0,
3480 htlc_minimum_msat: 0,
3481 htlc_maximum_msat: MAX_VALUE_MSAT,
3483 fee_proportional_millionths: 0,
3484 excess_data: Vec::new()
3486 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3487 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3488 short_channel_id: 3,
3490 flags: 2, // to disable
3491 cltv_expiry_delta: 0,
3492 htlc_minimum_msat: 0,
3493 htlc_maximum_msat: MAX_VALUE_MSAT,
3495 fee_proportional_millionths: 0,
3496 excess_data: Vec::new()
3498 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3499 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3500 short_channel_id: 13,
3502 flags: 2, // to disable
3503 cltv_expiry_delta: 0,
3504 htlc_minimum_msat: 0,
3505 htlc_maximum_msat: MAX_VALUE_MSAT,
3507 fee_proportional_millionths: 0,
3508 excess_data: Vec::new()
3510 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3511 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3512 short_channel_id: 6,
3514 flags: 2, // to disable
3515 cltv_expiry_delta: 0,
3516 htlc_minimum_msat: 0,
3517 htlc_maximum_msat: MAX_VALUE_MSAT,
3519 fee_proportional_millionths: 0,
3520 excess_data: Vec::new()
3522 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3523 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3524 short_channel_id: 7,
3526 flags: 2, // to disable
3527 cltv_expiry_delta: 0,
3528 htlc_minimum_msat: 0,
3529 htlc_maximum_msat: MAX_VALUE_MSAT,
3531 fee_proportional_millionths: 0,
3532 excess_data: Vec::new()
3535 // Check against amount_to_transfer_over_msat.
3536 // Set minimal HTLC of 200_000_000 msat.
3537 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3538 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3539 short_channel_id: 2,
3542 cltv_expiry_delta: 0,
3543 htlc_minimum_msat: 200_000_000,
3544 htlc_maximum_msat: MAX_VALUE_MSAT,
3546 fee_proportional_millionths: 0,
3547 excess_data: Vec::new()
3550 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3552 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3553 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3554 short_channel_id: 4,
3557 cltv_expiry_delta: 0,
3558 htlc_minimum_msat: 0,
3559 htlc_maximum_msat: 199_999_999,
3561 fee_proportional_millionths: 0,
3562 excess_data: Vec::new()
3565 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3566 let route_params = RouteParameters::from_payment_params_and_value(
3567 payment_params, 199_999_999);
3568 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3569 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3570 &Default::default(), &random_seed_bytes) {
3571 assert_eq!(err, "Failed to find a path to the given destination");
3572 } else { panic!(); }
3574 // Lift the restriction on the first hop.
3575 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3576 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3577 short_channel_id: 2,
3580 cltv_expiry_delta: 0,
3581 htlc_minimum_msat: 0,
3582 htlc_maximum_msat: MAX_VALUE_MSAT,
3584 fee_proportional_millionths: 0,
3585 excess_data: Vec::new()
3588 // A payment above the minimum should pass
3589 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3590 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3591 assert_eq!(route.paths[0].hops.len(), 2);
3595 fn htlc_minimum_overpay_test() {
3596 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3597 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3598 let config = UserConfig::default();
3599 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3600 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3602 let scorer = ln_test_utils::TestScorer::new();
3603 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3604 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3606 // A route to node#2 via two paths.
3607 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3608 // Thus, they can't send 60 without overpaying.
3609 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3610 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3611 short_channel_id: 2,
3614 cltv_expiry_delta: 0,
3615 htlc_minimum_msat: 35_000,
3616 htlc_maximum_msat: 40_000,
3618 fee_proportional_millionths: 0,
3619 excess_data: Vec::new()
3621 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3622 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3623 short_channel_id: 12,
3626 cltv_expiry_delta: 0,
3627 htlc_minimum_msat: 35_000,
3628 htlc_maximum_msat: 40_000,
3630 fee_proportional_millionths: 0,
3631 excess_data: Vec::new()
3635 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3636 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3637 short_channel_id: 13,
3640 cltv_expiry_delta: 0,
3641 htlc_minimum_msat: 0,
3642 htlc_maximum_msat: MAX_VALUE_MSAT,
3644 fee_proportional_millionths: 0,
3645 excess_data: Vec::new()
3647 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3648 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3649 short_channel_id: 4,
3652 cltv_expiry_delta: 0,
3653 htlc_minimum_msat: 0,
3654 htlc_maximum_msat: MAX_VALUE_MSAT,
3656 fee_proportional_millionths: 0,
3657 excess_data: Vec::new()
3660 // Disable other paths
3661 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3662 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3663 short_channel_id: 1,
3665 flags: 2, // to disable
3666 cltv_expiry_delta: 0,
3667 htlc_minimum_msat: 0,
3668 htlc_maximum_msat: MAX_VALUE_MSAT,
3670 fee_proportional_millionths: 0,
3671 excess_data: Vec::new()
3674 let mut route_params = RouteParameters::from_payment_params_and_value(
3675 payment_params.clone(), 60_000);
3676 route_params.max_total_routing_fee_msat = Some(15_000);
3677 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3678 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3679 // Overpay fees to hit htlc_minimum_msat.
3680 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3681 // TODO: this could be better balanced to overpay 10k and not 15k.
3682 assert_eq!(overpaid_fees, 15_000);
3684 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3685 // while taking even more fee to match htlc_minimum_msat.
3686 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3687 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3688 short_channel_id: 12,
3691 cltv_expiry_delta: 0,
3692 htlc_minimum_msat: 65_000,
3693 htlc_maximum_msat: 80_000,
3695 fee_proportional_millionths: 0,
3696 excess_data: Vec::new()
3698 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3699 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3700 short_channel_id: 2,
3703 cltv_expiry_delta: 0,
3704 htlc_minimum_msat: 0,
3705 htlc_maximum_msat: MAX_VALUE_MSAT,
3707 fee_proportional_millionths: 0,
3708 excess_data: Vec::new()
3710 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3711 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3712 short_channel_id: 4,
3715 cltv_expiry_delta: 0,
3716 htlc_minimum_msat: 0,
3717 htlc_maximum_msat: MAX_VALUE_MSAT,
3719 fee_proportional_millionths: 100_000,
3720 excess_data: Vec::new()
3723 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3724 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3725 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3726 assert_eq!(route.paths.len(), 1);
3727 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3728 let fees = route.paths[0].hops[0].fee_msat;
3729 assert_eq!(fees, 5_000);
3731 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3732 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3733 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3734 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3735 // the other channel.
3736 assert_eq!(route.paths.len(), 1);
3737 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3738 let fees = route.paths[0].hops[0].fee_msat;
3739 assert_eq!(fees, 5_000);
3743 fn htlc_minimum_recipient_overpay_test() {
3744 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3745 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3746 let config = UserConfig::default();
3747 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3748 let scorer = ln_test_utils::TestScorer::new();
3749 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3750 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3752 // Route to node2 over a single path which requires overpaying the recipient themselves.
3754 // First disable all paths except the us -> node1 -> node2 path
3755 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3756 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3757 short_channel_id: 13,
3760 cltv_expiry_delta: 0,
3761 htlc_minimum_msat: 0,
3762 htlc_maximum_msat: 0,
3764 fee_proportional_millionths: 0,
3765 excess_data: Vec::new()
3768 // Set channel 4 to free but with a high htlc_minimum_msat
3769 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3770 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3771 short_channel_id: 4,
3774 cltv_expiry_delta: 0,
3775 htlc_minimum_msat: 15_000,
3776 htlc_maximum_msat: MAX_VALUE_MSAT,
3778 fee_proportional_millionths: 0,
3779 excess_data: Vec::new()
3782 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3783 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3784 // what we try to find a route for, so this test only just happens to work out to exactly
3786 let mut route_params = RouteParameters::from_payment_params_and_value(
3787 payment_params.clone(), 5_000);
3788 route_params.max_total_routing_fee_msat = Some(9_999);
3789 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3790 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3791 &Default::default(), &random_seed_bytes) {
3792 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3793 } else { panic!(); }
3795 let mut route_params = RouteParameters::from_payment_params_and_value(
3796 payment_params.clone(), 5_000);
3797 route_params.max_total_routing_fee_msat = Some(10_000);
3798 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3799 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3800 assert_eq!(route.get_total_fees(), 10_000);
3804 fn disable_channels_test() {
3805 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3806 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3807 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3808 let scorer = ln_test_utils::TestScorer::new();
3809 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3810 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3812 // // Disable channels 4 and 12 by flags=2
3813 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3814 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3815 short_channel_id: 4,
3817 flags: 2, // to disable
3818 cltv_expiry_delta: 0,
3819 htlc_minimum_msat: 0,
3820 htlc_maximum_msat: MAX_VALUE_MSAT,
3822 fee_proportional_millionths: 0,
3823 excess_data: Vec::new()
3825 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3826 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3827 short_channel_id: 12,
3829 flags: 2, // to disable
3830 cltv_expiry_delta: 0,
3831 htlc_minimum_msat: 0,
3832 htlc_maximum_msat: MAX_VALUE_MSAT,
3834 fee_proportional_millionths: 0,
3835 excess_data: Vec::new()
3838 // If all the channels require some features we don't understand, route should fail
3839 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3840 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3841 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3842 &Default::default(), &random_seed_bytes) {
3843 assert_eq!(err, "Failed to find a path to the given destination");
3844 } else { panic!(); }
3846 // If we specify a channel to node7, that overrides our local channel view and that gets used
3847 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3848 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3849 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3850 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3851 &Default::default(), &random_seed_bytes).unwrap();
3852 assert_eq!(route.paths[0].hops.len(), 2);
3854 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3855 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3856 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3857 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3858 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3859 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3861 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3862 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3863 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3864 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3865 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3866 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3870 fn disable_node_test() {
3871 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3872 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3873 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3874 let scorer = ln_test_utils::TestScorer::new();
3875 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3876 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3878 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3879 let mut unknown_features = NodeFeatures::empty();
3880 unknown_features.set_unknown_feature_required();
3881 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3882 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3883 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3885 // If all nodes require some features we don't understand, route should fail
3886 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3887 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3888 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3889 &Default::default(), &random_seed_bytes) {
3890 assert_eq!(err, "Failed to find a path to the given destination");
3891 } else { panic!(); }
3893 // If we specify a channel to node7, that overrides our local channel view and that gets used
3894 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3895 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3896 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3897 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3898 &Default::default(), &random_seed_bytes).unwrap();
3899 assert_eq!(route.paths[0].hops.len(), 2);
3901 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3902 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3903 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3904 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3905 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3906 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3908 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3909 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3910 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3911 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3912 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3913 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3915 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3916 // naively) assume that the user checked the feature bits on the invoice, which override
3917 // the node_announcement.
3921 fn our_chans_test() {
3922 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3923 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3924 let scorer = ln_test_utils::TestScorer::new();
3925 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3926 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3928 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3929 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3930 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3931 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3932 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3933 assert_eq!(route.paths[0].hops.len(), 3);
3935 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3936 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3937 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3938 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3939 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3940 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3942 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3943 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3944 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3945 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3946 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3947 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3949 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3950 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3951 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3952 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3953 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3954 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3956 // If we specify a channel to node7, that overrides our local channel view and that gets used
3957 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3958 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3959 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3960 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3961 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3962 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3963 &Default::default(), &random_seed_bytes).unwrap();
3964 assert_eq!(route.paths[0].hops.len(), 2);
3966 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3967 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3968 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3969 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3970 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3971 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3973 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3974 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3975 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3976 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3977 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3978 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3981 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3982 let zero_fees = RoutingFees {
3984 proportional_millionths: 0,
3986 vec![RouteHint(vec![RouteHintHop {
3987 src_node_id: nodes[3],
3988 short_channel_id: 8,
3990 cltv_expiry_delta: (8 << 4) | 1,
3991 htlc_minimum_msat: None,
3992 htlc_maximum_msat: None,
3994 ]), RouteHint(vec![RouteHintHop {
3995 src_node_id: nodes[4],
3996 short_channel_id: 9,
3999 proportional_millionths: 0,
4001 cltv_expiry_delta: (9 << 4) | 1,
4002 htlc_minimum_msat: None,
4003 htlc_maximum_msat: None,
4004 }]), RouteHint(vec![RouteHintHop {
4005 src_node_id: nodes[5],
4006 short_channel_id: 10,
4008 cltv_expiry_delta: (10 << 4) | 1,
4009 htlc_minimum_msat: None,
4010 htlc_maximum_msat: None,
4014 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4015 let zero_fees = RoutingFees {
4017 proportional_millionths: 0,
4019 vec![RouteHint(vec![RouteHintHop {
4020 src_node_id: nodes[2],
4021 short_channel_id: 5,
4024 proportional_millionths: 0,
4026 cltv_expiry_delta: (5 << 4) | 1,
4027 htlc_minimum_msat: None,
4028 htlc_maximum_msat: None,
4030 src_node_id: nodes[3],
4031 short_channel_id: 8,
4033 cltv_expiry_delta: (8 << 4) | 1,
4034 htlc_minimum_msat: None,
4035 htlc_maximum_msat: None,
4037 ]), RouteHint(vec![RouteHintHop {
4038 src_node_id: nodes[4],
4039 short_channel_id: 9,
4042 proportional_millionths: 0,
4044 cltv_expiry_delta: (9 << 4) | 1,
4045 htlc_minimum_msat: None,
4046 htlc_maximum_msat: None,
4047 }]), RouteHint(vec![RouteHintHop {
4048 src_node_id: nodes[5],
4049 short_channel_id: 10,
4051 cltv_expiry_delta: (10 << 4) | 1,
4052 htlc_minimum_msat: None,
4053 htlc_maximum_msat: None,
4058 fn partial_route_hint_test() {
4059 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4060 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4061 let scorer = ln_test_utils::TestScorer::new();
4062 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4063 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4065 // Simple test across 2, 3, 5, and 4 via a last_hop channel
4066 // Tests the behaviour when the RouteHint contains a suboptimal hop.
4067 // RouteHint may be partially used by the algo to build the best path.
4069 // First check that last hop can't have its source as the payee.
4070 let invalid_last_hop = RouteHint(vec![RouteHintHop {
4071 src_node_id: nodes[6],
4072 short_channel_id: 8,
4075 proportional_millionths: 0,
4077 cltv_expiry_delta: (8 << 4) | 1,
4078 htlc_minimum_msat: None,
4079 htlc_maximum_msat: None,
4082 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
4083 invalid_last_hops.push(invalid_last_hop);
4085 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4086 .with_route_hints(invalid_last_hops).unwrap();
4087 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4088 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
4089 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
4090 &Default::default(), &random_seed_bytes) {
4091 assert_eq!(err, "Route hint cannot have the payee as the source.");
4092 } else { panic!(); }
4095 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4096 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
4097 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4098 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4099 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4100 assert_eq!(route.paths[0].hops.len(), 5);
4102 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4103 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4104 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4105 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4106 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4107 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4109 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4110 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4111 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4112 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4113 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4114 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4116 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4117 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4118 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4119 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4120 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4121 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4123 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4124 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4125 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4126 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4127 // If we have a peer in the node map, we'll use their features here since we don't have
4128 // a way of figuring out their features from the invoice:
4129 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4130 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4132 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4133 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4134 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4135 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4136 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4137 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4140 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4141 let zero_fees = RoutingFees {
4143 proportional_millionths: 0,
4145 vec![RouteHint(vec![RouteHintHop {
4146 src_node_id: nodes[3],
4147 short_channel_id: 8,
4149 cltv_expiry_delta: (8 << 4) | 1,
4150 htlc_minimum_msat: None,
4151 htlc_maximum_msat: None,
4152 }]), RouteHint(vec![
4154 ]), RouteHint(vec![RouteHintHop {
4155 src_node_id: nodes[5],
4156 short_channel_id: 10,
4158 cltv_expiry_delta: (10 << 4) | 1,
4159 htlc_minimum_msat: None,
4160 htlc_maximum_msat: None,
4165 fn ignores_empty_last_hops_test() {
4166 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4167 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4168 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
4169 let scorer = ln_test_utils::TestScorer::new();
4170 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4171 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4173 // Test handling of an empty RouteHint passed in Invoice.
4174 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4175 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4176 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4177 assert_eq!(route.paths[0].hops.len(), 5);
4179 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4180 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4181 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4182 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4183 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4184 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4186 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4187 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4188 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4189 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4190 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4191 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4193 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4194 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4195 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4196 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4197 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4198 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4200 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4201 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4202 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4203 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4204 // If we have a peer in the node map, we'll use their features here since we don't have
4205 // a way of figuring out their features from the invoice:
4206 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4207 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4209 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4210 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4211 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4212 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4213 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4214 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4217 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
4219 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
4220 let zero_fees = RoutingFees {
4222 proportional_millionths: 0,
4224 vec![RouteHint(vec![RouteHintHop {
4225 src_node_id: hint_hops[0],
4226 short_channel_id: 0xff00,
4229 proportional_millionths: 0,
4231 cltv_expiry_delta: (5 << 4) | 1,
4232 htlc_minimum_msat: None,
4233 htlc_maximum_msat: None,
4235 src_node_id: hint_hops[1],
4236 short_channel_id: 0xff01,
4238 cltv_expiry_delta: (8 << 4) | 1,
4239 htlc_minimum_msat: None,
4240 htlc_maximum_msat: None,
4245 fn multi_hint_last_hops_test() {
4246 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4247 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4248 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
4249 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4250 let scorer = ln_test_utils::TestScorer::new();
4251 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4252 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4253 // Test through channels 2, 3, 0xff00, 0xff01.
4254 // Test shows that multiple hop hints are considered.
4256 // Disabling channels 6 & 7 by flags=2
4257 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4258 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4259 short_channel_id: 6,
4261 flags: 2, // to disable
4262 cltv_expiry_delta: 0,
4263 htlc_minimum_msat: 0,
4264 htlc_maximum_msat: MAX_VALUE_MSAT,
4266 fee_proportional_millionths: 0,
4267 excess_data: Vec::new()
4269 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4270 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4271 short_channel_id: 7,
4273 flags: 2, // to disable
4274 cltv_expiry_delta: 0,
4275 htlc_minimum_msat: 0,
4276 htlc_maximum_msat: MAX_VALUE_MSAT,
4278 fee_proportional_millionths: 0,
4279 excess_data: Vec::new()
4282 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4283 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4284 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4285 assert_eq!(route.paths[0].hops.len(), 4);
4287 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4288 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4289 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4290 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4291 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4292 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4294 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4295 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4296 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4297 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4298 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4299 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4301 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4302 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4303 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4304 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4305 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4306 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4308 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4309 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4310 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4311 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4312 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4313 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4317 fn private_multi_hint_last_hops_test() {
4318 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4319 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4321 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4322 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4324 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4325 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4326 let scorer = ln_test_utils::TestScorer::new();
4327 // Test through channels 2, 3, 0xff00, 0xff01.
4328 // Test shows that multiple hop hints are considered.
4330 // Disabling channels 6 & 7 by flags=2
4331 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4332 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4333 short_channel_id: 6,
4335 flags: 2, // to disable
4336 cltv_expiry_delta: 0,
4337 htlc_minimum_msat: 0,
4338 htlc_maximum_msat: MAX_VALUE_MSAT,
4340 fee_proportional_millionths: 0,
4341 excess_data: Vec::new()
4343 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4344 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4345 short_channel_id: 7,
4347 flags: 2, // to disable
4348 cltv_expiry_delta: 0,
4349 htlc_minimum_msat: 0,
4350 htlc_maximum_msat: MAX_VALUE_MSAT,
4352 fee_proportional_millionths: 0,
4353 excess_data: Vec::new()
4356 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4357 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4358 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4359 assert_eq!(route.paths[0].hops.len(), 4);
4361 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4362 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4363 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4364 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4365 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4366 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4368 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4369 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4370 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4371 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4372 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4373 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4375 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4376 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4377 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4378 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4379 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4380 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4382 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4383 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4384 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4385 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4386 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4387 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4390 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4391 let zero_fees = RoutingFees {
4393 proportional_millionths: 0,
4395 vec![RouteHint(vec![RouteHintHop {
4396 src_node_id: nodes[4],
4397 short_channel_id: 11,
4399 cltv_expiry_delta: (11 << 4) | 1,
4400 htlc_minimum_msat: None,
4401 htlc_maximum_msat: None,
4403 src_node_id: nodes[3],
4404 short_channel_id: 8,
4406 cltv_expiry_delta: (8 << 4) | 1,
4407 htlc_minimum_msat: None,
4408 htlc_maximum_msat: None,
4409 }]), RouteHint(vec![RouteHintHop {
4410 src_node_id: nodes[4],
4411 short_channel_id: 9,
4414 proportional_millionths: 0,
4416 cltv_expiry_delta: (9 << 4) | 1,
4417 htlc_minimum_msat: None,
4418 htlc_maximum_msat: None,
4419 }]), RouteHint(vec![RouteHintHop {
4420 src_node_id: nodes[5],
4421 short_channel_id: 10,
4423 cltv_expiry_delta: (10 << 4) | 1,
4424 htlc_minimum_msat: None,
4425 htlc_maximum_msat: None,
4430 fn last_hops_with_public_channel_test() {
4431 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4432 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4433 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4434 let scorer = ln_test_utils::TestScorer::new();
4435 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4436 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4437 // This test shows that public routes can be present in the invoice
4438 // which would be handled in the same manner.
4440 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4441 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4442 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4443 assert_eq!(route.paths[0].hops.len(), 5);
4445 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4446 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4447 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4448 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4449 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4450 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4452 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4453 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4454 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4455 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4456 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4457 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4459 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4460 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4461 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4462 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4463 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4464 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4466 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4467 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4468 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4469 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4470 // If we have a peer in the node map, we'll use their features here since we don't have
4471 // a way of figuring out their features from the invoice:
4472 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4473 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4475 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4476 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4477 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4478 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4479 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4480 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4484 fn our_chans_last_hop_connect_test() {
4485 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4486 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4487 let scorer = ln_test_utils::TestScorer::new();
4488 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4489 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4491 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4492 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4493 let mut last_hops = last_hops(&nodes);
4494 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4495 .with_route_hints(last_hops.clone()).unwrap();
4496 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4497 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4498 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4499 &Default::default(), &random_seed_bytes).unwrap();
4500 assert_eq!(route.paths[0].hops.len(), 2);
4502 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4503 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4504 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
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(), &vec![0b11]);
4507 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4509 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4510 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4511 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
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(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4516 last_hops[0].0[0].fees.base_msat = 1000;
4518 // Revert to via 6 as the fee on 8 goes up
4519 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4520 .with_route_hints(last_hops).unwrap();
4521 let route_params = RouteParameters::from_payment_params_and_value(
4522 payment_params.clone(), 100);
4523 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4524 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4525 assert_eq!(route.paths[0].hops.len(), 4);
4527 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4528 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4529 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4530 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4531 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4532 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4534 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4535 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4536 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4537 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4538 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4539 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4541 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4542 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4543 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4544 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4545 // If we have a peer in the node map, we'll use their features here since we don't have
4546 // a way of figuring out their features from the invoice:
4547 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4548 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4550 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4551 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4552 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4553 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4554 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4555 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4557 // ...but still use 8 for larger payments as 6 has a variable feerate
4558 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4559 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4560 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4561 assert_eq!(route.paths[0].hops.len(), 5);
4563 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4564 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4565 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4566 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4567 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4568 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4570 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4571 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4572 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4573 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4574 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4575 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4577 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4578 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4579 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4580 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4581 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4582 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4584 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4585 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4586 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4587 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4588 // If we have a peer in the node map, we'll use their features here since we don't have
4589 // a way of figuring out their features from the invoice:
4590 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4591 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4593 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4594 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4595 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4596 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4597 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4598 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4601 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> {
4602 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4603 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4604 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4606 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4607 let last_hops = RouteHint(vec![RouteHintHop {
4608 src_node_id: middle_node_id,
4609 short_channel_id: 8,
4612 proportional_millionths: last_hop_fee_prop,
4614 cltv_expiry_delta: (8 << 4) | 1,
4615 htlc_minimum_msat: None,
4616 htlc_maximum_msat: last_hop_htlc_max,
4618 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4619 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4620 let scorer = ln_test_utils::TestScorer::new();
4621 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4622 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4623 let logger = ln_test_utils::TestLogger::new();
4624 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4625 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4626 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4627 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4628 &random_seed_bytes);
4633 fn unannounced_path_test() {
4634 // We should be able to send a payment to a destination without any help of a routing graph
4635 // if we have a channel with a common counterparty that appears in the first and last hop
4637 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4639 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4640 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4641 assert_eq!(route.paths[0].hops.len(), 2);
4643 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4644 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4645 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4646 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4647 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4648 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4650 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4651 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4652 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4653 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4654 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4655 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4659 fn overflow_unannounced_path_test_liquidity_underflow() {
4660 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4661 // the last-hop had a fee which overflowed a u64, we'd panic.
4662 // This was due to us adding the first-hop from us unconditionally, causing us to think
4663 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4664 // In this test, we previously hit a subtraction underflow due to having less available
4665 // liquidity at the last hop than 0.
4666 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());
4670 fn overflow_unannounced_path_test_feerate_overflow() {
4671 // This tests for the same case as above, except instead of hitting a subtraction
4672 // underflow, we hit a case where the fee charged at a hop overflowed.
4673 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());
4677 fn available_amount_while_routing_test() {
4678 // Tests whether we choose the correct available channel amount while routing.
4680 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4681 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4682 let scorer = ln_test_utils::TestScorer::new();
4683 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4684 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4685 let config = UserConfig::default();
4686 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4687 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4690 // We will use a simple single-path route from
4691 // our node to node2 via node0: channels {1, 3}.
4693 // First disable all other paths.
4694 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4695 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4696 short_channel_id: 2,
4699 cltv_expiry_delta: 0,
4700 htlc_minimum_msat: 0,
4701 htlc_maximum_msat: 100_000,
4703 fee_proportional_millionths: 0,
4704 excess_data: Vec::new()
4706 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4707 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4708 short_channel_id: 12,
4711 cltv_expiry_delta: 0,
4712 htlc_minimum_msat: 0,
4713 htlc_maximum_msat: 100_000,
4715 fee_proportional_millionths: 0,
4716 excess_data: Vec::new()
4719 // Make the first channel (#1) very permissive,
4720 // and we will be testing all limits on the second channel.
4721 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4722 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4723 short_channel_id: 1,
4726 cltv_expiry_delta: 0,
4727 htlc_minimum_msat: 0,
4728 htlc_maximum_msat: 1_000_000_000,
4730 fee_proportional_millionths: 0,
4731 excess_data: Vec::new()
4734 // First, let's see if routing works if we have absolutely no idea about the available amount.
4735 // In this case, it should be set to 250_000 sats.
4736 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4737 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4738 short_channel_id: 3,
4741 cltv_expiry_delta: 0,
4742 htlc_minimum_msat: 0,
4743 htlc_maximum_msat: 250_000_000,
4745 fee_proportional_millionths: 0,
4746 excess_data: Vec::new()
4750 // Attempt to route more than available results in a failure.
4751 let route_params = RouteParameters::from_payment_params_and_value(
4752 payment_params.clone(), 250_000_001);
4753 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4754 &our_id, &route_params, &network_graph.read_only(), None,
4755 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4756 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4757 } else { panic!(); }
4761 // Now, attempt to route an exact amount we have should be fine.
4762 let route_params = RouteParameters::from_payment_params_and_value(
4763 payment_params.clone(), 250_000_000);
4764 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4765 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4766 assert_eq!(route.paths.len(), 1);
4767 let path = route.paths.last().unwrap();
4768 assert_eq!(path.hops.len(), 2);
4769 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4770 assert_eq!(path.final_value_msat(), 250_000_000);
4773 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4774 // Disable channel #1 and use another first hop.
4775 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4776 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4777 short_channel_id: 1,
4780 cltv_expiry_delta: 0,
4781 htlc_minimum_msat: 0,
4782 htlc_maximum_msat: 1_000_000_000,
4784 fee_proportional_millionths: 0,
4785 excess_data: Vec::new()
4788 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4789 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4792 // Attempt to route more than available results in a failure.
4793 let route_params = RouteParameters::from_payment_params_and_value(
4794 payment_params.clone(), 200_000_001);
4795 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4796 &our_id, &route_params, &network_graph.read_only(),
4797 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4798 &Default::default(), &random_seed_bytes) {
4799 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4800 } else { panic!(); }
4804 // Now, attempt to route an exact amount we have should be fine.
4805 let route_params = RouteParameters::from_payment_params_and_value(
4806 payment_params.clone(), 200_000_000);
4807 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4808 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4809 &Default::default(), &random_seed_bytes).unwrap();
4810 assert_eq!(route.paths.len(), 1);
4811 let path = route.paths.last().unwrap();
4812 assert_eq!(path.hops.len(), 2);
4813 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4814 assert_eq!(path.final_value_msat(), 200_000_000);
4817 // Enable channel #1 back.
4818 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4819 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4820 short_channel_id: 1,
4823 cltv_expiry_delta: 0,
4824 htlc_minimum_msat: 0,
4825 htlc_maximum_msat: 1_000_000_000,
4827 fee_proportional_millionths: 0,
4828 excess_data: Vec::new()
4832 // Now let's see if routing works if we know only htlc_maximum_msat.
4833 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4834 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4835 short_channel_id: 3,
4838 cltv_expiry_delta: 0,
4839 htlc_minimum_msat: 0,
4840 htlc_maximum_msat: 15_000,
4842 fee_proportional_millionths: 0,
4843 excess_data: Vec::new()
4847 // Attempt to route more than available results in a failure.
4848 let route_params = RouteParameters::from_payment_params_and_value(
4849 payment_params.clone(), 15_001);
4850 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4851 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4852 &scorer, &Default::default(), &random_seed_bytes) {
4853 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4854 } else { panic!(); }
4858 // Now, attempt to route an exact amount we have should be fine.
4859 let route_params = RouteParameters::from_payment_params_and_value(
4860 payment_params.clone(), 15_000);
4861 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4862 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4863 assert_eq!(route.paths.len(), 1);
4864 let path = route.paths.last().unwrap();
4865 assert_eq!(path.hops.len(), 2);
4866 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4867 assert_eq!(path.final_value_msat(), 15_000);
4870 // Now let's see if routing works if we know only capacity from the UTXO.
4872 // We can't change UTXO capacity on the fly, so we'll disable
4873 // the existing channel and add another one with the capacity we need.
4874 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4875 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4876 short_channel_id: 3,
4879 cltv_expiry_delta: 0,
4880 htlc_minimum_msat: 0,
4881 htlc_maximum_msat: MAX_VALUE_MSAT,
4883 fee_proportional_millionths: 0,
4884 excess_data: Vec::new()
4887 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4888 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4889 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4890 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4891 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4893 *chain_monitor.utxo_ret.lock().unwrap() =
4894 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4895 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4897 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4898 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4899 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4900 short_channel_id: 333,
4903 cltv_expiry_delta: (3 << 4) | 1,
4904 htlc_minimum_msat: 0,
4905 htlc_maximum_msat: 15_000,
4907 fee_proportional_millionths: 0,
4908 excess_data: Vec::new()
4910 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4911 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4912 short_channel_id: 333,
4915 cltv_expiry_delta: (3 << 4) | 2,
4916 htlc_minimum_msat: 0,
4917 htlc_maximum_msat: 15_000,
4919 fee_proportional_millionths: 0,
4920 excess_data: Vec::new()
4924 // Attempt to route more than available results in a failure.
4925 let route_params = RouteParameters::from_payment_params_and_value(
4926 payment_params.clone(), 15_001);
4927 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4928 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4929 &scorer, &Default::default(), &random_seed_bytes) {
4930 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4931 } else { panic!(); }
4935 // Now, attempt to route an exact amount we have should be fine.
4936 let route_params = RouteParameters::from_payment_params_and_value(
4937 payment_params.clone(), 15_000);
4938 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4939 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4940 assert_eq!(route.paths.len(), 1);
4941 let path = route.paths.last().unwrap();
4942 assert_eq!(path.hops.len(), 2);
4943 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4944 assert_eq!(path.final_value_msat(), 15_000);
4947 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4948 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4949 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4950 short_channel_id: 333,
4953 cltv_expiry_delta: 0,
4954 htlc_minimum_msat: 0,
4955 htlc_maximum_msat: 10_000,
4957 fee_proportional_millionths: 0,
4958 excess_data: Vec::new()
4962 // Attempt to route more than available results in a failure.
4963 let route_params = RouteParameters::from_payment_params_and_value(
4964 payment_params.clone(), 10_001);
4965 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4966 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4967 &scorer, &Default::default(), &random_seed_bytes) {
4968 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4969 } else { panic!(); }
4973 // Now, attempt to route an exact amount we have should be fine.
4974 let route_params = RouteParameters::from_payment_params_and_value(
4975 payment_params.clone(), 10_000);
4976 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4977 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4978 assert_eq!(route.paths.len(), 1);
4979 let path = route.paths.last().unwrap();
4980 assert_eq!(path.hops.len(), 2);
4981 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4982 assert_eq!(path.final_value_msat(), 10_000);
4987 fn available_liquidity_last_hop_test() {
4988 // Check that available liquidity properly limits the path even when only
4989 // one of the latter hops is limited.
4990 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4991 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4992 let scorer = ln_test_utils::TestScorer::new();
4993 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4994 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4995 let config = UserConfig::default();
4996 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4997 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5000 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5001 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
5002 // Total capacity: 50 sats.
5004 // Disable other potential paths.
5005 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5006 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5007 short_channel_id: 2,
5010 cltv_expiry_delta: 0,
5011 htlc_minimum_msat: 0,
5012 htlc_maximum_msat: 100_000,
5014 fee_proportional_millionths: 0,
5015 excess_data: Vec::new()
5017 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5018 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5019 short_channel_id: 7,
5022 cltv_expiry_delta: 0,
5023 htlc_minimum_msat: 0,
5024 htlc_maximum_msat: 100_000,
5026 fee_proportional_millionths: 0,
5027 excess_data: Vec::new()
5032 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5033 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5034 short_channel_id: 12,
5037 cltv_expiry_delta: 0,
5038 htlc_minimum_msat: 0,
5039 htlc_maximum_msat: 100_000,
5041 fee_proportional_millionths: 0,
5042 excess_data: Vec::new()
5044 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5045 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5046 short_channel_id: 13,
5049 cltv_expiry_delta: 0,
5050 htlc_minimum_msat: 0,
5051 htlc_maximum_msat: 100_000,
5053 fee_proportional_millionths: 0,
5054 excess_data: Vec::new()
5057 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5058 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5059 short_channel_id: 6,
5062 cltv_expiry_delta: 0,
5063 htlc_minimum_msat: 0,
5064 htlc_maximum_msat: 50_000,
5066 fee_proportional_millionths: 0,
5067 excess_data: Vec::new()
5069 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5070 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5071 short_channel_id: 11,
5074 cltv_expiry_delta: 0,
5075 htlc_minimum_msat: 0,
5076 htlc_maximum_msat: 100_000,
5078 fee_proportional_millionths: 0,
5079 excess_data: Vec::new()
5082 // Attempt to route more than available results in a failure.
5083 let route_params = RouteParameters::from_payment_params_and_value(
5084 payment_params.clone(), 60_000);
5085 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5086 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5087 &scorer, &Default::default(), &random_seed_bytes) {
5088 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5089 } else { panic!(); }
5093 // Now, attempt to route 49 sats (just a bit below the capacity).
5094 let route_params = RouteParameters::from_payment_params_and_value(
5095 payment_params.clone(), 49_000);
5096 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5097 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5098 assert_eq!(route.paths.len(), 1);
5099 let mut total_amount_paid_msat = 0;
5100 for path in &route.paths {
5101 assert_eq!(path.hops.len(), 4);
5102 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5103 total_amount_paid_msat += path.final_value_msat();
5105 assert_eq!(total_amount_paid_msat, 49_000);
5109 // Attempt to route an exact amount is also fine
5110 let route_params = RouteParameters::from_payment_params_and_value(
5111 payment_params, 50_000);
5112 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5113 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5114 assert_eq!(route.paths.len(), 1);
5115 let mut total_amount_paid_msat = 0;
5116 for path in &route.paths {
5117 assert_eq!(path.hops.len(), 4);
5118 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5119 total_amount_paid_msat += path.final_value_msat();
5121 assert_eq!(total_amount_paid_msat, 50_000);
5126 fn ignore_fee_first_hop_test() {
5127 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5128 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5129 let scorer = ln_test_utils::TestScorer::new();
5130 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5131 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5132 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5134 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5135 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5136 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5137 short_channel_id: 1,
5140 cltv_expiry_delta: 0,
5141 htlc_minimum_msat: 0,
5142 htlc_maximum_msat: 100_000,
5143 fee_base_msat: 1_000_000,
5144 fee_proportional_millionths: 0,
5145 excess_data: Vec::new()
5147 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5148 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5149 short_channel_id: 3,
5152 cltv_expiry_delta: 0,
5153 htlc_minimum_msat: 0,
5154 htlc_maximum_msat: 50_000,
5156 fee_proportional_millionths: 0,
5157 excess_data: Vec::new()
5161 let route_params = RouteParameters::from_payment_params_and_value(
5162 payment_params, 50_000);
5163 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5164 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5165 assert_eq!(route.paths.len(), 1);
5166 let mut total_amount_paid_msat = 0;
5167 for path in &route.paths {
5168 assert_eq!(path.hops.len(), 2);
5169 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5170 total_amount_paid_msat += path.final_value_msat();
5172 assert_eq!(total_amount_paid_msat, 50_000);
5177 fn simple_mpp_route_test() {
5178 let (secp_ctx, _, _, _, _) = build_graph();
5179 let (_, _, _, nodes) = get_nodes(&secp_ctx);
5180 let config = UserConfig::default();
5181 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5182 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5184 do_simple_mpp_route_test(clear_payment_params);
5186 // MPP to a 1-hop blinded path for nodes[2]
5187 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
5188 let blinded_path = BlindedPath {
5189 introduction_node_id: nodes[2],
5190 blinding_point: ln_test_utils::pubkey(42),
5191 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
5193 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
5195 fee_proportional_millionths: 0,
5196 htlc_minimum_msat: 0,
5197 htlc_maximum_msat: 0,
5198 cltv_expiry_delta: 0,
5199 features: BlindedHopFeatures::empty(),
5201 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
5202 .with_bolt12_features(bolt12_features.clone()).unwrap();
5203 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
5205 // MPP to 3 2-hop blinded paths
5206 let mut blinded_path_node_0 = blinded_path.clone();
5207 blinded_path_node_0.introduction_node_id = nodes[0];
5208 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
5209 let mut node_0_payinfo = blinded_payinfo.clone();
5210 node_0_payinfo.htlc_maximum_msat = 50_000;
5212 let mut blinded_path_node_7 = blinded_path_node_0.clone();
5213 blinded_path_node_7.introduction_node_id = nodes[7];
5214 let mut node_7_payinfo = blinded_payinfo.clone();
5215 node_7_payinfo.htlc_maximum_msat = 60_000;
5217 let mut blinded_path_node_1 = blinded_path_node_0.clone();
5218 blinded_path_node_1.introduction_node_id = nodes[1];
5219 let mut node_1_payinfo = blinded_payinfo.clone();
5220 node_1_payinfo.htlc_maximum_msat = 180_000;
5222 let two_hop_blinded_payment_params = PaymentParameters::blinded(
5224 (node_0_payinfo, blinded_path_node_0),
5225 (node_7_payinfo, blinded_path_node_7),
5226 (node_1_payinfo, blinded_path_node_1)
5228 .with_bolt12_features(bolt12_features).unwrap();
5229 do_simple_mpp_route_test(two_hop_blinded_payment_params);
5233 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
5234 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5235 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5236 let scorer = ln_test_utils::TestScorer::new();
5237 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5238 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5240 // We need a route consisting of 3 paths:
5241 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5242 // To achieve this, the amount being transferred should be around
5243 // the total capacity of these 3 paths.
5245 // First, we set limits on these (previously unlimited) channels.
5246 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
5248 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5249 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5250 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5251 short_channel_id: 1,
5254 cltv_expiry_delta: 0,
5255 htlc_minimum_msat: 0,
5256 htlc_maximum_msat: 100_000,
5258 fee_proportional_millionths: 0,
5259 excess_data: Vec::new()
5261 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5262 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5263 short_channel_id: 3,
5266 cltv_expiry_delta: 0,
5267 htlc_minimum_msat: 0,
5268 htlc_maximum_msat: 50_000,
5270 fee_proportional_millionths: 0,
5271 excess_data: Vec::new()
5274 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
5275 // (total limit 60).
5276 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5277 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5278 short_channel_id: 12,
5281 cltv_expiry_delta: 0,
5282 htlc_minimum_msat: 0,
5283 htlc_maximum_msat: 60_000,
5285 fee_proportional_millionths: 0,
5286 excess_data: Vec::new()
5288 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5289 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5290 short_channel_id: 13,
5293 cltv_expiry_delta: 0,
5294 htlc_minimum_msat: 0,
5295 htlc_maximum_msat: 60_000,
5297 fee_proportional_millionths: 0,
5298 excess_data: Vec::new()
5301 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5302 // (total capacity 180 sats).
5303 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5304 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5305 short_channel_id: 2,
5308 cltv_expiry_delta: 0,
5309 htlc_minimum_msat: 0,
5310 htlc_maximum_msat: 200_000,
5312 fee_proportional_millionths: 0,
5313 excess_data: Vec::new()
5315 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5316 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5317 short_channel_id: 4,
5320 cltv_expiry_delta: 0,
5321 htlc_minimum_msat: 0,
5322 htlc_maximum_msat: 180_000,
5324 fee_proportional_millionths: 0,
5325 excess_data: Vec::new()
5329 // Attempt to route more than available results in a failure.
5330 let route_params = RouteParameters::from_payment_params_and_value(
5331 payment_params.clone(), 300_000);
5332 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5333 &our_id, &route_params, &network_graph.read_only(), None,
5334 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5335 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5336 } else { panic!(); }
5340 // Attempt to route while setting max_path_count to 0 results in a failure.
5341 let zero_payment_params = payment_params.clone().with_max_path_count(0);
5342 let route_params = RouteParameters::from_payment_params_and_value(
5343 zero_payment_params, 100);
5344 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5345 &our_id, &route_params, &network_graph.read_only(), None,
5346 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5347 assert_eq!(err, "Can't find a route with no paths allowed.");
5348 } else { panic!(); }
5352 // Attempt to route while setting max_path_count to 3 results in a failure.
5353 // This is the case because the minimal_value_contribution_msat would require each path
5354 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5355 let fail_payment_params = payment_params.clone().with_max_path_count(3);
5356 let route_params = RouteParameters::from_payment_params_and_value(
5357 fail_payment_params, 250_000);
5358 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5359 &our_id, &route_params, &network_graph.read_only(), None,
5360 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5361 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5362 } else { panic!(); }
5366 // Now, attempt to route 250 sats (just a bit below the capacity).
5367 // Our algorithm should provide us with these 3 paths.
5368 let route_params = RouteParameters::from_payment_params_and_value(
5369 payment_params.clone(), 250_000);
5370 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5371 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5372 assert_eq!(route.paths.len(), 3);
5373 let mut total_amount_paid_msat = 0;
5374 for path in &route.paths {
5375 if let Some(bt) = &path.blinded_tail {
5376 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5378 assert_eq!(path.hops.len(), 2);
5379 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5381 total_amount_paid_msat += path.final_value_msat();
5383 assert_eq!(total_amount_paid_msat, 250_000);
5387 // Attempt to route an exact amount is also fine
5388 let route_params = RouteParameters::from_payment_params_and_value(
5389 payment_params.clone(), 290_000);
5390 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5391 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5392 assert_eq!(route.paths.len(), 3);
5393 let mut total_amount_paid_msat = 0;
5394 for path in &route.paths {
5395 if payment_params.payee.blinded_route_hints().len() != 0 {
5396 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5397 if let Some(bt) = &path.blinded_tail {
5398 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5399 if bt.hops.len() > 1 {
5400 assert_eq!(path.hops.last().unwrap().pubkey,
5401 payment_params.payee.blinded_route_hints().iter()
5402 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5403 .map(|(_, p)| p.introduction_node_id).unwrap());
5405 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5408 assert_eq!(path.hops.len(), 2);
5409 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5411 total_amount_paid_msat += path.final_value_msat();
5413 assert_eq!(total_amount_paid_msat, 290_000);
5418 fn long_mpp_route_test() {
5419 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5420 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5421 let scorer = ln_test_utils::TestScorer::new();
5422 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5423 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5424 let config = UserConfig::default();
5425 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5426 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5429 // We need a route consisting of 3 paths:
5430 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5431 // Note that these paths overlap (channels 5, 12, 13).
5432 // We will route 300 sats.
5433 // Each path will have 100 sats capacity, those channels which
5434 // are used twice will have 200 sats capacity.
5436 // Disable other potential paths.
5437 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5438 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5439 short_channel_id: 2,
5442 cltv_expiry_delta: 0,
5443 htlc_minimum_msat: 0,
5444 htlc_maximum_msat: 100_000,
5446 fee_proportional_millionths: 0,
5447 excess_data: Vec::new()
5449 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5450 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5451 short_channel_id: 7,
5454 cltv_expiry_delta: 0,
5455 htlc_minimum_msat: 0,
5456 htlc_maximum_msat: 100_000,
5458 fee_proportional_millionths: 0,
5459 excess_data: Vec::new()
5462 // Path via {node0, node2} is channels {1, 3, 5}.
5463 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5464 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5465 short_channel_id: 1,
5468 cltv_expiry_delta: 0,
5469 htlc_minimum_msat: 0,
5470 htlc_maximum_msat: 100_000,
5472 fee_proportional_millionths: 0,
5473 excess_data: Vec::new()
5475 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5476 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5477 short_channel_id: 3,
5480 cltv_expiry_delta: 0,
5481 htlc_minimum_msat: 0,
5482 htlc_maximum_msat: 100_000,
5484 fee_proportional_millionths: 0,
5485 excess_data: Vec::new()
5488 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5489 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5490 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5491 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5492 short_channel_id: 5,
5495 cltv_expiry_delta: 0,
5496 htlc_minimum_msat: 0,
5497 htlc_maximum_msat: 200_000,
5499 fee_proportional_millionths: 0,
5500 excess_data: Vec::new()
5503 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5504 // Add 100 sats to the capacities of {12, 13}, because these channels
5505 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5506 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5507 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5508 short_channel_id: 12,
5511 cltv_expiry_delta: 0,
5512 htlc_minimum_msat: 0,
5513 htlc_maximum_msat: 200_000,
5515 fee_proportional_millionths: 0,
5516 excess_data: Vec::new()
5518 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5519 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5520 short_channel_id: 13,
5523 cltv_expiry_delta: 0,
5524 htlc_minimum_msat: 0,
5525 htlc_maximum_msat: 200_000,
5527 fee_proportional_millionths: 0,
5528 excess_data: Vec::new()
5531 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5532 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5533 short_channel_id: 6,
5536 cltv_expiry_delta: 0,
5537 htlc_minimum_msat: 0,
5538 htlc_maximum_msat: 100_000,
5540 fee_proportional_millionths: 0,
5541 excess_data: Vec::new()
5543 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5544 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5545 short_channel_id: 11,
5548 cltv_expiry_delta: 0,
5549 htlc_minimum_msat: 0,
5550 htlc_maximum_msat: 100_000,
5552 fee_proportional_millionths: 0,
5553 excess_data: Vec::new()
5556 // Path via {node7, node2} is channels {12, 13, 5}.
5557 // We already limited them to 200 sats (they are used twice for 100 sats).
5558 // Nothing to do here.
5561 // Attempt to route more than available results in a failure.
5562 let route_params = RouteParameters::from_payment_params_and_value(
5563 payment_params.clone(), 350_000);
5564 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5565 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5566 &scorer, &Default::default(), &random_seed_bytes) {
5567 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5568 } else { panic!(); }
5572 // Now, attempt to route 300 sats (exact amount we can route).
5573 // Our algorithm should provide us with these 3 paths, 100 sats each.
5574 let route_params = RouteParameters::from_payment_params_and_value(
5575 payment_params, 300_000);
5576 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5577 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5578 assert_eq!(route.paths.len(), 3);
5580 let mut total_amount_paid_msat = 0;
5581 for path in &route.paths {
5582 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5583 total_amount_paid_msat += path.final_value_msat();
5585 assert_eq!(total_amount_paid_msat, 300_000);
5591 fn mpp_cheaper_route_test() {
5592 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5593 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5594 let scorer = ln_test_utils::TestScorer::new();
5595 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5596 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5597 let config = UserConfig::default();
5598 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5599 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5602 // This test checks that if we have two cheaper paths and one more expensive path,
5603 // so that liquidity-wise any 2 of 3 combination is sufficient,
5604 // two cheaper paths will be taken.
5605 // These paths have equal available liquidity.
5607 // We need a combination of 3 paths:
5608 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5609 // Note that these paths overlap (channels 5, 12, 13).
5610 // Each path will have 100 sats capacity, those channels which
5611 // are used twice will have 200 sats capacity.
5613 // Disable other potential paths.
5614 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5615 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5616 short_channel_id: 2,
5619 cltv_expiry_delta: 0,
5620 htlc_minimum_msat: 0,
5621 htlc_maximum_msat: 100_000,
5623 fee_proportional_millionths: 0,
5624 excess_data: Vec::new()
5626 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5627 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5628 short_channel_id: 7,
5631 cltv_expiry_delta: 0,
5632 htlc_minimum_msat: 0,
5633 htlc_maximum_msat: 100_000,
5635 fee_proportional_millionths: 0,
5636 excess_data: Vec::new()
5639 // Path via {node0, node2} is channels {1, 3, 5}.
5640 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5641 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5642 short_channel_id: 1,
5645 cltv_expiry_delta: 0,
5646 htlc_minimum_msat: 0,
5647 htlc_maximum_msat: 100_000,
5649 fee_proportional_millionths: 0,
5650 excess_data: Vec::new()
5652 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5653 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5654 short_channel_id: 3,
5657 cltv_expiry_delta: 0,
5658 htlc_minimum_msat: 0,
5659 htlc_maximum_msat: 100_000,
5661 fee_proportional_millionths: 0,
5662 excess_data: Vec::new()
5665 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5666 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5667 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5668 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5669 short_channel_id: 5,
5672 cltv_expiry_delta: 0,
5673 htlc_minimum_msat: 0,
5674 htlc_maximum_msat: 200_000,
5676 fee_proportional_millionths: 0,
5677 excess_data: Vec::new()
5680 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5681 // Add 100 sats to the capacities of {12, 13}, because these channels
5682 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5683 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5684 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5685 short_channel_id: 12,
5688 cltv_expiry_delta: 0,
5689 htlc_minimum_msat: 0,
5690 htlc_maximum_msat: 200_000,
5692 fee_proportional_millionths: 0,
5693 excess_data: Vec::new()
5695 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5696 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5697 short_channel_id: 13,
5700 cltv_expiry_delta: 0,
5701 htlc_minimum_msat: 0,
5702 htlc_maximum_msat: 200_000,
5704 fee_proportional_millionths: 0,
5705 excess_data: Vec::new()
5708 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5709 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5710 short_channel_id: 6,
5713 cltv_expiry_delta: 0,
5714 htlc_minimum_msat: 0,
5715 htlc_maximum_msat: 100_000,
5716 fee_base_msat: 1_000,
5717 fee_proportional_millionths: 0,
5718 excess_data: Vec::new()
5720 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5721 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5722 short_channel_id: 11,
5725 cltv_expiry_delta: 0,
5726 htlc_minimum_msat: 0,
5727 htlc_maximum_msat: 100_000,
5729 fee_proportional_millionths: 0,
5730 excess_data: Vec::new()
5733 // Path via {node7, node2} is channels {12, 13, 5}.
5734 // We already limited them to 200 sats (they are used twice for 100 sats).
5735 // Nothing to do here.
5738 // Now, attempt to route 180 sats.
5739 // Our algorithm should provide us with these 2 paths.
5740 let route_params = RouteParameters::from_payment_params_and_value(
5741 payment_params, 180_000);
5742 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5743 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5744 assert_eq!(route.paths.len(), 2);
5746 let mut total_value_transferred_msat = 0;
5747 let mut total_paid_msat = 0;
5748 for path in &route.paths {
5749 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5750 total_value_transferred_msat += path.final_value_msat();
5751 for hop in &path.hops {
5752 total_paid_msat += hop.fee_msat;
5755 // If we paid fee, this would be higher.
5756 assert_eq!(total_value_transferred_msat, 180_000);
5757 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5758 assert_eq!(total_fees_paid, 0);
5763 fn fees_on_mpp_route_test() {
5764 // This test makes sure that MPP algorithm properly takes into account
5765 // fees charged on the channels, by making the fees impactful:
5766 // if the fee is not properly accounted for, the behavior is different.
5767 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5768 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5769 let scorer = ln_test_utils::TestScorer::new();
5770 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5771 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5772 let config = UserConfig::default();
5773 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5774 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5777 // We need a route consisting of 2 paths:
5778 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5779 // We will route 200 sats, Each path will have 100 sats capacity.
5781 // This test is not particularly stable: e.g.,
5782 // there's a way to route via {node0, node2, node4}.
5783 // It works while pathfinding is deterministic, but can be broken otherwise.
5784 // It's fine to ignore this concern for now.
5786 // Disable other potential paths.
5787 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5788 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5789 short_channel_id: 2,
5792 cltv_expiry_delta: 0,
5793 htlc_minimum_msat: 0,
5794 htlc_maximum_msat: 100_000,
5796 fee_proportional_millionths: 0,
5797 excess_data: Vec::new()
5800 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5801 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5802 short_channel_id: 7,
5805 cltv_expiry_delta: 0,
5806 htlc_minimum_msat: 0,
5807 htlc_maximum_msat: 100_000,
5809 fee_proportional_millionths: 0,
5810 excess_data: Vec::new()
5813 // Path via {node0, node2} is channels {1, 3, 5}.
5814 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5815 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5816 short_channel_id: 1,
5819 cltv_expiry_delta: 0,
5820 htlc_minimum_msat: 0,
5821 htlc_maximum_msat: 100_000,
5823 fee_proportional_millionths: 0,
5824 excess_data: Vec::new()
5826 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5827 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5828 short_channel_id: 3,
5831 cltv_expiry_delta: 0,
5832 htlc_minimum_msat: 0,
5833 htlc_maximum_msat: 100_000,
5835 fee_proportional_millionths: 0,
5836 excess_data: Vec::new()
5839 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5840 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5841 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5842 short_channel_id: 5,
5845 cltv_expiry_delta: 0,
5846 htlc_minimum_msat: 0,
5847 htlc_maximum_msat: 100_000,
5849 fee_proportional_millionths: 0,
5850 excess_data: Vec::new()
5853 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5854 // All channels should be 100 sats capacity. But for the fee experiment,
5855 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5856 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5857 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5858 // so no matter how large are other channels,
5859 // the whole path will be limited by 100 sats with just these 2 conditions:
5860 // - channel 12 capacity is 250 sats
5861 // - fee for channel 6 is 150 sats
5862 // Let's test this by enforcing these 2 conditions and removing other limits.
5863 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5864 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5865 short_channel_id: 12,
5868 cltv_expiry_delta: 0,
5869 htlc_minimum_msat: 0,
5870 htlc_maximum_msat: 250_000,
5872 fee_proportional_millionths: 0,
5873 excess_data: Vec::new()
5875 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5876 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5877 short_channel_id: 13,
5880 cltv_expiry_delta: 0,
5881 htlc_minimum_msat: 0,
5882 htlc_maximum_msat: MAX_VALUE_MSAT,
5884 fee_proportional_millionths: 0,
5885 excess_data: Vec::new()
5888 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5889 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5890 short_channel_id: 6,
5893 cltv_expiry_delta: 0,
5894 htlc_minimum_msat: 0,
5895 htlc_maximum_msat: MAX_VALUE_MSAT,
5896 fee_base_msat: 150_000,
5897 fee_proportional_millionths: 0,
5898 excess_data: Vec::new()
5900 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5901 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5902 short_channel_id: 11,
5905 cltv_expiry_delta: 0,
5906 htlc_minimum_msat: 0,
5907 htlc_maximum_msat: MAX_VALUE_MSAT,
5909 fee_proportional_millionths: 0,
5910 excess_data: Vec::new()
5914 // Attempt to route more than available results in a failure.
5915 let route_params = RouteParameters::from_payment_params_and_value(
5916 payment_params.clone(), 210_000);
5917 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5918 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5919 &scorer, &Default::default(), &random_seed_bytes) {
5920 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5921 } else { panic!(); }
5925 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5926 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5927 max_total_routing_fee_msat: Some(149_999) };
5928 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5929 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5930 &scorer, &Default::default(), &random_seed_bytes) {
5931 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5932 } else { panic!(); }
5936 // Now, attempt to route 200 sats (exact amount we can route).
5937 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5938 max_total_routing_fee_msat: Some(150_000) };
5939 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5940 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5941 assert_eq!(route.paths.len(), 2);
5943 let mut total_amount_paid_msat = 0;
5944 for path in &route.paths {
5945 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5946 total_amount_paid_msat += path.final_value_msat();
5948 assert_eq!(total_amount_paid_msat, 200_000);
5949 assert_eq!(route.get_total_fees(), 150_000);
5954 fn mpp_with_last_hops() {
5955 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5956 // via a single last-hop route hint, we'd fail to route if we first collected routes
5957 // totaling close but not quite enough to fund the full payment.
5959 // This was because we considered last-hop hints to have exactly the sought payment amount
5960 // instead of the amount we were trying to collect, needlessly limiting our path searching
5961 // at the very first hop.
5963 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5964 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5965 // to only have the remaining to-collect amount in available liquidity.
5967 // This bug appeared in production in some specific channel configurations.
5968 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5969 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5970 let scorer = ln_test_utils::TestScorer::new();
5971 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5972 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5973 let config = UserConfig::default();
5974 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
5975 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
5976 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5977 src_node_id: nodes[2],
5978 short_channel_id: 42,
5979 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5980 cltv_expiry_delta: 42,
5981 htlc_minimum_msat: None,
5982 htlc_maximum_msat: None,
5983 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5985 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5986 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5987 // would first use the no-fee route and then fail to find a path along the second route as
5988 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5989 // under 5% of our payment amount.
5990 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5991 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5992 short_channel_id: 1,
5995 cltv_expiry_delta: (5 << 4) | 5,
5996 htlc_minimum_msat: 0,
5997 htlc_maximum_msat: 99_000,
5998 fee_base_msat: u32::max_value(),
5999 fee_proportional_millionths: u32::max_value(),
6000 excess_data: Vec::new()
6002 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6003 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6004 short_channel_id: 2,
6007 cltv_expiry_delta: (5 << 4) | 3,
6008 htlc_minimum_msat: 0,
6009 htlc_maximum_msat: 99_000,
6010 fee_base_msat: u32::max_value(),
6011 fee_proportional_millionths: u32::max_value(),
6012 excess_data: Vec::new()
6014 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6015 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6016 short_channel_id: 4,
6019 cltv_expiry_delta: (4 << 4) | 1,
6020 htlc_minimum_msat: 0,
6021 htlc_maximum_msat: MAX_VALUE_MSAT,
6023 fee_proportional_millionths: 0,
6024 excess_data: Vec::new()
6026 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6027 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6028 short_channel_id: 13,
6030 flags: 0|2, // Channel disabled
6031 cltv_expiry_delta: (13 << 4) | 1,
6032 htlc_minimum_msat: 0,
6033 htlc_maximum_msat: MAX_VALUE_MSAT,
6035 fee_proportional_millionths: 2000000,
6036 excess_data: Vec::new()
6039 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
6041 let route_params = RouteParameters::from_payment_params_and_value(
6042 payment_params, 100_000);
6043 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6044 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6045 assert_eq!(route.paths.len(), 2);
6046 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
6047 // Paths are manually ordered ordered by SCID, so:
6048 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
6049 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
6050 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
6051 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
6052 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
6053 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
6054 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
6055 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
6056 assert_eq!(route.get_total_fees(), 1);
6057 assert_eq!(route.get_total_amount(), 100_000);
6061 fn drop_lowest_channel_mpp_route_test() {
6062 // This test checks that low-capacity channel is dropped when after
6063 // path finding we realize that we found more capacity than we need.
6064 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6065 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6066 let scorer = ln_test_utils::TestScorer::new();
6067 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6068 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6069 let config = UserConfig::default();
6070 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6071 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6073 .with_max_channel_saturation_power_of_half(0);
6075 // We need a route consisting of 3 paths:
6076 // From our node to node2 via node0, node7, node1 (three paths one hop each).
6078 // The first and the second paths should be sufficient, but the third should be
6079 // cheaper, so that we select it but drop later.
6081 // First, we set limits on these (previously unlimited) channels.
6082 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
6084 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
6085 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6086 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6087 short_channel_id: 1,
6090 cltv_expiry_delta: 0,
6091 htlc_minimum_msat: 0,
6092 htlc_maximum_msat: 100_000,
6094 fee_proportional_millionths: 0,
6095 excess_data: Vec::new()
6097 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6098 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6099 short_channel_id: 3,
6102 cltv_expiry_delta: 0,
6103 htlc_minimum_msat: 0,
6104 htlc_maximum_msat: 50_000,
6106 fee_proportional_millionths: 0,
6107 excess_data: Vec::new()
6110 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
6111 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6112 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6113 short_channel_id: 12,
6116 cltv_expiry_delta: 0,
6117 htlc_minimum_msat: 0,
6118 htlc_maximum_msat: 60_000,
6120 fee_proportional_millionths: 0,
6121 excess_data: Vec::new()
6123 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6124 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6125 short_channel_id: 13,
6128 cltv_expiry_delta: 0,
6129 htlc_minimum_msat: 0,
6130 htlc_maximum_msat: 60_000,
6132 fee_proportional_millionths: 0,
6133 excess_data: Vec::new()
6136 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
6137 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6138 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6139 short_channel_id: 2,
6142 cltv_expiry_delta: 0,
6143 htlc_minimum_msat: 0,
6144 htlc_maximum_msat: 20_000,
6146 fee_proportional_millionths: 0,
6147 excess_data: Vec::new()
6149 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6150 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6151 short_channel_id: 4,
6154 cltv_expiry_delta: 0,
6155 htlc_minimum_msat: 0,
6156 htlc_maximum_msat: 20_000,
6158 fee_proportional_millionths: 0,
6159 excess_data: Vec::new()
6163 // Attempt to route more than available results in a failure.
6164 let route_params = RouteParameters::from_payment_params_and_value(
6165 payment_params.clone(), 150_000);
6166 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6167 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6168 &scorer, &Default::default(), &random_seed_bytes) {
6169 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6170 } else { panic!(); }
6174 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
6175 // Our algorithm should provide us with these 3 paths.
6176 let route_params = RouteParameters::from_payment_params_and_value(
6177 payment_params.clone(), 125_000);
6178 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6179 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6180 assert_eq!(route.paths.len(), 3);
6181 let mut total_amount_paid_msat = 0;
6182 for path in &route.paths {
6183 assert_eq!(path.hops.len(), 2);
6184 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6185 total_amount_paid_msat += path.final_value_msat();
6187 assert_eq!(total_amount_paid_msat, 125_000);
6191 // Attempt to route without the last small cheap channel
6192 let route_params = RouteParameters::from_payment_params_and_value(
6193 payment_params, 90_000);
6194 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6195 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6196 assert_eq!(route.paths.len(), 2);
6197 let mut total_amount_paid_msat = 0;
6198 for path in &route.paths {
6199 assert_eq!(path.hops.len(), 2);
6200 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6201 total_amount_paid_msat += path.final_value_msat();
6203 assert_eq!(total_amount_paid_msat, 90_000);
6208 fn min_criteria_consistency() {
6209 // Test that we don't use an inconsistent metric between updating and walking nodes during
6210 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
6211 // was updated with a different criterion from the heap sorting, resulting in loops in
6212 // calculated paths. We test for that specific case here.
6214 // We construct a network that looks like this:
6216 // node2 -1(3)2- node3
6220 // node1 -1(5)2- node4 -1(1)2- node6
6226 // We create a loop on the side of our real path - our destination is node 6, with a
6227 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
6228 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
6229 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
6230 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
6231 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
6232 // "previous hop" being set to node 3, creating a loop in the path.
6233 let secp_ctx = Secp256k1::new();
6234 let logger = Arc::new(ln_test_utils::TestLogger::new());
6235 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6236 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
6237 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6238 let scorer = ln_test_utils::TestScorer::new();
6239 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6240 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6241 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
6243 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
6244 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6245 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6246 short_channel_id: 6,
6249 cltv_expiry_delta: (6 << 4) | 0,
6250 htlc_minimum_msat: 0,
6251 htlc_maximum_msat: MAX_VALUE_MSAT,
6253 fee_proportional_millionths: 0,
6254 excess_data: Vec::new()
6256 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
6258 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6259 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6260 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6261 short_channel_id: 5,
6264 cltv_expiry_delta: (5 << 4) | 0,
6265 htlc_minimum_msat: 0,
6266 htlc_maximum_msat: MAX_VALUE_MSAT,
6268 fee_proportional_millionths: 0,
6269 excess_data: Vec::new()
6271 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
6273 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
6274 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6275 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6276 short_channel_id: 4,
6279 cltv_expiry_delta: (4 << 4) | 0,
6280 htlc_minimum_msat: 0,
6281 htlc_maximum_msat: MAX_VALUE_MSAT,
6283 fee_proportional_millionths: 0,
6284 excess_data: Vec::new()
6286 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6288 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6289 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
6290 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6291 short_channel_id: 3,
6294 cltv_expiry_delta: (3 << 4) | 0,
6295 htlc_minimum_msat: 0,
6296 htlc_maximum_msat: MAX_VALUE_MSAT,
6298 fee_proportional_millionths: 0,
6299 excess_data: Vec::new()
6301 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6303 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6304 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
6305 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6306 short_channel_id: 2,
6309 cltv_expiry_delta: (2 << 4) | 0,
6310 htlc_minimum_msat: 0,
6311 htlc_maximum_msat: MAX_VALUE_MSAT,
6313 fee_proportional_millionths: 0,
6314 excess_data: Vec::new()
6317 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6318 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6319 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6320 short_channel_id: 1,
6323 cltv_expiry_delta: (1 << 4) | 0,
6324 htlc_minimum_msat: 100,
6325 htlc_maximum_msat: MAX_VALUE_MSAT,
6327 fee_proportional_millionths: 0,
6328 excess_data: Vec::new()
6330 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6333 // Now ensure the route flows simply over nodes 1 and 4 to 6.
6334 let route_params = RouteParameters::from_payment_params_and_value(
6335 payment_params, 10_000);
6336 let route = get_route(&our_id, &route_params, &network.read_only(), None,
6337 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6338 assert_eq!(route.paths.len(), 1);
6339 assert_eq!(route.paths[0].hops.len(), 3);
6341 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6342 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6343 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6344 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6345 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6346 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6348 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6349 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6350 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6351 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6352 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6353 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6355 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6356 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6357 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6358 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6359 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6360 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6366 fn exact_fee_liquidity_limit() {
6367 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6368 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6369 // we calculated fees on a higher value, resulting in us ignoring such paths.
6370 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6371 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6372 let scorer = ln_test_utils::TestScorer::new();
6373 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6374 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6375 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6377 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6379 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6380 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6381 short_channel_id: 2,
6384 cltv_expiry_delta: 0,
6385 htlc_minimum_msat: 0,
6386 htlc_maximum_msat: 85_000,
6388 fee_proportional_millionths: 0,
6389 excess_data: Vec::new()
6392 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6393 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6394 short_channel_id: 12,
6397 cltv_expiry_delta: (4 << 4) | 1,
6398 htlc_minimum_msat: 0,
6399 htlc_maximum_msat: 270_000,
6401 fee_proportional_millionths: 1000000,
6402 excess_data: Vec::new()
6406 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6407 // 200% fee charged channel 13 in the 1-to-2 direction.
6408 let mut route_params = RouteParameters::from_payment_params_and_value(
6409 payment_params, 90_000);
6410 route_params.max_total_routing_fee_msat = Some(90_000*2);
6411 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6412 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6413 assert_eq!(route.paths.len(), 1);
6414 assert_eq!(route.paths[0].hops.len(), 2);
6416 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6417 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6418 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6419 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6420 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6421 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6423 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6424 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6425 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6426 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6427 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6428 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6433 fn htlc_max_reduction_below_min() {
6434 // Test that if, while walking the graph, we reduce the value being sent to meet an
6435 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6436 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6437 // resulting in us thinking there is no possible path, even if other paths exist.
6438 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6439 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6440 let scorer = ln_test_utils::TestScorer::new();
6441 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6442 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6443 let config = UserConfig::default();
6444 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6445 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6448 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6449 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6450 // then try to send 90_000.
6451 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6452 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6453 short_channel_id: 2,
6456 cltv_expiry_delta: 0,
6457 htlc_minimum_msat: 0,
6458 htlc_maximum_msat: 80_000,
6460 fee_proportional_millionths: 0,
6461 excess_data: Vec::new()
6463 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6464 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6465 short_channel_id: 4,
6468 cltv_expiry_delta: (4 << 4) | 1,
6469 htlc_minimum_msat: 90_000,
6470 htlc_maximum_msat: MAX_VALUE_MSAT,
6472 fee_proportional_millionths: 0,
6473 excess_data: Vec::new()
6477 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6478 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6479 // expensive) channels 12-13 path.
6480 let mut route_params = RouteParameters::from_payment_params_and_value(
6481 payment_params, 90_000);
6482 route_params.max_total_routing_fee_msat = Some(90_000*2);
6483 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6484 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6485 assert_eq!(route.paths.len(), 1);
6486 assert_eq!(route.paths[0].hops.len(), 2);
6488 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6489 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6490 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6491 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6492 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6493 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6495 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6496 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6497 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6498 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6499 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6500 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6505 fn multiple_direct_first_hops() {
6506 // Previously we'd only ever considered one first hop path per counterparty.
6507 // However, as we don't restrict users to one channel per peer, we really need to support
6508 // looking at all first hop paths.
6509 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6510 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6511 // route over multiple channels with the same first hop.
6512 let secp_ctx = Secp256k1::new();
6513 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6514 let logger = Arc::new(ln_test_utils::TestLogger::new());
6515 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6516 let scorer = ln_test_utils::TestScorer::new();
6517 let config = UserConfig::default();
6518 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6519 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6521 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6522 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6525 let route_params = RouteParameters::from_payment_params_and_value(
6526 payment_params.clone(), 100_000);
6527 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6528 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6529 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6530 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6531 assert_eq!(route.paths.len(), 1);
6532 assert_eq!(route.paths[0].hops.len(), 1);
6534 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6535 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6536 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6539 let route_params = RouteParameters::from_payment_params_and_value(
6540 payment_params.clone(), 100_000);
6541 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6542 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6543 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6544 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6545 assert_eq!(route.paths.len(), 2);
6546 assert_eq!(route.paths[0].hops.len(), 1);
6547 assert_eq!(route.paths[1].hops.len(), 1);
6549 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6550 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6552 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6553 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6555 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6556 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6560 // If we have a bunch of outbound channels to the same node, where most are not
6561 // sufficient to pay the full payment, but one is, we should default to just using the
6562 // one single channel that has sufficient balance, avoiding MPP.
6564 // If we have several options above the 3xpayment value threshold, we should pick the
6565 // smallest of them, avoiding further fragmenting our available outbound balance to
6567 let route_params = RouteParameters::from_payment_params_and_value(
6568 payment_params, 100_000);
6569 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6570 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6571 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6572 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6573 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6574 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6575 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6576 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6577 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6578 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6579 assert_eq!(route.paths.len(), 1);
6580 assert_eq!(route.paths[0].hops.len(), 1);
6582 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6583 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6584 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6589 fn prefers_shorter_route_with_higher_fees() {
6590 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6591 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6592 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6594 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6595 let scorer = ln_test_utils::TestScorer::new();
6596 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6597 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6598 let route_params = RouteParameters::from_payment_params_and_value(
6599 payment_params.clone(), 100);
6600 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6601 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6602 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6604 assert_eq!(route.get_total_fees(), 100);
6605 assert_eq!(route.get_total_amount(), 100);
6606 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6608 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6609 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6610 let scorer = FixedPenaltyScorer::with_penalty(100);
6611 let route_params = RouteParameters::from_payment_params_and_value(
6612 payment_params, 100);
6613 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6614 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6615 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6617 assert_eq!(route.get_total_fees(), 300);
6618 assert_eq!(route.get_total_amount(), 100);
6619 assert_eq!(path, vec![2, 4, 7, 10]);
6622 struct BadChannelScorer {
6623 short_channel_id: u64,
6627 impl Writeable for BadChannelScorer {
6628 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6630 impl ScoreLookUp for BadChannelScorer {
6631 type ScoreParams = ();
6632 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6633 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6637 struct BadNodeScorer {
6642 impl Writeable for BadNodeScorer {
6643 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6646 impl ScoreLookUp for BadNodeScorer {
6647 type ScoreParams = ();
6648 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6649 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6654 fn avoids_routing_through_bad_channels_and_nodes() {
6655 let (secp_ctx, network, _, _, logger) = build_graph();
6656 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6657 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6658 let network_graph = network.read_only();
6660 // A path to nodes[6] exists when no penalties are applied to any channel.
6661 let scorer = ln_test_utils::TestScorer::new();
6662 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6663 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6664 let route_params = RouteParameters::from_payment_params_and_value(
6665 payment_params, 100);
6666 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6667 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6668 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6670 assert_eq!(route.get_total_fees(), 100);
6671 assert_eq!(route.get_total_amount(), 100);
6672 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6674 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6675 let scorer = BadChannelScorer { short_channel_id: 6 };
6676 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6677 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6678 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6680 assert_eq!(route.get_total_fees(), 300);
6681 assert_eq!(route.get_total_amount(), 100);
6682 assert_eq!(path, vec![2, 4, 7, 10]);
6684 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6685 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6686 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6687 &scorer, &Default::default(), &random_seed_bytes) {
6688 Err(LightningError { err, .. } ) => {
6689 assert_eq!(err, "Failed to find a path to the given destination");
6691 Ok(_) => panic!("Expected error"),
6696 fn total_fees_single_path() {
6698 paths: vec![Path { hops: vec![
6700 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6701 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6702 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6705 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6706 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6707 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6710 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6711 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6712 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6714 ], blinded_tail: None }],
6718 assert_eq!(route.get_total_fees(), 250);
6719 assert_eq!(route.get_total_amount(), 225);
6723 fn total_fees_multi_path() {
6725 paths: vec![Path { hops: vec![
6727 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6728 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6729 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6732 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6733 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6734 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6736 ], blinded_tail: None }, Path { hops: vec![
6738 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6739 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6740 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6743 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6744 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6745 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6747 ], blinded_tail: None }],
6751 assert_eq!(route.get_total_fees(), 200);
6752 assert_eq!(route.get_total_amount(), 300);
6756 fn total_empty_route_no_panic() {
6757 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6758 // would both panic if the route was completely empty. We test to ensure they return 0
6759 // here, even though its somewhat nonsensical as a route.
6760 let route = Route { paths: Vec::new(), route_params: None };
6762 assert_eq!(route.get_total_fees(), 0);
6763 assert_eq!(route.get_total_amount(), 0);
6767 fn limits_total_cltv_delta() {
6768 let (secp_ctx, network, _, _, logger) = build_graph();
6769 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6770 let network_graph = network.read_only();
6772 let scorer = ln_test_utils::TestScorer::new();
6774 // Make sure that generally there is at least one route available
6775 let feasible_max_total_cltv_delta = 1008;
6776 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6777 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6778 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6779 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6780 let route_params = RouteParameters::from_payment_params_and_value(
6781 feasible_payment_params, 100);
6782 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6783 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6784 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6785 assert_ne!(path.len(), 0);
6787 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6788 let fail_max_total_cltv_delta = 23;
6789 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6790 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6791 let route_params = RouteParameters::from_payment_params_and_value(
6792 fail_payment_params, 100);
6793 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6794 &Default::default(), &random_seed_bytes)
6796 Err(LightningError { err, .. } ) => {
6797 assert_eq!(err, "Failed to find a path to the given destination");
6799 Ok(_) => panic!("Expected error"),
6804 fn avoids_recently_failed_paths() {
6805 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6806 // randomly inserting channels into it until we can't find a route anymore.
6807 let (secp_ctx, network, _, _, logger) = build_graph();
6808 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6809 let network_graph = network.read_only();
6811 let scorer = ln_test_utils::TestScorer::new();
6812 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6813 .with_max_path_count(1);
6814 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6815 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6817 // We should be able to find a route initially, and then after we fail a few random
6818 // channels eventually we won't be able to any longer.
6819 let route_params = RouteParameters::from_payment_params_and_value(
6820 payment_params.clone(), 100);
6821 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6822 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6824 let route_params = RouteParameters::from_payment_params_and_value(
6825 payment_params.clone(), 100);
6826 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6827 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6829 for chan in route.paths[0].hops.iter() {
6830 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6832 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6833 % route.paths[0].hops.len();
6834 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6840 fn limits_path_length() {
6841 let (secp_ctx, network, _, _, logger) = build_line_graph();
6842 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6843 let network_graph = network.read_only();
6845 let scorer = ln_test_utils::TestScorer::new();
6846 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6847 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6849 // First check we can actually create a long route on this graph.
6850 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6851 let route_params = RouteParameters::from_payment_params_and_value(
6852 feasible_payment_params, 100);
6853 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6854 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6855 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6856 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6858 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6859 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6860 let route_params = RouteParameters::from_payment_params_and_value(
6861 fail_payment_params, 100);
6862 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6863 &Default::default(), &random_seed_bytes)
6865 Err(LightningError { err, .. } ) => {
6866 assert_eq!(err, "Failed to find a path to the given destination");
6868 Ok(_) => panic!("Expected error"),
6873 fn adds_and_limits_cltv_offset() {
6874 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6875 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6877 let scorer = ln_test_utils::TestScorer::new();
6879 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6880 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6881 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6882 let route_params = RouteParameters::from_payment_params_and_value(
6883 payment_params.clone(), 100);
6884 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6885 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6886 assert_eq!(route.paths.len(), 1);
6888 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6890 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6891 let mut route_default = route.clone();
6892 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6893 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6894 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6895 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6896 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6898 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6899 let mut route_limited = route.clone();
6900 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6901 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6902 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6903 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6904 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6908 fn adds_plausible_cltv_offset() {
6909 let (secp_ctx, network, _, _, logger) = build_graph();
6910 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6911 let network_graph = network.read_only();
6912 let network_nodes = network_graph.nodes();
6913 let network_channels = network_graph.channels();
6914 let scorer = ln_test_utils::TestScorer::new();
6915 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6916 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6917 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6919 let route_params = RouteParameters::from_payment_params_and_value(
6920 payment_params.clone(), 100);
6921 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6922 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6923 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6925 let mut path_plausibility = vec![];
6927 for p in route.paths {
6928 // 1. Select random observation point
6929 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6930 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6932 prng.process_in_place(&mut random_bytes);
6933 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6934 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6936 // 2. Calculate what CLTV expiry delta we would observe there
6937 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6939 // 3. Starting from the observation point, find candidate paths
6940 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6941 candidates.push_back((observation_point, vec![]));
6943 let mut found_plausible_candidate = false;
6945 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6946 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6947 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6948 found_plausible_candidate = true;
6949 break 'candidate_loop;
6953 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6954 for channel_id in &cur_node.channels {
6955 if let Some(channel_info) = network_channels.get(&channel_id) {
6956 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6957 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6958 if cur_path_cltv_deltas.iter().sum::<u32>()
6959 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6960 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6961 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6962 candidates.push_back((*next_id, new_path_cltv_deltas));
6970 path_plausibility.push(found_plausible_candidate);
6972 assert!(path_plausibility.iter().all(|x| *x));
6976 fn builds_correct_path_from_hops() {
6977 let (secp_ctx, network, _, _, logger) = build_graph();
6978 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6979 let network_graph = network.read_only();
6981 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6982 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6984 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6985 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6986 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6987 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6988 Arc::clone(&logger), &random_seed_bytes).unwrap();
6989 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6990 assert_eq!(hops.len(), route.paths[0].hops.len());
6991 for (idx, hop_pubkey) in hops.iter().enumerate() {
6992 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6997 fn avoids_saturating_channels() {
6998 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6999 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
7000 let decay_params = ProbabilisticScoringDecayParameters::default();
7001 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
7003 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
7004 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
7005 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7006 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7007 short_channel_id: 4,
7010 cltv_expiry_delta: (4 << 4) | 1,
7011 htlc_minimum_msat: 0,
7012 htlc_maximum_msat: 250_000_000,
7014 fee_proportional_millionths: 0,
7015 excess_data: Vec::new()
7017 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
7018 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7019 short_channel_id: 13,
7022 cltv_expiry_delta: (13 << 4) | 1,
7023 htlc_minimum_msat: 0,
7024 htlc_maximum_msat: 250_000_000,
7026 fee_proportional_millionths: 0,
7027 excess_data: Vec::new()
7030 let config = UserConfig::default();
7031 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
7032 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7034 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7035 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7036 // 100,000 sats is less than the available liquidity on each channel, set above.
7037 let route_params = RouteParameters::from_payment_params_and_value(
7038 payment_params, 100_000_000);
7039 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
7040 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
7041 assert_eq!(route.paths.len(), 2);
7042 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
7043 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
7046 #[cfg(not(feature = "no-std"))]
7047 pub(super) fn random_init_seed() -> u64 {
7048 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
7049 use core::hash::{BuildHasher, Hasher};
7050 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
7051 println!("Using seed of {}", seed);
7056 #[cfg(not(feature = "no-std"))]
7057 fn generate_routes() {
7058 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7060 let logger = ln_test_utils::TestLogger::new();
7061 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7069 let params = ProbabilisticScoringFeeParameters::default();
7070 let features = super::Bolt11InvoiceFeatures::empty();
7072 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7076 #[cfg(not(feature = "no-std"))]
7077 fn generate_routes_mpp() {
7078 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7080 let logger = ln_test_utils::TestLogger::new();
7081 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7089 let params = ProbabilisticScoringFeeParameters::default();
7090 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7092 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7096 #[cfg(not(feature = "no-std"))]
7097 fn generate_large_mpp_routes() {
7098 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
7100 let logger = ln_test_utils::TestLogger::new();
7101 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7109 let params = ProbabilisticScoringFeeParameters::default();
7110 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &*graph, &logger);
7111 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7113 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
7117 fn honors_manual_penalties() {
7118 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
7119 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7121 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7122 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7124 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
7125 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
7127 // First check set manual penalties are returned by the scorer.
7128 let usage = ChannelUsage {
7130 inflight_htlc_msat: 0,
7131 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
7133 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
7134 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
7135 let network_graph = network_graph.read_only();
7136 let channels = network_graph.channels();
7137 let channel = channels.get(&5).unwrap();
7138 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
7139 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop(CandidatePublicHop {
7141 short_channel_id: 5,
7143 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
7145 // Then check we can get a normal route
7146 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
7147 let route_params = RouteParameters::from_payment_params_and_value(
7148 payment_params, 100);
7149 let route = get_route(&our_id, &route_params, &network_graph, None,
7150 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
7151 assert!(route.is_ok());
7153 // Then check that we can't get a route if we ban an intermediate node.
7154 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
7155 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7156 assert!(route.is_err());
7158 // Finally make sure we can route again, when we remove the ban.
7159 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
7160 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7161 assert!(route.is_ok());
7165 fn abide_by_route_hint_max_htlc() {
7166 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
7167 // params in the final route.
7168 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7169 let netgraph = network_graph.read_only();
7170 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7171 let scorer = ln_test_utils::TestScorer::new();
7172 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7173 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7174 let config = UserConfig::default();
7176 let max_htlc_msat = 50_000;
7177 let route_hint_1 = RouteHint(vec![RouteHintHop {
7178 src_node_id: nodes[2],
7179 short_channel_id: 42,
7182 proportional_millionths: 0,
7184 cltv_expiry_delta: 10,
7185 htlc_minimum_msat: None,
7186 htlc_maximum_msat: Some(max_htlc_msat),
7188 let dest_node_id = ln_test_utils::pubkey(42);
7189 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7190 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
7191 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7194 // Make sure we'll error if our route hints don't have enough liquidity according to their
7195 // htlc_maximum_msat.
7196 let mut route_params = RouteParameters::from_payment_params_and_value(
7197 payment_params, max_htlc_msat + 1);
7198 route_params.max_total_routing_fee_msat = None;
7199 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
7200 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
7203 assert_eq!(err, "Failed to find a sufficient route to the given destination");
7204 } else { panic!(); }
7206 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
7207 let mut route_hint_2 = route_hint_1.clone();
7208 route_hint_2.0[0].short_channel_id = 43;
7209 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7210 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7211 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7213 let mut route_params = RouteParameters::from_payment_params_and_value(
7214 payment_params, max_htlc_msat + 1);
7215 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
7216 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
7217 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7218 assert_eq!(route.paths.len(), 2);
7219 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7220 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7224 fn direct_channel_to_hints_with_max_htlc() {
7225 // Check that if we have a first hop channel peer that's connected to multiple provided route
7226 // hints, that we properly split the payment between the route hints if needed.
7227 let logger = Arc::new(ln_test_utils::TestLogger::new());
7228 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7229 let scorer = ln_test_utils::TestScorer::new();
7230 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7231 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7232 let config = UserConfig::default();
7234 let our_node_id = ln_test_utils::pubkey(42);
7235 let intermed_node_id = ln_test_utils::pubkey(43);
7236 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7238 let amt_msat = 900_000;
7239 let max_htlc_msat = 500_000;
7240 let route_hint_1 = RouteHint(vec![RouteHintHop {
7241 src_node_id: intermed_node_id,
7242 short_channel_id: 44,
7245 proportional_millionths: 0,
7247 cltv_expiry_delta: 10,
7248 htlc_minimum_msat: None,
7249 htlc_maximum_msat: Some(max_htlc_msat),
7251 src_node_id: intermed_node_id,
7252 short_channel_id: 45,
7255 proportional_millionths: 0,
7257 cltv_expiry_delta: 10,
7258 htlc_minimum_msat: None,
7259 // Check that later route hint max htlcs don't override earlier ones
7260 htlc_maximum_msat: Some(max_htlc_msat - 50),
7262 let mut route_hint_2 = route_hint_1.clone();
7263 route_hint_2.0[0].short_channel_id = 46;
7264 route_hint_2.0[1].short_channel_id = 47;
7265 let dest_node_id = ln_test_utils::pubkey(44);
7266 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7267 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7268 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7271 let route_params = RouteParameters::from_payment_params_and_value(
7272 payment_params, amt_msat);
7273 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7274 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7275 &Default::default(), &random_seed_bytes).unwrap();
7276 assert_eq!(route.paths.len(), 2);
7277 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7278 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7279 assert_eq!(route.get_total_amount(), amt_msat);
7281 // Re-run but with two first hop channels connected to the same route hint peers that must be
7283 let first_hops = vec![
7284 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7285 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7287 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7288 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7289 &Default::default(), &random_seed_bytes).unwrap();
7290 assert_eq!(route.paths.len(), 2);
7291 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7292 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7293 assert_eq!(route.get_total_amount(), amt_msat);
7295 // Make sure this works for blinded route hints.
7296 let blinded_path = BlindedPath {
7297 introduction_node_id: intermed_node_id,
7298 blinding_point: ln_test_utils::pubkey(42),
7300 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
7301 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
7304 let blinded_payinfo = BlindedPayInfo {
7306 fee_proportional_millionths: 0,
7307 htlc_minimum_msat: 1,
7308 htlc_maximum_msat: max_htlc_msat,
7309 cltv_expiry_delta: 10,
7310 features: BlindedHopFeatures::empty(),
7312 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7313 let payment_params = PaymentParameters::blinded(vec![
7314 (blinded_payinfo.clone(), blinded_path.clone()),
7315 (blinded_payinfo.clone(), blinded_path.clone())])
7316 .with_bolt12_features(bolt12_features).unwrap();
7317 let route_params = RouteParameters::from_payment_params_and_value(
7318 payment_params, amt_msat);
7319 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7320 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7321 &Default::default(), &random_seed_bytes).unwrap();
7322 assert_eq!(route.paths.len(), 2);
7323 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7324 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7325 assert_eq!(route.get_total_amount(), amt_msat);
7329 fn blinded_route_ser() {
7330 let blinded_path_1 = BlindedPath {
7331 introduction_node_id: ln_test_utils::pubkey(42),
7332 blinding_point: ln_test_utils::pubkey(43),
7334 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7335 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7338 let blinded_path_2 = BlindedPath {
7339 introduction_node_id: ln_test_utils::pubkey(46),
7340 blinding_point: ln_test_utils::pubkey(47),
7342 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7343 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7346 // (De)serialize a Route with 1 blinded path out of two total paths.
7347 let mut route = Route { paths: vec![Path {
7348 hops: vec![RouteHop {
7349 pubkey: ln_test_utils::pubkey(50),
7350 node_features: NodeFeatures::empty(),
7351 short_channel_id: 42,
7352 channel_features: ChannelFeatures::empty(),
7354 cltv_expiry_delta: 0,
7355 maybe_announced_channel: true,
7357 blinded_tail: Some(BlindedTail {
7358 hops: blinded_path_1.blinded_hops,
7359 blinding_point: blinded_path_1.blinding_point,
7360 excess_final_cltv_expiry_delta: 40,
7361 final_value_msat: 100,
7363 hops: vec![RouteHop {
7364 pubkey: ln_test_utils::pubkey(51),
7365 node_features: NodeFeatures::empty(),
7366 short_channel_id: 43,
7367 channel_features: ChannelFeatures::empty(),
7369 cltv_expiry_delta: 0,
7370 maybe_announced_channel: true,
7371 }], blinded_tail: None }],
7374 let encoded_route = route.encode();
7375 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7376 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7377 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7379 // (De)serialize a Route with two paths, each containing a blinded tail.
7380 route.paths[1].blinded_tail = Some(BlindedTail {
7381 hops: blinded_path_2.blinded_hops,
7382 blinding_point: blinded_path_2.blinding_point,
7383 excess_final_cltv_expiry_delta: 41,
7384 final_value_msat: 101,
7386 let encoded_route = route.encode();
7387 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7388 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7389 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7393 fn blinded_path_inflight_processing() {
7394 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7395 // account for the blinded tail's final amount_msat.
7396 let mut inflight_htlcs = InFlightHtlcs::new();
7397 let blinded_path = BlindedPath {
7398 introduction_node_id: ln_test_utils::pubkey(43),
7399 blinding_point: ln_test_utils::pubkey(48),
7400 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7403 hops: vec![RouteHop {
7404 pubkey: ln_test_utils::pubkey(42),
7405 node_features: NodeFeatures::empty(),
7406 short_channel_id: 42,
7407 channel_features: ChannelFeatures::empty(),
7409 cltv_expiry_delta: 0,
7410 maybe_announced_channel: false,
7413 pubkey: blinded_path.introduction_node_id,
7414 node_features: NodeFeatures::empty(),
7415 short_channel_id: 43,
7416 channel_features: ChannelFeatures::empty(),
7418 cltv_expiry_delta: 0,
7419 maybe_announced_channel: false,
7421 blinded_tail: Some(BlindedTail {
7422 hops: blinded_path.blinded_hops,
7423 blinding_point: blinded_path.blinding_point,
7424 excess_final_cltv_expiry_delta: 0,
7425 final_value_msat: 200,
7428 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7429 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7430 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7434 fn blinded_path_cltv_shadow_offset() {
7435 // Make sure we add a shadow offset when sending to blinded paths.
7436 let blinded_path = BlindedPath {
7437 introduction_node_id: ln_test_utils::pubkey(43),
7438 blinding_point: ln_test_utils::pubkey(44),
7440 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7441 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7444 let mut route = Route { paths: vec![Path {
7445 hops: vec![RouteHop {
7446 pubkey: ln_test_utils::pubkey(42),
7447 node_features: NodeFeatures::empty(),
7448 short_channel_id: 42,
7449 channel_features: ChannelFeatures::empty(),
7451 cltv_expiry_delta: 0,
7452 maybe_announced_channel: false,
7455 pubkey: blinded_path.introduction_node_id,
7456 node_features: NodeFeatures::empty(),
7457 short_channel_id: 43,
7458 channel_features: ChannelFeatures::empty(),
7460 cltv_expiry_delta: 0,
7461 maybe_announced_channel: false,
7464 blinded_tail: Some(BlindedTail {
7465 hops: blinded_path.blinded_hops,
7466 blinding_point: blinded_path.blinding_point,
7467 excess_final_cltv_expiry_delta: 0,
7468 final_value_msat: 200,
7470 }], route_params: None};
7472 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7473 let (_, network_graph, _, _, _) = build_line_graph();
7474 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7475 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7476 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7480 fn simple_blinded_route_hints() {
7481 do_simple_blinded_route_hints(1);
7482 do_simple_blinded_route_hints(2);
7483 do_simple_blinded_route_hints(3);
7486 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7487 // Check that we can generate a route to a blinded path with the expected hops.
7488 let (secp_ctx, network, _, _, logger) = build_graph();
7489 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7490 let network_graph = network.read_only();
7492 let scorer = ln_test_utils::TestScorer::new();
7493 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7494 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7496 let mut blinded_path = BlindedPath {
7497 introduction_node_id: nodes[2],
7498 blinding_point: ln_test_utils::pubkey(42),
7499 blinded_hops: Vec::with_capacity(num_blinded_hops),
7501 for i in 0..num_blinded_hops {
7502 blinded_path.blinded_hops.push(
7503 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7506 let blinded_payinfo = BlindedPayInfo {
7508 fee_proportional_millionths: 500,
7509 htlc_minimum_msat: 1000,
7510 htlc_maximum_msat: 100_000_000,
7511 cltv_expiry_delta: 15,
7512 features: BlindedHopFeatures::empty(),
7515 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7516 let route_params = RouteParameters::from_payment_params_and_value(
7517 payment_params, 1001);
7518 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7519 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7520 assert_eq!(route.paths.len(), 1);
7521 assert_eq!(route.paths[0].hops.len(), 2);
7523 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7524 assert_eq!(tail.hops, blinded_path.blinded_hops);
7525 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7526 assert_eq!(tail.final_value_msat, 1001);
7528 let final_hop = route.paths[0].hops.last().unwrap();
7529 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
7530 if tail.hops.len() > 1 {
7531 assert_eq!(final_hop.fee_msat,
7532 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7533 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7535 assert_eq!(final_hop.fee_msat, 0);
7536 assert_eq!(final_hop.cltv_expiry_delta, 0);
7541 fn blinded_path_routing_errors() {
7542 // Check that we can generate a route to a blinded path with the expected hops.
7543 let (secp_ctx, network, _, _, logger) = build_graph();
7544 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7545 let network_graph = network.read_only();
7547 let scorer = ln_test_utils::TestScorer::new();
7548 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7549 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7551 let mut invalid_blinded_path = BlindedPath {
7552 introduction_node_id: nodes[2],
7553 blinding_point: ln_test_utils::pubkey(42),
7555 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7558 let blinded_payinfo = BlindedPayInfo {
7560 fee_proportional_millionths: 500,
7561 htlc_minimum_msat: 1000,
7562 htlc_maximum_msat: 100_000_000,
7563 cltv_expiry_delta: 15,
7564 features: BlindedHopFeatures::empty(),
7567 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7568 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
7569 let payment_params = PaymentParameters::blinded(vec![
7570 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7571 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7572 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7573 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7574 &scorer, &Default::default(), &random_seed_bytes)
7576 Err(LightningError { err, .. }) => {
7577 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7579 _ => panic!("Expected error")
7582 invalid_blinded_path.introduction_node_id = our_id;
7583 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7584 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7585 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7586 &Default::default(), &random_seed_bytes)
7588 Err(LightningError { err, .. }) => {
7589 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7591 _ => panic!("Expected error")
7594 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
7595 invalid_blinded_path.blinded_hops.clear();
7596 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7597 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7598 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7599 &Default::default(), &random_seed_bytes)
7601 Err(LightningError { err, .. }) => {
7602 assert_eq!(err, "0-hop blinded path provided");
7604 _ => panic!("Expected error")
7609 fn matching_intro_node_paths_provided() {
7610 // Check that if multiple blinded paths with the same intro node are provided in payment
7611 // parameters, we'll return the correct paths in the resulting MPP route.
7612 let (secp_ctx, network, _, _, logger) = build_graph();
7613 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7614 let network_graph = network.read_only();
7616 let scorer = ln_test_utils::TestScorer::new();
7617 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7618 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7619 let config = UserConfig::default();
7621 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7622 let blinded_path_1 = BlindedPath {
7623 introduction_node_id: nodes[2],
7624 blinding_point: ln_test_utils::pubkey(42),
7626 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7627 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7630 let blinded_payinfo_1 = BlindedPayInfo {
7632 fee_proportional_millionths: 0,
7633 htlc_minimum_msat: 0,
7634 htlc_maximum_msat: 30_000,
7635 cltv_expiry_delta: 0,
7636 features: BlindedHopFeatures::empty(),
7639 let mut blinded_path_2 = blinded_path_1.clone();
7640 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7641 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7642 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7644 let blinded_hints = vec![
7645 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7646 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7648 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7649 .with_bolt12_features(bolt12_features).unwrap();
7651 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7652 route_params.max_total_routing_fee_msat = Some(100_000);
7653 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7654 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7655 assert_eq!(route.paths.len(), 2);
7656 let mut total_amount_paid_msat = 0;
7657 for path in route.paths.into_iter() {
7658 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7659 if let Some(bt) = &path.blinded_tail {
7660 assert_eq!(bt.blinding_point,
7661 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7662 .map(|(_, bp)| bp.blinding_point).unwrap());
7663 } else { panic!(); }
7664 total_amount_paid_msat += path.final_value_msat();
7666 assert_eq!(total_amount_paid_msat, 100_000);
7670 fn direct_to_intro_node() {
7671 // This previously caused a debug panic in the router when asserting
7672 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7673 // direct channels we failed to account for the fee charged for use of the blinded path.
7676 // node0 -1(1)2 - node1
7677 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7678 // doesn't account for the blinded path fee.
7680 let secp_ctx = Secp256k1::new();
7681 let logger = Arc::new(ln_test_utils::TestLogger::new());
7682 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7683 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7684 let scorer = ln_test_utils::TestScorer::new();
7685 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7686 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7688 let amt_msat = 10_000_000;
7689 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7690 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7691 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7692 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7693 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7694 short_channel_id: 1,
7697 cltv_expiry_delta: 42,
7698 htlc_minimum_msat: 1_000,
7699 htlc_maximum_msat: 10_000_000,
7701 fee_proportional_millionths: 0,
7702 excess_data: Vec::new()
7704 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7705 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7706 short_channel_id: 1,
7709 cltv_expiry_delta: 42,
7710 htlc_minimum_msat: 1_000,
7711 htlc_maximum_msat: 10_000_000,
7713 fee_proportional_millionths: 0,
7714 excess_data: Vec::new()
7716 let first_hops = vec![
7717 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7719 let blinded_path = BlindedPath {
7720 introduction_node_id: nodes[1],
7721 blinding_point: ln_test_utils::pubkey(42),
7723 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7724 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7727 let blinded_payinfo = BlindedPayInfo {
7728 fee_base_msat: 1000,
7729 fee_proportional_millionths: 0,
7730 htlc_minimum_msat: 1000,
7731 htlc_maximum_msat: MAX_VALUE_MSAT,
7732 cltv_expiry_delta: 0,
7733 features: BlindedHopFeatures::empty(),
7735 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7737 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7739 let netgraph = network_graph.read_only();
7740 let route_params = RouteParameters::from_payment_params_and_value(
7741 payment_params.clone(), amt_msat);
7742 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7743 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7744 &Default::default(), &random_seed_bytes) {
7745 assert_eq!(err, "Failed to find a path to the given destination");
7746 } else { panic!("Expected error") }
7748 // Sending an exact amount accounting for the blinded path fee works.
7749 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7750 let route_params = RouteParameters::from_payment_params_and_value(
7751 payment_params, amt_minus_blinded_path_fee);
7752 let route = get_route(&nodes[0], &route_params, &netgraph,
7753 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7754 &Default::default(), &random_seed_bytes).unwrap();
7755 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7756 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7760 fn direct_to_matching_intro_nodes() {
7761 // This previously caused us to enter `unreachable` code in the following situation:
7762 // 1. We add a route candidate for intro_node contributing a high amount
7763 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7764 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7765 // amount, and update our route candidate for intro_node for the lower amount
7766 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7767 // lower contribution amount, but fail (this was previously caused by failure to account for
7768 // blinded path fees when adding first_hop<>intro_node candidates)
7769 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7770 // candidate still thinks its path is contributing the original higher amount. This caused us
7771 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7773 let secp_ctx = Secp256k1::new();
7774 let logger = Arc::new(ln_test_utils::TestLogger::new());
7775 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7776 let scorer = ln_test_utils::TestScorer::new();
7777 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7778 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7779 let config = UserConfig::default();
7781 // Values are taken from the fuzz input that uncovered this panic.
7782 let amt_msat = 21_7020_5185_1403_2640;
7783 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7784 let first_hops = vec![
7785 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7786 18446744073709551615)];
7788 let blinded_path = BlindedPath {
7789 introduction_node_id: nodes[1],
7790 blinding_point: ln_test_utils::pubkey(42),
7792 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7793 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7796 let blinded_payinfo = BlindedPayInfo {
7797 fee_base_msat: 5046_2720,
7798 fee_proportional_millionths: 0,
7799 htlc_minimum_msat: 4503_5996_2737_0496,
7800 htlc_maximum_msat: 45_0359_9627_3704_9600,
7801 cltv_expiry_delta: 0,
7802 features: BlindedHopFeatures::empty(),
7804 let mut blinded_hints = vec![
7805 (blinded_payinfo.clone(), blinded_path.clone()),
7806 (blinded_payinfo.clone(), blinded_path.clone()),
7808 blinded_hints[1].0.fee_base_msat = 419_4304;
7809 blinded_hints[1].0.fee_proportional_millionths = 257;
7810 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7811 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7812 blinded_hints[1].0.cltv_expiry_delta = 0;
7814 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7815 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7816 .with_bolt12_features(bolt12_features).unwrap();
7818 let netgraph = network_graph.read_only();
7819 let route_params = RouteParameters::from_payment_params_and_value(
7820 payment_params, amt_msat);
7821 let route = get_route(&nodes[0], &route_params, &netgraph,
7822 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7823 &Default::default(), &random_seed_bytes).unwrap();
7824 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7825 assert_eq!(route.get_total_amount(), amt_msat);
7829 fn we_are_intro_node_candidate_hops() {
7830 // This previously led to a panic in the router because we'd generate a Path with only a
7831 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7832 // where the origin node is the intro node. We now fully disallow considering candidate hops
7833 // where the origin node is the intro node.
7834 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7835 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7836 let scorer = ln_test_utils::TestScorer::new();
7837 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7838 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7839 let config = UserConfig::default();
7841 // Values are taken from the fuzz input that uncovered this panic.
7842 let amt_msat = 21_7020_5185_1423_0019;
7844 let blinded_path = BlindedPath {
7845 introduction_node_id: our_id,
7846 blinding_point: ln_test_utils::pubkey(42),
7848 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7849 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7852 let blinded_payinfo = BlindedPayInfo {
7853 fee_base_msat: 5052_9027,
7854 fee_proportional_millionths: 0,
7855 htlc_minimum_msat: 21_7020_5185_1423_0019,
7856 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7857 cltv_expiry_delta: 0,
7858 features: BlindedHopFeatures::empty(),
7860 let mut blinded_hints = vec![
7861 (blinded_payinfo.clone(), blinded_path.clone()),
7862 (blinded_payinfo.clone(), blinded_path.clone()),
7864 blinded_hints[1].1.introduction_node_id = nodes[6];
7866 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7867 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7868 .with_bolt12_features(bolt12_features.clone()).unwrap();
7870 let netgraph = network_graph.read_only();
7871 let route_params = RouteParameters::from_payment_params_and_value(
7872 payment_params, amt_msat);
7873 if let Err(LightningError { err, .. }) = get_route(
7874 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7876 assert_eq!(err, "Failed to find a path to the given destination");
7881 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7882 // This previously led to a debug panic in the router because we'd find an invalid Path with
7883 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7884 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7885 // the payment, when it was intended to only include the final value of the payment.
7886 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7887 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7888 let scorer = ln_test_utils::TestScorer::new();
7889 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7890 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7891 let config = UserConfig::default();
7893 // Values are taken from the fuzz input that uncovered this panic.
7894 let amt_msat = 21_7020_5185_1423_0019;
7896 let blinded_path = BlindedPath {
7897 introduction_node_id: our_id,
7898 blinding_point: ln_test_utils::pubkey(42),
7900 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7901 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7904 let blinded_payinfo = BlindedPayInfo {
7905 fee_base_msat: 10_4425_1395,
7906 fee_proportional_millionths: 0,
7907 htlc_minimum_msat: 21_7301_9934_9094_0931,
7908 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7909 cltv_expiry_delta: 0,
7910 features: BlindedHopFeatures::empty(),
7912 let mut blinded_hints = vec![
7913 (blinded_payinfo.clone(), blinded_path.clone()),
7914 (blinded_payinfo.clone(), blinded_path.clone()),
7915 (blinded_payinfo.clone(), blinded_path.clone()),
7917 blinded_hints[1].0.fee_base_msat = 5052_9027;
7918 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7919 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7921 blinded_hints[2].1.introduction_node_id = nodes[6];
7923 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7924 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7925 .with_bolt12_features(bolt12_features.clone()).unwrap();
7927 let netgraph = network_graph.read_only();
7928 let route_params = RouteParameters::from_payment_params_and_value(
7929 payment_params, amt_msat);
7930 if let Err(LightningError { err, .. }) = get_route(
7931 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7933 assert_eq!(err, "Failed to find a path to the given destination");
7938 fn min_htlc_overpay_violates_max_htlc() {
7939 do_min_htlc_overpay_violates_max_htlc(true);
7940 do_min_htlc_overpay_violates_max_htlc(false);
7942 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7943 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7944 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7945 // to `targets` and build an invalid path with it, and subsquently hit a debug panic asserting
7946 // that the used liquidity for a hop was less than its available liquidity limit.
7947 let secp_ctx = Secp256k1::new();
7948 let logger = Arc::new(ln_test_utils::TestLogger::new());
7949 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7950 let scorer = ln_test_utils::TestScorer::new();
7951 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7952 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7953 let config = UserConfig::default();
7955 // Values are taken from the fuzz input that uncovered this panic.
7956 let amt_msat = 7_4009_8048;
7957 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7958 let first_hop_outbound_capacity = 2_7345_2000;
7959 let first_hops = vec![get_channel_details(
7960 Some(200), nodes[0], channelmanager::provided_init_features(&config),
7961 first_hop_outbound_capacity
7964 let base_fee = 1_6778_3453;
7965 let htlc_min = 2_5165_8240;
7966 let payment_params = if blinded_payee {
7967 let blinded_path = BlindedPath {
7968 introduction_node_id: nodes[0],
7969 blinding_point: ln_test_utils::pubkey(42),
7971 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7972 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7975 let blinded_payinfo = BlindedPayInfo {
7976 fee_base_msat: base_fee,
7977 fee_proportional_millionths: 0,
7978 htlc_minimum_msat: htlc_min,
7979 htlc_maximum_msat: htlc_min * 1000,
7980 cltv_expiry_delta: 0,
7981 features: BlindedHopFeatures::empty(),
7983 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7984 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
7985 .with_bolt12_features(bolt12_features.clone()).unwrap()
7987 let route_hint = RouteHint(vec![RouteHintHop {
7988 src_node_id: nodes[0],
7989 short_channel_id: 42,
7991 base_msat: base_fee,
7992 proportional_millionths: 0,
7994 cltv_expiry_delta: 10,
7995 htlc_minimum_msat: Some(htlc_min),
7996 htlc_maximum_msat: None,
7999 PaymentParameters::from_node_id(nodes[1], 42)
8000 .with_route_hints(vec![route_hint]).unwrap()
8001 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8004 let netgraph = network_graph.read_only();
8005 let route_params = RouteParameters::from_payment_params_and_value(
8006 payment_params, amt_msat);
8007 if let Err(LightningError { err, .. }) = get_route(
8008 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8009 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8011 assert_eq!(err, "Failed to find a path to the given destination");
8016 fn previously_used_liquidity_violates_max_htlc() {
8017 do_previously_used_liquidity_violates_max_htlc(true);
8018 do_previously_used_liquidity_violates_max_htlc(false);
8021 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
8022 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
8023 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
8024 // candidate. In this case, the candidate does not have enough due to a previous path taking up
8025 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
8026 // asserting that the used liquidity for a hop was less than its available liquidity limit.
8027 let secp_ctx = Secp256k1::new();
8028 let logger = Arc::new(ln_test_utils::TestLogger::new());
8029 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8030 let scorer = ln_test_utils::TestScorer::new();
8031 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8032 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8033 let config = UserConfig::default();
8035 // Values are taken from the fuzz input that uncovered this panic.
8036 let amt_msat = 52_4288;
8037 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8038 let first_hops = vec![get_channel_details(
8039 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
8040 ), get_channel_details(
8041 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
8044 let base_fees = [0, 425_9840, 0, 0];
8045 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
8046 let payment_params = if blinded_payee {
8047 let blinded_path = BlindedPath {
8048 introduction_node_id: nodes[0],
8049 blinding_point: ln_test_utils::pubkey(42),
8051 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8052 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8055 let mut blinded_hints = Vec::new();
8056 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
8057 blinded_hints.push((BlindedPayInfo {
8058 fee_base_msat: *base_fee,
8059 fee_proportional_millionths: 0,
8060 htlc_minimum_msat: *htlc_min,
8061 htlc_maximum_msat: htlc_min * 100,
8062 cltv_expiry_delta: 10,
8063 features: BlindedHopFeatures::empty(),
8064 }, blinded_path.clone()));
8066 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8067 PaymentParameters::blinded(blinded_hints.clone())
8068 .with_bolt12_features(bolt12_features.clone()).unwrap()
8070 let mut route_hints = Vec::new();
8071 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
8072 route_hints.push(RouteHint(vec![RouteHintHop {
8073 src_node_id: nodes[0],
8074 short_channel_id: 42 + idx as u64,
8076 base_msat: *base_fee,
8077 proportional_millionths: 0,
8079 cltv_expiry_delta: 10,
8080 htlc_minimum_msat: Some(*htlc_min),
8081 htlc_maximum_msat: Some(htlc_min * 100),
8084 PaymentParameters::from_node_id(nodes[1], 42)
8085 .with_route_hints(route_hints).unwrap()
8086 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8089 let netgraph = network_graph.read_only();
8090 let route_params = RouteParameters::from_payment_params_and_value(
8091 payment_params, amt_msat);
8093 let route = get_route(
8094 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8095 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8097 assert_eq!(route.paths.len(), 1);
8098 assert_eq!(route.get_total_amount(), amt_msat);
8102 fn candidate_path_min() {
8103 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
8104 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
8105 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
8106 // would add a connecting first_hop node that did not have enough contribution amount, leading
8107 // to a debug panic upon invalid path construction.
8108 let secp_ctx = Secp256k1::new();
8109 let logger = Arc::new(ln_test_utils::TestLogger::new());
8110 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8111 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
8112 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8113 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8114 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8115 let config = UserConfig::default();
8117 // Values are taken from the fuzz input that uncovered this panic.
8118 let amt_msat = 7_4009_8048;
8119 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
8120 let first_hops = vec![get_channel_details(
8121 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
8124 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
8125 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8126 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8127 short_channel_id: 6,
8130 cltv_expiry_delta: (6 << 4) | 0,
8131 htlc_minimum_msat: 0,
8132 htlc_maximum_msat: MAX_VALUE_MSAT,
8134 fee_proportional_millionths: 0,
8135 excess_data: Vec::new()
8137 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
8139 let htlc_min = 2_5165_8240;
8140 let blinded_hints = vec![
8142 fee_base_msat: 1_6778_3453,
8143 fee_proportional_millionths: 0,
8144 htlc_minimum_msat: htlc_min,
8145 htlc_maximum_msat: htlc_min * 100,
8146 cltv_expiry_delta: 10,
8147 features: BlindedHopFeatures::empty(),
8149 introduction_node_id: nodes[0],
8150 blinding_point: ln_test_utils::pubkey(42),
8152 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8153 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8157 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8158 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8159 .with_bolt12_features(bolt12_features.clone()).unwrap();
8160 let route_params = RouteParameters::from_payment_params_and_value(
8161 payment_params, amt_msat);
8162 let netgraph = network_graph.read_only();
8164 if let Err(LightningError { err, .. }) = get_route(
8165 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8166 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8169 assert_eq!(err, "Failed to find a path to the given destination");
8174 fn path_contribution_includes_min_htlc_overpay() {
8175 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
8176 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
8177 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
8178 // selection, both tested here.
8179 let secp_ctx = Secp256k1::new();
8180 let logger = Arc::new(ln_test_utils::TestLogger::new());
8181 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8182 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8183 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8184 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8185 let config = UserConfig::default();
8187 // Values are taken from the fuzz input that uncovered this panic.
8188 let amt_msat = 562_0000;
8189 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8190 let first_hops = vec![
8191 get_channel_details(
8192 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
8196 let htlc_mins = [49_0000, 1125_0000];
8197 let payment_params = {
8198 let blinded_path = BlindedPath {
8199 introduction_node_id: nodes[0],
8200 blinding_point: ln_test_utils::pubkey(42),
8202 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8203 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8206 let mut blinded_hints = Vec::new();
8207 for htlc_min in htlc_mins.iter() {
8208 blinded_hints.push((BlindedPayInfo {
8210 fee_proportional_millionths: 0,
8211 htlc_minimum_msat: *htlc_min,
8212 htlc_maximum_msat: *htlc_min * 100,
8213 cltv_expiry_delta: 10,
8214 features: BlindedHopFeatures::empty(),
8215 }, blinded_path.clone()));
8217 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8218 PaymentParameters::blinded(blinded_hints.clone())
8219 .with_bolt12_features(bolt12_features.clone()).unwrap()
8222 let netgraph = network_graph.read_only();
8223 let route_params = RouteParameters::from_payment_params_and_value(
8224 payment_params, amt_msat);
8225 let route = get_route(
8226 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8227 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8230 assert_eq!(route.paths.len(), 1);
8231 assert_eq!(route.get_total_amount(), amt_msat);
8235 fn first_hop_preferred_over_hint() {
8236 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
8237 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
8238 let secp_ctx = Secp256k1::new();
8239 let logger = Arc::new(ln_test_utils::TestLogger::new());
8240 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8241 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
8242 let scorer = ln_test_utils::TestScorer::new();
8243 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8244 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8245 let config = UserConfig::default();
8247 let amt_msat = 1_000_000;
8248 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
8250 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
8251 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
8252 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8253 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8254 short_channel_id: 1,
8257 cltv_expiry_delta: 42,
8258 htlc_minimum_msat: 1_000,
8259 htlc_maximum_msat: 10_000_000,
8261 fee_proportional_millionths: 0,
8262 excess_data: Vec::new()
8264 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8265 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8266 short_channel_id: 1,
8269 cltv_expiry_delta: 42,
8270 htlc_minimum_msat: 1_000,
8271 htlc_maximum_msat: 10_000_000,
8273 fee_proportional_millionths: 0,
8274 excess_data: Vec::new()
8277 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
8278 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
8279 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8280 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8281 short_channel_id: 2,
8284 cltv_expiry_delta: 42,
8285 htlc_minimum_msat: 1_000,
8286 htlc_maximum_msat: 10_000_000,
8288 fee_proportional_millionths: 0,
8289 excess_data: Vec::new()
8291 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8292 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8293 short_channel_id: 2,
8296 cltv_expiry_delta: 42,
8297 htlc_minimum_msat: 1_000,
8298 htlc_maximum_msat: 10_000_000,
8300 fee_proportional_millionths: 0,
8301 excess_data: Vec::new()
8304 let dest_node_id = nodes[2];
8306 let route_hint = RouteHint(vec![RouteHintHop {
8307 src_node_id: our_node_id,
8308 short_channel_id: 44,
8311 proportional_millionths: 0,
8313 cltv_expiry_delta: 10,
8314 htlc_minimum_msat: None,
8315 htlc_maximum_msat: Some(5_000_000),
8318 src_node_id: nodes[0],
8319 short_channel_id: 45,
8322 proportional_millionths: 0,
8324 cltv_expiry_delta: 10,
8325 htlc_minimum_msat: None,
8326 htlc_maximum_msat: None,
8329 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8330 .with_route_hints(vec![route_hint]).unwrap()
8331 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8332 let route_params = RouteParameters::from_payment_params_and_value(
8333 payment_params, amt_msat);
8335 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8337 let first_hop = get_channel_details(Some(1), nodes[0],
8338 channelmanager::provided_init_features(&config), 999_999);
8339 let first_hops = vec![first_hop];
8341 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8342 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8343 &Default::default(), &random_seed_bytes).unwrap();
8344 assert_eq!(route.paths.len(), 1);
8345 assert_eq!(route.get_total_amount(), amt_msat);
8346 assert_eq!(route.paths[0].hops.len(), 2);
8347 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8348 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8349 assert_eq!(route.get_total_fees(), 123);
8351 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8352 // for a first hop channel.
8353 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8354 first_hop.outbound_scid_alias = Some(44);
8355 let first_hops = vec![first_hop];
8357 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8358 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8359 &Default::default(), &random_seed_bytes);
8360 assert!(route_res.is_err());
8362 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8363 // use the cheaper second hop of the route hint.
8364 let mut first_hop = get_channel_details(Some(1), nodes[0],
8365 channelmanager::provided_init_features(&config), 10_000_000);
8366 first_hop.outbound_scid_alias = Some(44);
8367 let first_hops = vec![first_hop];
8369 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8370 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8371 &Default::default(), &random_seed_bytes).unwrap();
8372 assert_eq!(route.paths.len(), 1);
8373 assert_eq!(route.get_total_amount(), amt_msat);
8374 assert_eq!(route.paths[0].hops.len(), 2);
8375 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8376 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8377 assert_eq!(route.get_total_fees(), 123);
8381 fn allow_us_being_first_hint() {
8382 // Check that we consider a route hint even if we are the src of the first hop.
8383 let secp_ctx = Secp256k1::new();
8384 let logger = Arc::new(ln_test_utils::TestLogger::new());
8385 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8386 let scorer = ln_test_utils::TestScorer::new();
8387 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8388 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8389 let config = UserConfig::default();
8391 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8393 let amt_msat = 1_000_000;
8394 let dest_node_id = nodes[1];
8396 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8397 let first_hops = vec![first_hop];
8399 let route_hint = RouteHint(vec![RouteHintHop {
8400 src_node_id: our_node_id,
8401 short_channel_id: 44,
8404 proportional_millionths: 0,
8406 cltv_expiry_delta: 10,
8407 htlc_minimum_msat: None,
8408 htlc_maximum_msat: None,
8411 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8412 .with_route_hints(vec![route_hint]).unwrap()
8413 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8415 let route_params = RouteParameters::from_payment_params_and_value(
8416 payment_params, amt_msat);
8419 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8420 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8421 &Default::default(), &random_seed_bytes).unwrap();
8423 assert_eq!(route.paths.len(), 1);
8424 assert_eq!(route.get_total_amount(), amt_msat);
8425 assert_eq!(route.get_total_fees(), 0);
8426 assert_eq!(route.paths[0].hops.len(), 1);
8428 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8432 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
8433 pub(crate) mod bench_utils {
8437 use bitcoin::hashes::Hash;
8438 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
8440 use crate::chain::transaction::OutPoint;
8441 use crate::routing::scoring::ScoreUpdate;
8442 use crate::sign::{EntropySource, KeysManager};
8443 use crate::ln::ChannelId;
8444 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
8445 use crate::ln::features::Bolt11InvoiceFeatures;
8446 use crate::routing::gossip::NetworkGraph;
8447 use crate::routing::scoring::ProbabilisticScorer;
8448 use crate::util::config::UserConfig;
8449 use crate::util::ser::ReadableArgs;
8450 use crate::util::test_utils::TestLogger;
8451 use crate::sync::Arc;
8453 /// Tries to open a network graph file, or panics with a URL to fetch it.
8454 pub(crate) fn get_graph_scorer_file() -> Result<(std::fs::File, std::fs::File), &'static str> {
8455 let load_file = |fname, err_str| {
8456 File::open(fname) // By default we're run in RL/lightning
8457 .or_else(|_| File::open(&format!("lightning/{}", fname))) // We may be run manually in RL/
8458 .or_else(|_| { // Fall back to guessing based on the binary location
8459 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8460 let mut path = std::env::current_exe().unwrap();
8461 path.pop(); // lightning-...
8463 path.pop(); // debug
8464 path.pop(); // target
8465 path.push("lightning");
8469 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8470 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8471 let mut path = std::env::current_exe().unwrap();
8472 path.pop(); // bench...
8474 path.pop(); // debug
8475 path.pop(); // target
8476 path.pop(); // bench
8477 path.push("lightning");
8481 .map_err(|_| err_str)
8483 let graph_res = load_file(
8484 "net_graph-2023-12-10.bin",
8485 "Please fetch https://bitcoin.ninja/ldk-net_graph-v0.0.118-2023-12-10.bin and place it at lightning/net_graph-2023-12-10.bin"
8487 let scorer_res = load_file(
8488 "scorer-2023-12-10.bin",
8489 "Please fetch https://bitcoin.ninja/ldk-scorer-v0.0.118-2023-12-10.bin and place it at scorer-2023-12-10.bin"
8491 #[cfg(require_route_graph_test)]
8492 return Ok((graph_res.unwrap(), scorer_res.unwrap()));
8493 #[cfg(not(require_route_graph_test))]
8494 return Ok((graph_res?, scorer_res?));
8497 pub(crate) fn read_graph_scorer(logger: &TestLogger)
8498 -> Result<(Arc<NetworkGraph<&TestLogger>>, ProbabilisticScorer<Arc<NetworkGraph<&TestLogger>>, &TestLogger>), &'static str> {
8499 let (mut graph_file, mut scorer_file) = get_graph_scorer_file()?;
8500 let graph = Arc::new(NetworkGraph::read(&mut graph_file, logger).unwrap());
8501 let scorer_args = (Default::default(), Arc::clone(&graph), logger);
8502 let scorer = ProbabilisticScorer::read(&mut scorer_file, scorer_args).unwrap();
8506 pub(crate) fn payer_pubkey() -> PublicKey {
8507 let secp_ctx = Secp256k1::new();
8508 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8512 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8514 channel_id: ChannelId::new_zero(),
8515 counterparty: ChannelCounterparty {
8516 features: channelmanager::provided_init_features(&UserConfig::default()),
8518 unspendable_punishment_reserve: 0,
8519 forwarding_info: None,
8520 outbound_htlc_minimum_msat: None,
8521 outbound_htlc_maximum_msat: None,
8523 funding_txo: Some(OutPoint {
8524 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8527 short_channel_id: Some(1),
8528 inbound_scid_alias: None,
8529 outbound_scid_alias: None,
8530 channel_value_satoshis: 10_000_000_000,
8532 balance_msat: 10_000_000_000,
8533 outbound_capacity_msat: 10_000_000_000,
8534 next_outbound_htlc_minimum_msat: 0,
8535 next_outbound_htlc_limit_msat: 10_000_000_000,
8536 inbound_capacity_msat: 0,
8537 unspendable_punishment_reserve: None,
8538 confirmations_required: None,
8539 confirmations: None,
8540 force_close_spend_delay: None,
8542 is_channel_ready: true,
8545 inbound_htlc_minimum_msat: None,
8546 inbound_htlc_maximum_msat: None,
8548 feerate_sat_per_1000_weight: None,
8549 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
8553 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8554 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8555 starting_amount: u64, route_count: usize,
8556 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8557 let payer = payer_pubkey();
8558 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8559 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8561 let nodes = graph.read_only().nodes().clone();
8562 let mut route_endpoints = Vec::new();
8563 for _ in 0..route_count {
8565 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8566 let src = PublicKey::from_slice(nodes.unordered_keys()
8567 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8568 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8569 let dst = PublicKey::from_slice(nodes.unordered_keys()
8570 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8571 let params = PaymentParameters::from_node_id(dst, 42)
8572 .with_bolt11_features(features.clone()).unwrap();
8573 let first_hop = first_hop(src);
8574 let amt_msat = starting_amount + seed % 1_000_000;
8575 let route_params = RouteParameters::from_payment_params_and_value(
8576 params.clone(), amt_msat);
8578 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8579 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8581 route_endpoints.push((first_hop, params, amt_msat));
8587 // Because we've changed channel scores, it's possible we'll take different routes to the
8588 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
8589 // requires a too-high CLTV delta.
8590 route_endpoints.retain(|(first_hop, params, amt_msat)| {
8591 let route_params = RouteParameters::from_payment_params_and_value(
8592 params.clone(), *amt_msat);
8593 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8594 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
8596 route_endpoints.truncate(route_count);
8597 assert_eq!(route_endpoints.len(), route_count);
8605 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8606 use crate::sign::{EntropySource, KeysManager};
8607 use crate::ln::channelmanager;
8608 use crate::ln::features::Bolt11InvoiceFeatures;
8609 use crate::routing::gossip::NetworkGraph;
8610 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScoringFeeParameters};
8611 use crate::util::config::UserConfig;
8612 use crate::util::logger::{Logger, Record};
8613 use crate::util::test_utils::TestLogger;
8615 use criterion::Criterion;
8617 struct DummyLogger {}
8618 impl Logger for DummyLogger {
8619 fn log(&self, _record: Record) {}
8622 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8623 let logger = TestLogger::new();
8624 let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap();
8625 let scorer = FixedPenaltyScorer::with_penalty(0);
8626 generate_routes(bench, &network_graph, scorer, &Default::default(),
8627 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8630 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8631 let logger = TestLogger::new();
8632 let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap();
8633 let scorer = FixedPenaltyScorer::with_penalty(0);
8634 generate_routes(bench, &network_graph, scorer, &Default::default(),
8635 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8636 "generate_mpp_routes_with_zero_penalty_scorer");
8639 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8640 let logger = TestLogger::new();
8641 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8642 let params = ProbabilisticScoringFeeParameters::default();
8643 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8644 "generate_routes_with_probabilistic_scorer");
8647 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8648 let logger = TestLogger::new();
8649 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8650 let params = ProbabilisticScoringFeeParameters::default();
8651 generate_routes(bench, &network_graph, scorer, ¶ms,
8652 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8653 "generate_mpp_routes_with_probabilistic_scorer");
8656 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8657 let logger = TestLogger::new();
8658 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8659 let params = ProbabilisticScoringFeeParameters::default();
8660 generate_routes(bench, &network_graph, scorer, ¶ms,
8661 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8662 "generate_large_mpp_routes_with_probabilistic_scorer");
8665 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8666 let logger = TestLogger::new();
8667 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8668 let mut params = ProbabilisticScoringFeeParameters::default();
8669 params.linear_success_probability = false;
8670 generate_routes(bench, &network_graph, scorer, ¶ms,
8671 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8672 "generate_routes_with_nonlinear_probabilistic_scorer");
8675 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8676 let logger = TestLogger::new();
8677 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8678 let mut params = ProbabilisticScoringFeeParameters::default();
8679 params.linear_success_probability = false;
8680 generate_routes(bench, &network_graph, scorer, ¶ms,
8681 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8682 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8685 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8686 let logger = TestLogger::new();
8687 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8688 let mut params = ProbabilisticScoringFeeParameters::default();
8689 params.linear_success_probability = false;
8690 generate_routes(bench, &network_graph, scorer, ¶ms,
8691 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8692 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8695 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8696 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8697 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8698 bench_name: &'static str,
8700 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8701 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8703 // ...then benchmark finding paths between the nodes we learned.
8704 do_route_bench(bench, graph, scorer, score_params, bench_name, route_endpoints);
8708 fn do_route_bench<S: ScoreLookUp + ScoreUpdate>(
8709 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, scorer: S,
8710 score_params: &S::ScoreParams, bench_name: &'static str,
8711 route_endpoints: Vec<(ChannelDetails, PaymentParameters, u64)>,
8713 let payer = bench_utils::payer_pubkey();
8714 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8715 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8718 bench.bench_function(bench_name, |b| b.iter(|| {
8719 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8720 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8721 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8722 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());