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.
1115 // Thus, we use `#[repr(C)]` on the struct to force a suboptimal layout and check that it stays 64
1117 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1118 const _GRAPH_NODE_SMALL: usize = 64 - core::mem::size_of::<RouteGraphNode>();
1119 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1120 const _GRAPH_NODE_FIXED_SIZE: usize = core::mem::size_of::<RouteGraphNode>() - 64;
1122 /// A [`CandidateRouteHop::FirstHop`] entry.
1123 #[derive(Clone, Debug)]
1124 pub struct CandidateFirstHop<'a> {
1125 /// Channel details of the first hop
1127 /// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1128 /// has been funded and is able to pay), and accessor methods may panic otherwise.
1130 /// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1131 pub details: &'a ChannelDetails,
1132 /// The node id of the payer, which is also the source side of this candidate route hop.
1133 pub payer_node_id: &'a NodeId,
1134 /// A unique ID which describes the payer. It will not conlict with any
1135 /// [`NodeInfo::node_counter`]s, but may be equal to one if the payer is a public node.
1136 payer_node_counter: u32,
1137 /// A unique ID which describes the first hop counterparty. It will not conlict with any
1138 /// [`NodeInfo::node_counter`]s, but may be equal to one if the counterparty is a public node.
1139 target_node_counter: u32,
1142 /// A [`CandidateRouteHop::PublicHop`] entry.
1143 #[derive(Clone, Debug)]
1144 pub struct CandidatePublicHop<'a> {
1145 /// Information about the channel, including potentially its capacity and
1146 /// direction-specific information.
1147 pub info: DirectedChannelInfo<'a>,
1148 /// The short channel ID of the channel, i.e. the identifier by which we refer to this
1150 pub short_channel_id: u64,
1153 /// A [`CandidateRouteHop::PrivateHop`] entry.
1154 #[derive(Clone, Debug)]
1155 pub struct CandidatePrivateHop<'a> {
1156 /// Information about the private hop communicated via BOLT 11.
1157 pub hint: &'a RouteHintHop,
1158 /// Node id of the next hop in BOLT 11 route hint.
1159 pub target_node_id: &'a NodeId,
1160 /// A unique ID which describes the source node of the hop (further from the payment target).
1161 /// It will not conlict with any [`NodeInfo::node_counter`]s, but may be equal to one if the
1162 /// node is a public node.
1163 source_node_counter: u32,
1164 /// A unique ID which describes the destination node of the hop (towards the payment target).
1165 /// It will not conlict with any [`NodeInfo::node_counter`]s, but may be equal to one if the
1166 /// node is a public node.
1167 target_node_counter: u32,
1171 /// A [`CandidateRouteHop::Blinded`] entry.
1172 #[derive(Clone, Debug)]
1173 pub struct CandidateBlindedPath<'a> {
1174 /// Information about the blinded path including the fee, HTLC amount limits, and
1175 /// cryptographic material required to build an HTLC through the given path.
1176 pub hint: &'a (BlindedPayInfo, BlindedPath),
1177 /// Index of the hint in the original list of blinded hints.
1179 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1180 /// a short channel ID for this hop.
1182 /// A unique ID which describes the introduction point of the blinded path.
1183 /// It will not conlict with any [`NodeInfo::node_counter`]s, but will generally be equal to
1184 /// one from the public network graph (assuming the introduction point is a public node).
1185 source_node_counter: u32,
1188 /// A [`CandidateRouteHop::OneHopBlinded`] entry.
1189 #[derive(Clone, Debug)]
1190 pub struct CandidateOneHopBlindedPath<'a> {
1191 /// Information about the blinded path including the fee, HTLC amount limits, and
1192 /// cryptographic material required to build an HTLC terminating with the given path.
1194 /// Note that the [`BlindedPayInfo`] is ignored here.
1195 pub hint: &'a (BlindedPayInfo, BlindedPath),
1196 /// Index of the hint in the original list of blinded hints.
1198 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1199 /// a short channel ID for this hop.
1201 /// A unique ID which describes the introduction point of the blinded path.
1202 /// It will not conlict with any [`NodeInfo::node_counter`]s, but will generally be equal to
1203 /// one from the public network graph (assuming the introduction point is a public node).
1204 source_node_counter: u32,
1207 /// A wrapper around the various hop representations.
1209 /// Can be used to examine the properties of a hop,
1210 /// potentially to decide whether to include it in a route.
1211 #[derive(Clone, Debug)]
1212 pub enum CandidateRouteHop<'a> {
1213 /// A hop from the payer, where the outbound liquidity is known.
1214 FirstHop(CandidateFirstHop<'a>),
1215 /// A hop found in the [`ReadOnlyNetworkGraph`].
1216 PublicHop(CandidatePublicHop<'a>),
1217 /// A private hop communicated by the payee, generally via a BOLT 11 invoice.
1219 /// Because BOLT 11 route hints can take multiple hops to get to the destination, this may not
1220 /// terminate at the payee.
1221 PrivateHop(CandidatePrivateHop<'a>),
1222 /// A blinded path which starts with an introduction point and ultimately terminates with the
1225 /// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1226 /// `None` in this state.
1228 /// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1229 /// path, the full path is treated as a single [`CandidateRouteHop`].
1230 Blinded(CandidateBlindedPath<'a>),
1231 /// Similar to [`Self::Blinded`], but the path here only has one hop.
1233 /// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1234 /// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1235 /// payee's identity - it's the introduction point!
1237 /// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1238 /// to the hops *between* the introduction node and the destination.
1240 /// This primarily exists to track that we need to included a blinded path at the end of our
1241 /// [`Route`], even though it doesn't actually add an additional hop in the payment.
1242 OneHopBlinded(CandidateOneHopBlindedPath<'a>),
1245 impl<'a> CandidateRouteHop<'a> {
1246 /// Returns the short channel ID for this hop, if one is known.
1248 /// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1249 /// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1251 /// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1252 /// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1253 /// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1254 /// (which is always true for channels which are funded and ready for use).
1256 /// In other words, this should always return `Some` as long as the candidate hop is not a
1257 /// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1259 /// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1260 /// define a global namespace.
1262 fn short_channel_id(&self) -> Option<u64> {
1264 CandidateRouteHop::FirstHop(hop) => hop.details.get_outbound_payment_scid(),
1265 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1266 CandidateRouteHop::PrivateHop(hop) => Some(hop.hint.short_channel_id),
1267 CandidateRouteHop::Blinded(_) => None,
1268 CandidateRouteHop::OneHopBlinded(_) => None,
1272 /// Returns the globally unique short channel ID for this hop, if one is known.
1274 /// This only returns `Some` if the channel is public (either our own, or one we've learned
1275 /// from the public network graph), and thus the short channel ID we have for this channel is
1276 /// globally unique and identifies this channel in a global namespace.
1278 pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1280 CandidateRouteHop::FirstHop(hop) => if hop.details.is_public { hop.details.short_channel_id } else { None },
1281 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1282 CandidateRouteHop::PrivateHop(_) => None,
1283 CandidateRouteHop::Blinded(_) => None,
1284 CandidateRouteHop::OneHopBlinded(_) => None,
1288 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1289 fn features(&self) -> ChannelFeatures {
1291 CandidateRouteHop::FirstHop(hop) => hop.details.counterparty.features.to_context(),
1292 CandidateRouteHop::PublicHop(hop) => hop.info.channel().features.clone(),
1293 CandidateRouteHop::PrivateHop(_) => ChannelFeatures::empty(),
1294 CandidateRouteHop::Blinded(_) => ChannelFeatures::empty(),
1295 CandidateRouteHop::OneHopBlinded(_) => ChannelFeatures::empty(),
1299 /// Returns the required difference in HTLC CLTV expiry between the [`Self::source`] and the
1300 /// next-hop for an HTLC taking this hop.
1302 /// This is the time that the node(s) in this hop have to claim the HTLC on-chain if the
1303 /// next-hop goes on chain with a payment preimage.
1305 pub fn cltv_expiry_delta(&self) -> u32 {
1307 CandidateRouteHop::FirstHop(_) => 0,
1308 CandidateRouteHop::PublicHop(hop) => hop.info.direction().cltv_expiry_delta as u32,
1309 CandidateRouteHop::PrivateHop(hop) => hop.hint.cltv_expiry_delta as u32,
1310 CandidateRouteHop::Blinded(hop) => hop.hint.0.cltv_expiry_delta as u32,
1311 CandidateRouteHop::OneHopBlinded(_) => 0,
1315 /// Returns the minimum amount that can be sent over this hop, in millisatoshis.
1317 pub fn htlc_minimum_msat(&self) -> u64 {
1319 CandidateRouteHop::FirstHop(hop) => hop.details.next_outbound_htlc_minimum_msat,
1320 CandidateRouteHop::PublicHop(hop) => hop.info.direction().htlc_minimum_msat,
1321 CandidateRouteHop::PrivateHop(hop) => hop.hint.htlc_minimum_msat.unwrap_or(0),
1322 CandidateRouteHop::Blinded(hop) => hop.hint.0.htlc_minimum_msat,
1323 CandidateRouteHop::OneHopBlinded { .. } => 0,
1328 fn src_node_counter(&self) -> u32 {
1330 CandidateRouteHop::FirstHop { payer_node_counter, .. } => *payer_node_counter,
1331 CandidateRouteHop::PublicHop { info, .. } => info.source_counter(),
1332 CandidateRouteHop::PrivateHop { source_node_counter, .. } => *source_node_counter,
1333 CandidateRouteHop::Blinded { source_node_counter, .. } => *source_node_counter,
1334 CandidateRouteHop::OneHopBlinded { source_node_counter, .. } => *source_node_counter,
1339 fn target_node_counter(&self) -> Option<u32> {
1341 CandidateRouteHop::FirstHop { target_node_counter, .. } => Some(*target_node_counter),
1342 CandidateRouteHop::PublicHop { info, .. } => Some(info.target_counter()),
1343 CandidateRouteHop::PrivateHop { target_node_counter, .. } => Some(*target_node_counter),
1344 CandidateRouteHop::Blinded { .. } => None,
1345 CandidateRouteHop::OneHopBlinded { .. } => None,
1349 /// Returns the fees that must be paid to route an HTLC over this channel.
1351 pub fn fees(&self) -> RoutingFees {
1353 CandidateRouteHop::FirstHop(_) => RoutingFees {
1354 base_msat: 0, proportional_millionths: 0,
1356 CandidateRouteHop::PublicHop(hop) => hop.info.direction().fees,
1357 CandidateRouteHop::PrivateHop(hop) => hop.hint.fees,
1358 CandidateRouteHop::Blinded(hop) => {
1360 base_msat: hop.hint.0.fee_base_msat,
1361 proportional_millionths: hop.hint.0.fee_proportional_millionths
1364 CandidateRouteHop::OneHopBlinded(_) =>
1365 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1369 /// Fetch the effective capacity of this hop.
1371 /// Note that this may be somewhat expensive, so calls to this should be limited and results
1373 fn effective_capacity(&self) -> EffectiveCapacity {
1375 CandidateRouteHop::FirstHop(hop) => EffectiveCapacity::ExactLiquidity {
1376 liquidity_msat: hop.details.next_outbound_htlc_limit_msat,
1378 CandidateRouteHop::PublicHop(hop) => hop.info.effective_capacity(),
1379 CandidateRouteHop::PrivateHop(CandidatePrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. }) =>
1380 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1381 CandidateRouteHop::PrivateHop(CandidatePrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. }) =>
1382 EffectiveCapacity::Infinite,
1383 CandidateRouteHop::Blinded(hop) =>
1384 EffectiveCapacity::HintMaxHTLC { amount_msat: hop.hint.0.htlc_maximum_msat },
1385 CandidateRouteHop::OneHopBlinded(_) => EffectiveCapacity::Infinite,
1389 /// Returns an ID describing the given hop.
1391 /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1393 fn id(&self) -> CandidateHopId {
1395 CandidateRouteHop::Blinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1396 CandidateRouteHop::OneHopBlinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1397 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1400 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1402 CandidateRouteHop::Blinded(CandidateBlindedPath { hint, .. }) | CandidateRouteHop::OneHopBlinded(CandidateOneHopBlindedPath { hint, .. }) => {
1408 /// Returns the source node id of current hop.
1410 /// Source node id refers to the node forwarding the HTLC through this hop.
1412 /// For [`Self::FirstHop`] we return payer's node id.
1414 pub fn source(&self) -> NodeId {
1416 CandidateRouteHop::FirstHop(hop) => *hop.payer_node_id,
1417 CandidateRouteHop::PublicHop(hop) => *hop.info.source(),
1418 CandidateRouteHop::PrivateHop(hop) => hop.hint.src_node_id.into(),
1419 CandidateRouteHop::Blinded(hop) => hop.hint.1.introduction_node_id.into(),
1420 CandidateRouteHop::OneHopBlinded(hop) => hop.hint.1.introduction_node_id.into(),
1423 /// Returns the target node id of this hop, if known.
1425 /// Target node id refers to the node receiving the HTLC after this hop.
1427 /// For [`Self::Blinded`] we return `None` because the ultimate destination after the blinded
1428 /// path is unknown.
1430 /// For [`Self::OneHopBlinded`] we return `None` because the target is the same as the source,
1431 /// and such a return value would be somewhat nonsensical.
1433 pub fn target(&self) -> Option<NodeId> {
1435 CandidateRouteHop::FirstHop(hop) => Some(hop.details.counterparty.node_id.into()),
1436 CandidateRouteHop::PublicHop(hop) => Some(*hop.info.target()),
1437 CandidateRouteHop::PrivateHop(hop) => Some(*hop.target_node_id),
1438 CandidateRouteHop::Blinded(_) => None,
1439 CandidateRouteHop::OneHopBlinded(_) => None,
1444 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1446 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1448 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1449 /// isn't guaranteed to be unique at all.
1451 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1452 /// difficult-to-use API.
1453 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1454 enum CandidateHopId {
1455 /// Contains (scid, src_node_id < target_node_id)
1457 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1462 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1463 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1465 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1466 EffectiveCapacity::Infinite => u64::max_value(),
1467 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1468 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1469 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1470 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1471 // expected to have been generated from up-to-date capacity information.
1472 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1473 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1474 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1478 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1479 -> bool where I1::Item: PartialEq<I2::Item> {
1481 let a = iter_a.next();
1482 let b = iter_b.next();
1483 if a.is_none() && b.is_none() { return true; }
1484 if a.is_none() || b.is_none() { return false; }
1485 if a.unwrap().ne(&b.unwrap()) { return false; }
1489 /// It's useful to keep track of the hops associated with the fees required to use them,
1490 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1491 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1492 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1494 #[repr(C)] // Force fields to appear in the order we define them.
1495 struct PathBuildingHop<'a> {
1496 candidate: CandidateRouteHop<'a>,
1497 target_node_counter: Option<u32>,
1498 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1499 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1500 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1501 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1502 /// avoid processing them again.
1503 was_processed: bool,
1504 /// Used to compare channels when choosing the for routing.
1505 /// Includes paying for the use of a hop and the following hops, as well as
1506 /// an estimated cost of reaching this hop.
1507 /// Might get stale when fees are recomputed. Primarily for internal use.
1508 total_fee_msat: u64,
1509 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1510 /// walk and may be invalid thereafter.
1511 path_htlc_minimum_msat: u64,
1512 /// All penalties incurred from this channel on the way to the destination, as calculated using
1513 /// channel scoring.
1514 path_penalty_msat: u64,
1516 // The last 16 bytes are on the next cache line by default in glibc's malloc. Thus, we should
1517 // only place fields which are not hot there. Luckily, the next three fields are only read if
1518 // we end up on the selected path, and only in the final path layout phase, so we don't care
1519 // too much if reading them is slow.
1523 /// All the fees paid *after* this channel on the way to the destination
1524 next_hops_fee_msat: u64,
1525 /// Fee paid for the use of the current channel (see candidate.fees()).
1526 /// The value will be actually deducted from the counterparty balance on the previous link.
1527 hop_use_fee_msat: u64,
1529 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1530 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1531 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1532 // value_contribution_msat, which requires tracking it here. See comments below where it is
1533 // used for more info.
1534 value_contribution_msat: u64,
1537 // Checks that the entries in the `find_route` `dist` map fit in (exactly) two standard x86-64
1538 // cache lines. Sadly, they're not guaranteed to actually lie on a cache line (and in fact,
1539 // generally won't, because at least glibc's malloc will align to a nice, big, round
1540 // boundary...plus 16), but at least it will reduce the amount of data we'll need to load.
1542 // Note that these assertions only pass on somewhat recent rustc, and thus are gated on the
1545 const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::<(NodeId, PathBuildingHop)>();
1547 const _NODE_MAP_SIZE_EXACTLY_CACHE_LINES: usize = core::mem::size_of::<(NodeId, PathBuildingHop)>() - 128;
1549 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1550 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1551 let mut debug_struct = f.debug_struct("PathBuildingHop");
1553 .field("source_node_id", &self.candidate.source())
1554 .field("target_node_id", &self.candidate.target())
1555 .field("short_channel_id", &self.candidate.short_channel_id())
1556 .field("total_fee_msat", &self.total_fee_msat)
1557 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1558 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1559 .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)))
1560 .field("path_penalty_msat", &self.path_penalty_msat)
1561 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1562 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1563 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1564 let debug_struct = debug_struct
1565 .field("value_contribution_msat", &self.value_contribution_msat);
1566 debug_struct.finish()
1570 // Instantiated with a list of hops with correct data in them collected during path finding,
1571 // an instance of this struct should be further modified only via given methods.
1573 struct PaymentPath<'a> {
1574 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1577 impl<'a> PaymentPath<'a> {
1578 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1579 fn get_value_msat(&self) -> u64 {
1580 self.hops.last().unwrap().0.fee_msat
1583 fn get_path_penalty_msat(&self) -> u64 {
1584 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1587 fn get_total_fee_paid_msat(&self) -> u64 {
1588 if self.hops.len() < 1 {
1592 // Can't use next_hops_fee_msat because it gets outdated.
1593 for (i, (hop, _)) in self.hops.iter().enumerate() {
1594 if i != self.hops.len() - 1 {
1595 result += hop.fee_msat;
1601 fn get_cost_msat(&self) -> u64 {
1602 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1605 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1606 // to change fees may result in an inconsistency.
1608 // Sometimes we call this function right after constructing a path which is inconsistent in
1609 // that it the value being transferred has decreased while we were doing path finding, leading
1610 // to the fees being paid not lining up with the actual limits.
1612 // Note that this function is not aware of the available_liquidity limit, and thus does not
1613 // support increasing the value being transferred beyond what was selected during the initial
1616 // Returns the amount that this path contributes to the total payment value, which may be greater
1617 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1618 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1619 let mut extra_contribution_msat = 0;
1620 let mut total_fee_paid_msat = 0 as u64;
1621 for i in (0..self.hops.len()).rev() {
1622 let last_hop = i == self.hops.len() - 1;
1624 // For non-last-hop, this value will represent the fees paid on the current hop. It
1625 // will consist of the fees for the use of the next hop, and extra fees to match
1626 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1627 let mut cur_hop_fees_msat = 0;
1629 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1632 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1633 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1634 cur_hop.path_penalty_msat += extra_contribution_msat;
1635 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1636 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1637 // set it too high just to maliciously take more fees by exploiting this
1638 // match htlc_minimum_msat logic.
1639 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1640 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1641 // Note that there is a risk that *previous hops* (those closer to us, as we go
1642 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1644 // This might make us end up with a broken route, although this should be super-rare
1645 // in practice, both because of how healthy channels look like, and how we pick
1646 // channels in add_entry.
1647 // Also, this can't be exploited more heavily than *announce a free path and fail
1649 cur_hop_transferred_amount_msat += extra_fees_msat;
1651 // We remember and return the extra fees on the final hop to allow accounting for
1652 // them in the path's value contribution.
1654 extra_contribution_msat = extra_fees_msat;
1656 total_fee_paid_msat += extra_fees_msat;
1657 cur_hop_fees_msat += extra_fees_msat;
1662 // Final hop is a special case: it usually has just value_msat (by design), but also
1663 // it still could overpay for the htlc_minimum_msat.
1664 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1666 // Propagate updated fees for the use of the channels to one hop back, where they
1667 // will be actually paid (fee_msat). The last hop is handled above separately.
1668 cur_hop.fee_msat = cur_hop_fees_msat;
1671 // Fee for the use of the current hop which will be deducted on the previous hop.
1672 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1673 // this channel is free for us.
1675 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1676 cur_hop.hop_use_fee_msat = new_fee;
1677 total_fee_paid_msat += new_fee;
1679 // It should not be possible because this function is called only to reduce the
1680 // value. In that case, compute_fee was already called with the same fees for
1681 // larger amount and there was no overflow.
1686 value_msat + extra_contribution_msat
1691 /// Calculate the fees required to route the given amount over a channel with the given fees.
1692 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1693 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1694 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1698 /// Calculate the fees required to route the given amount over a channel with the given fees,
1699 /// saturating to [`u64::max_value`].
1700 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1701 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1702 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1703 .saturating_add(channel_fees.base_msat as u64)
1706 /// The default `features` we assume for a node in a route, when no `features` are known about that
1709 /// Default features are:
1710 /// * variable_length_onion_optional
1711 fn default_node_features() -> NodeFeatures {
1712 let mut features = NodeFeatures::empty();
1713 features.set_variable_length_onion_optional();
1717 struct LoggedPayeePubkey(Option<PublicKey>);
1718 impl fmt::Display for LoggedPayeePubkey {
1719 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1722 "payee node id ".fmt(f)?;
1726 "blinded payee".fmt(f)
1732 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1733 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1734 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1736 CandidateRouteHop::Blinded(CandidateBlindedPath { hint, .. }) | CandidateRouteHop::OneHopBlinded(CandidateOneHopBlindedPath { hint, .. }) => {
1737 "blinded route hint with introduction node id ".fmt(f)?;
1738 hint.1.introduction_node_id.fmt(f)?;
1739 " and blinding point ".fmt(f)?;
1740 hint.1.blinding_point.fmt(f)
1742 CandidateRouteHop::FirstHop(_) => {
1743 "first hop with SCID ".fmt(f)?;
1744 self.0.short_channel_id().unwrap().fmt(f)
1746 CandidateRouteHop::PrivateHop(_) => {
1747 "route hint with SCID ".fmt(f)?;
1748 self.0.short_channel_id().unwrap().fmt(f)
1752 self.0.short_channel_id().unwrap().fmt(f)
1759 fn sort_first_hop_channels(
1760 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1761 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1763 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1764 // most like to use.
1766 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1767 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1770 // Second, because simply always sorting in descending order would always use our largest
1771 // available outbound capacity, needlessly fragmenting our available channel capacities,
1772 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1773 // which have enough, but not too much, capacity for the payment.
1775 // Available outbound balances factor in liquidity already reserved for previously found paths.
1776 channels.sort_unstable_by(|chan_a, chan_b| {
1777 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1778 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1779 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1780 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1781 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1782 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1783 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1784 // Sort in descending order
1785 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1787 // Sort in ascending order
1788 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1793 /// Finds a route from us (payer) to the given target node (payee).
1795 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1796 /// in the given [`RouteParameters::payment_params`].
1797 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1799 /// Private routing paths between a public node and the target may be included in the `payee` field
1800 /// of [`RouteParameters::payment_params`].
1802 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1803 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1804 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1806 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1807 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1808 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1812 /// Panics if first_hops contains channels without `short_channel_id`s;
1813 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1815 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1816 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1817 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1818 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1819 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1820 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1821 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1822 ) -> Result<Route, LightningError>
1823 where L::Target: Logger, GL::Target: Logger {
1824 let graph_lock = network_graph.read_only();
1825 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1826 scorer, score_params, random_seed_bytes)?;
1827 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1831 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1832 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1833 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1834 _random_seed_bytes: &[u8; 32]
1835 ) -> Result<Route, LightningError>
1836 where L::Target: Logger {
1838 let payment_params = &route_params.payment_params;
1839 let final_value_msat = route_params.final_value_msat;
1840 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1841 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1842 // so use a dummy id for this in the blinded case.
1843 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1844 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1845 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1846 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1847 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1849 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1850 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1852 if our_node_id == maybe_dummy_payee_node_id {
1853 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1856 if final_value_msat > MAX_VALUE_MSAT {
1857 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1860 if final_value_msat == 0 {
1861 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1864 match &payment_params.payee {
1865 Payee::Clear { route_hints, node_id, .. } => {
1866 for route in route_hints.iter() {
1867 for hop in &route.0 {
1868 if hop.src_node_id == *node_id {
1869 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1874 Payee::Blinded { route_hints, .. } => {
1875 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1876 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});
1878 for (_, blinded_path) in route_hints.iter() {
1879 if blinded_path.blinded_hops.len() == 0 {
1880 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1881 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1882 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1883 } else if blinded_path.blinded_hops.len() == 1 &&
1884 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1885 && p.introduction_node_id != blinded_path.introduction_node_id)
1887 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1892 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1893 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1894 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});
1897 // The general routing idea is the following:
1898 // 1. Fill first/last hops communicated by the caller.
1899 // 2. Attempt to construct a path from payer to payee for transferring
1900 // any ~sufficient (described later) value.
1901 // If succeed, remember which channels were used and how much liquidity they have available,
1902 // so that future paths don't rely on the same liquidity.
1903 // 3. Proceed to the next step if:
1904 // - we hit the recommended target value;
1905 // - OR if we could not construct a new path. Any next attempt will fail too.
1906 // Otherwise, repeat step 2.
1907 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1908 // (not recommended value).
1909 // 5. If yes, proceed. If not, fail routing.
1910 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1911 // transferred up to the transfer target value.
1912 // 7. Reduce the value of the last path until we are sending only the target value.
1913 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1914 // them so that we're not sending two HTLCs along the same path.
1916 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1917 // distance from the payee
1919 // We are not a faithful Dijkstra's implementation because we can change values which impact
1920 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1921 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1922 // the value we are currently attempting to send over a path, we simply reduce the value being
1923 // sent along the path for any hops after that channel. This may imply that later fees (which
1924 // we've already tabulated) are lower because a smaller value is passing through the channels
1925 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1926 // channels which were selected earlier (and which may still be used for other paths without a
1927 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1930 // One potentially problematic case for this algorithm would be if there are many
1931 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1932 // graph walking), we may never find a path which is not liquidity-limited and has lower
1933 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1934 // Because we only consider paths with at least 5% of the total value being sent, the damage
1935 // from such a case should be limited, however this could be further reduced in the future by
1936 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1937 // limits for the purposes of fee calculation.
1939 // Alternatively, we could store more detailed path information in the heap (targets, below)
1940 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1941 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1942 // and practically (as we would need to store dynamically-allocated path information in heap
1943 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1944 // results of such an algorithm would likely be biased towards lower-value paths.
1946 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1947 // outside of our current search value, running a path search more times to gather candidate
1948 // paths at different values. While this may be acceptable, further path searches may increase
1949 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1950 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1951 // the same time, remaining generic across different payment values.
1953 let network_channels = network_graph.channels();
1954 let network_nodes = network_graph.nodes();
1956 if payment_params.max_path_count == 0 {
1957 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1960 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1961 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1963 let allow_mpp = if payment_params.max_path_count == 1 {
1965 } else if payment_params.payee.supports_basic_mpp() {
1967 } else if let Some(payee) = payee_node_id_opt {
1968 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1969 |info| info.features.supports_basic_mpp()))
1972 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1974 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph with a fee limit of {} msat",
1975 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
1976 if allow_mpp { "with" } else { "without" },
1977 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " },
1978 max_total_routing_fee_msat);
1980 let private_hop_targets_node_counter_offset = network_graph.max_node_counter() + 2;
1981 let mut private_node_id_to_node_counter = HashMap::new();
1983 let mut private_hop_key_cache = HashMap::with_capacity(
1984 payment_params.payee.unblinded_route_hints().iter().map(|path| path.0.len()).sum()
1987 // Because we store references to private hop node_ids in `dist`, below, we need them to exist
1988 // (as `NodeId`, not `PublicKey`) for the lifetime of `dist`. Thus, we calculate all the keys
1989 // we'll need here and simply fetch them when routing.
1990 let payee_node_counter = payee_node_id_opt
1991 .and_then(|payee| network_nodes.get(&payee))
1992 .map(|node| node.node_counter)
1993 .unwrap_or(private_hop_targets_node_counter_offset);
1994 private_node_id_to_node_counter.insert(maybe_dummy_payee_node_id, payee_node_counter);
1995 private_hop_key_cache.insert(maybe_dummy_payee_pk, (NodeId::from_pubkey(&maybe_dummy_payee_pk), payee_node_counter));
1997 for route in payment_params.payee.unblinded_route_hints().iter() {
1998 for hop in route.0.iter() {
1999 let hop_node_id = NodeId::from_pubkey(&hop.src_node_id);
2000 let node_counter = if let Some(node) = network_nodes.get(&hop_node_id) {
2003 let next_node_counter = private_hop_targets_node_counter_offset + private_node_id_to_node_counter.len() as u32;
2004 *private_node_id_to_node_counter.entry(hop_node_id)
2005 .or_insert(next_node_counter)
2007 private_hop_key_cache.insert(hop.src_node_id, (hop_node_id, node_counter));
2012 // Prepare the data we'll use for payee-to-payer search by
2013 // inserting first hops suggested by the caller as targets.
2014 // Our search will then attempt to reach them while traversing from the payee node.
2015 let mut first_hop_targets: HashMap<_, (Vec<&ChannelDetails>, u32)> =
2016 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
2017 if let Some(hops) = first_hops {
2019 if chan.get_outbound_payment_scid().is_none() {
2020 panic!("first_hops should be filled in with usable channels, not pending ones");
2022 if chan.counterparty.node_id == *our_node_pubkey {
2023 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
2025 let counterparty_node_id = NodeId::from_pubkey(&chan.counterparty.node_id);
2027 .entry(counterparty_node_id)
2028 .or_insert_with(|| {
2029 let node_counter = if let Some(node) = network_nodes.get(&counterparty_node_id) {
2032 let next_node_counter = private_hop_targets_node_counter_offset + private_node_id_to_node_counter.len() as u32;
2033 *private_node_id_to_node_counter.entry(counterparty_node_id)
2034 .or_insert(next_node_counter)
2036 (Vec::new(), node_counter)
2040 if first_hop_targets.is_empty() {
2041 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
2045 // The main heap containing all candidate next-hops sorted by their score (max(fee,
2046 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
2047 // adding duplicate entries when we find a better path to a given node.
2048 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
2050 // Map from node_id to information about the best current path to that node, including feerate
2052 let dist_len = private_hop_targets_node_counter_offset + private_hop_key_cache.len() as u32 + 1;
2053 let mut dist: Vec<Option<PathBuildingHop>> = vec![None; dist_len as usize];
2054 let payer_node_counter = network_nodes
2056 .map(|node| node.node_counter)
2058 private_node_id_to_node_counter.get(&our_node_id).map(|counter| *counter)
2060 .unwrap_or(network_graph.max_node_counter() + 1);
2062 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
2063 // indicating that we may wish to try again with a higher value, potentially paying to meet an
2064 // htlc_minimum with extra fees while still finding a cheaper path.
2065 let mut hit_minimum_limit;
2067 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
2068 // We start with a path_value of the exact amount we want, and if that generates a route we may
2069 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
2070 // amount we want in total across paths, selecting the best subset at the end.
2071 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
2072 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
2073 let mut path_value_msat = final_value_msat;
2075 // Routing Fragmentation Mitigation heuristic:
2077 // Routing fragmentation across many payment paths increases the overall routing
2078 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
2079 // Taking too many smaller paths also increases the chance of payment failure.
2080 // Thus to avoid this effect, we require from our collected links to provide
2081 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
2082 // This requirement is currently set to be 1/max_path_count of the payment
2083 // value to ensure we only ever return routes that do not violate this limit.
2084 let minimal_value_contribution_msat: u64 = if allow_mpp {
2085 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
2090 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
2091 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
2092 // drop the requirement by setting this to 0.
2093 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
2095 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
2096 // determine if the channel can be used by additional MPP paths or to inform path finding
2097 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
2098 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
2100 let mut used_liquidities: HashMap<CandidateHopId, u64> =
2101 HashMap::with_capacity(network_nodes.len());
2103 // Keeping track of how much value we already collected across other paths. Helps to decide
2104 // when we want to stop looking for new paths.
2105 let mut already_collected_value_msat = 0;
2107 for (_, (channels, _)) in first_hop_targets.iter_mut() {
2108 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
2112 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
2113 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
2115 // Remember how many candidates we ignored to allow for some logging afterwards.
2116 let mut num_ignored_value_contribution: u32 = 0;
2117 let mut num_ignored_path_length_limit: u32 = 0;
2118 let mut num_ignored_cltv_delta_limit: u32 = 0;
2119 let mut num_ignored_previously_failed: u32 = 0;
2120 let mut num_ignored_total_fee_limit: u32 = 0;
2121 let mut num_ignored_avoid_overpayment: u32 = 0;
2122 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
2124 macro_rules! add_entry {
2125 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
2126 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
2127 // since that value has to be transferred over this channel.
2128 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
2129 ( $candidate: expr, $next_hops_fee_msat: expr,
2130 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
2131 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
2132 // We "return" whether we updated the path at the end, and how much we can route via
2133 // this channel, via this:
2134 let mut hop_contribution_amt_msat = None;
2135 // Channels to self should not be used. This is more of belt-and-suspenders, because in
2136 // practice these cases should be caught earlier:
2137 // - for regular channels at channel announcement (TODO)
2138 // - for first and last hops early in get_route
2139 let src_node_id = $candidate.source();
2140 if Some(src_node_id) != $candidate.target() {
2141 let scid_opt = $candidate.short_channel_id();
2142 let effective_capacity = $candidate.effective_capacity();
2143 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
2145 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
2146 // It may be misleading because we might later choose to reduce the value transferred
2147 // over these channels, and the channel which was insufficient might become sufficient.
2148 // Worst case: we drop a good channel here because it can't cover the high following
2149 // fees caused by one expensive channel, but then this channel could have been used
2150 // if the amount being transferred over this path is lower.
2151 // We do this for now, but this is a subject for removal.
2152 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
2153 let used_liquidity_msat = used_liquidities
2154 .get(&$candidate.id())
2155 .map_or(0, |used_liquidity_msat| {
2156 available_value_contribution_msat = available_value_contribution_msat
2157 .saturating_sub(*used_liquidity_msat);
2158 *used_liquidity_msat
2161 // Verify the liquidity offered by this channel complies to the minimal contribution.
2162 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
2163 // Do not consider candidate hops that would exceed the maximum path length.
2164 let path_length_to_node = $next_hops_path_length + 1;
2165 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
2167 // Do not consider candidates that exceed the maximum total cltv expiry limit.
2168 // In order to already account for some of the privacy enhancing random CLTV
2169 // expiry delta offset we add on top later, we subtract a rough estimate
2170 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
2171 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
2172 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
2173 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
2174 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
2175 .saturating_add($candidate.cltv_expiry_delta());
2176 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
2178 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
2179 // Includes paying fees for the use of the following channels.
2180 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
2181 Some(result) => result,
2182 // Can't overflow due to how the values were computed right above.
2183 None => unreachable!(),
2185 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2186 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
2187 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
2189 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2190 let may_overpay_to_meet_path_minimum_msat =
2191 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
2192 recommended_value_msat >= $candidate.htlc_minimum_msat()) ||
2193 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
2194 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
2196 let payment_failed_on_this_channel = scid_opt.map_or(false,
2197 |scid| payment_params.previously_failed_channels.contains(&scid));
2199 let (should_log_candidate, first_hop_details) = match $candidate {
2200 CandidateRouteHop::FirstHop(hop) => (true, Some(hop.details)),
2201 CandidateRouteHop::PrivateHop(_) => (true, None),
2202 CandidateRouteHop::Blinded(_) => (true, None),
2203 CandidateRouteHop::OneHopBlinded(_) => (true, None),
2207 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
2208 // bother considering this channel. If retrying with recommended_value_msat may
2209 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
2210 // around again with a higher amount.
2211 if !contributes_sufficient_value {
2212 if should_log_candidate {
2213 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
2215 if let Some(details) = first_hop_details {
2217 "First hop candidate next_outbound_htlc_limit_msat: {}",
2218 details.next_outbound_htlc_limit_msat,
2222 num_ignored_value_contribution += 1;
2223 } else if exceeds_max_path_length {
2224 if should_log_candidate {
2225 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
2227 num_ignored_path_length_limit += 1;
2228 } else if exceeds_cltv_delta_limit {
2229 if should_log_candidate {
2230 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
2232 if let Some(_) = first_hop_details {
2234 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
2235 hop_total_cltv_delta,
2236 max_total_cltv_expiry_delta,
2240 num_ignored_cltv_delta_limit += 1;
2241 } else if payment_failed_on_this_channel {
2242 if should_log_candidate {
2243 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
2245 num_ignored_previously_failed += 1;
2246 } else if may_overpay_to_meet_path_minimum_msat {
2247 if should_log_candidate {
2249 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit.",
2250 LoggedCandidateHop(&$candidate));
2252 if let Some(details) = first_hop_details {
2254 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2255 details.next_outbound_htlc_minimum_msat,
2259 num_ignored_avoid_overpayment += 1;
2260 hit_minimum_limit = true;
2261 } else if over_path_minimum_msat {
2262 // Note that low contribution here (limited by available_liquidity_msat)
2263 // might violate htlc_minimum_msat on the hops which are next along the
2264 // payment path (upstream to the payee). To avoid that, we recompute
2265 // path fees knowing the final path contribution after constructing it.
2266 let curr_min = cmp::max(
2267 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
2269 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
2270 .saturating_add(curr_min);
2272 let dist_entry = &mut dist[$candidate.src_node_counter() as usize];
2273 let mut old_entry = if let Some(hop) = dist_entry {
2276 // If there was previously no known way to access the source node
2277 // (recall it goes payee-to-payer) of short_channel_id, first add a
2278 // semi-dummy record just to compute the fees to reach the source node.
2279 // This will affect our decision on selecting short_channel_id
2280 // as a way to reach the $candidate.target() node.
2281 *dist_entry = Some(PathBuildingHop {
2282 candidate: $candidate.clone(),
2283 target_node_counter: None,
2285 next_hops_fee_msat: u64::max_value(),
2286 hop_use_fee_msat: u64::max_value(),
2287 total_fee_msat: u64::max_value(),
2288 path_htlc_minimum_msat,
2289 path_penalty_msat: u64::max_value(),
2290 was_processed: false,
2291 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2292 value_contribution_msat,
2294 dist_entry.as_mut().unwrap()
2297 #[allow(unused_mut)] // We only use the mut in cfg(test)
2298 let mut should_process = !old_entry.was_processed;
2299 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2301 // In test/fuzzing builds, we do extra checks to make sure the skipping
2302 // of already-seen nodes only happens in cases we expect (see below).
2303 if !should_process { should_process = true; }
2307 let mut hop_use_fee_msat = 0;
2308 let mut total_fee_msat: u64 = $next_hops_fee_msat;
2310 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2311 // will have the same effective-fee
2312 if src_node_id != our_node_id {
2313 // Note that `u64::max_value` means we'll always fail the
2314 // `old_entry.total_fee_msat > total_fee_msat` check below
2315 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
2316 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2319 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2320 if total_fee_msat > max_total_routing_fee_msat {
2321 if should_log_candidate {
2322 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2324 if let Some(_) = first_hop_details {
2326 "First hop candidate routing fee: {}. Limit: {}",
2328 max_total_routing_fee_msat,
2332 num_ignored_total_fee_limit += 1;
2334 let channel_usage = ChannelUsage {
2335 amount_msat: amount_to_transfer_over_msat,
2336 inflight_htlc_msat: used_liquidity_msat,
2339 let channel_penalty_msat =
2340 scorer.channel_penalty_msat($candidate,
2343 let path_penalty_msat = $next_hops_path_penalty_msat
2344 .saturating_add(channel_penalty_msat);
2346 // Update the way of reaching $candidate.source()
2347 // with the given short_channel_id (from $candidate.target()),
2348 // if this way is cheaper than the already known
2349 // (considering the cost to "reach" this channel from the route destination,
2350 // the cost of using this channel,
2351 // and the cost of routing to the source node of this channel).
2352 // Also, consider that htlc_minimum_msat_difference, because we might end up
2353 // paying it. Consider the following exploit:
2354 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2355 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2356 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2357 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2359 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2360 // but it may require additional tracking - we don't want to double-count
2361 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2362 // can't use something that may decrease on future hops.
2363 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2364 .saturating_add(old_entry.path_penalty_msat);
2365 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2366 .saturating_add(path_penalty_msat);
2368 if !old_entry.was_processed && new_cost < old_cost {
2369 let new_graph_node = RouteGraphNode {
2370 node_id: src_node_id,
2371 score: cmp::max(total_fee_msat, path_htlc_minimum_msat).saturating_add(path_penalty_msat),
2372 total_cltv_delta: hop_total_cltv_delta,
2373 value_contribution_msat,
2374 path_length_to_node,
2376 targets.push(new_graph_node);
2377 old_entry.target_node_counter = $candidate.target_node_counter();
2378 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2379 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2380 old_entry.total_fee_msat = total_fee_msat;
2381 old_entry.candidate = $candidate.clone();
2382 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2383 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2384 old_entry.path_penalty_msat = path_penalty_msat;
2385 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2387 old_entry.value_contribution_msat = value_contribution_msat;
2389 hop_contribution_amt_msat = Some(value_contribution_msat);
2390 } else if old_entry.was_processed && new_cost < old_cost {
2391 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2393 // If we're skipping processing a node which was previously
2394 // processed even though we found another path to it with a
2395 // cheaper fee, check that it was because the second path we
2396 // found (which we are processing now) has a lower value
2397 // contribution due to an HTLC minimum limit.
2399 // e.g. take a graph with two paths from node 1 to node 2, one
2400 // through channel A, and one through channel B. Channel A and
2401 // B are both in the to-process heap, with their scores set by
2402 // a higher htlc_minimum than fee.
2403 // Channel A is processed first, and the channels onwards from
2404 // node 1 are added to the to-process heap. Thereafter, we pop
2405 // Channel B off of the heap, note that it has a much more
2406 // restrictive htlc_maximum_msat, and recalculate the fees for
2407 // all of node 1's channels using the new, reduced, amount.
2409 // This would be bogus - we'd be selecting a higher-fee path
2410 // with a lower htlc_maximum_msat instead of the one we'd
2411 // already decided to use.
2412 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2414 value_contribution_msat + path_penalty_msat <
2415 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2422 if should_log_candidate {
2424 "Ignoring {} due to its htlc_minimum_msat limit.",
2425 LoggedCandidateHop(&$candidate));
2427 if let Some(details) = first_hop_details {
2429 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2430 details.next_outbound_htlc_minimum_msat,
2434 num_ignored_htlc_minimum_msat_limit += 1;
2438 hop_contribution_amt_msat
2442 let default_node_features = default_node_features();
2444 // Find ways (channels with destination) to reach a given node and store them
2445 // in the corresponding data structures (routing graph etc).
2446 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2447 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2448 // This data can later be helpful to optimize routing (pay lower fees).
2449 macro_rules! add_entries_to_cheapest_to_target_node {
2450 ( $node: expr, $node_id: expr, $next_hops_value_contribution: expr,
2451 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2452 let fee_to_target_msat;
2453 let next_hops_path_htlc_minimum_msat;
2454 let next_hops_path_penalty_msat;
2455 let skip_node = if let Some(elem) = &mut dist[$node.node_counter as usize] {
2456 let was_processed = elem.was_processed;
2457 elem.was_processed = true;
2458 fee_to_target_msat = elem.total_fee_msat;
2459 next_hops_path_htlc_minimum_msat = elem.path_htlc_minimum_msat;
2460 next_hops_path_penalty_msat = elem.path_penalty_msat;
2463 // Entries are added to dist in add_entry!() when there is a channel from a node.
2464 // Because there are no channels from payee, it will not have a dist entry at this point.
2465 // If we're processing any other node, it is always be the result of a channel from it.
2466 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2468 fee_to_target_msat = 0;
2469 next_hops_path_htlc_minimum_msat = 0;
2470 next_hops_path_penalty_msat = 0;
2475 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get(&$node_id) {
2476 for details in first_channels {
2477 debug_assert_eq!(*peer_node_counter, $node.node_counter);
2478 let candidate = CandidateRouteHop::FirstHop(CandidateFirstHop {
2479 details, payer_node_id: &our_node_id, payer_node_counter,
2480 target_node_counter: $node.node_counter,
2482 add_entry!(&candidate, fee_to_target_msat,
2483 $next_hops_value_contribution,
2484 next_hops_path_htlc_minimum_msat, next_hops_path_penalty_msat,
2485 $next_hops_cltv_delta, $next_hops_path_length);
2489 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2492 &default_node_features
2495 if !features.requires_unknown_bits() {
2496 for chan_id in $node.channels.iter() {
2497 let chan = network_channels.get(chan_id).unwrap();
2498 if !chan.features.requires_unknown_bits() {
2499 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2500 if first_hops.is_none() || *source != our_node_id {
2501 if directed_channel.direction().enabled {
2502 let candidate = CandidateRouteHop::PublicHop(CandidatePublicHop {
2503 info: directed_channel,
2504 short_channel_id: *chan_id,
2506 add_entry!(&candidate,
2508 $next_hops_value_contribution,
2509 next_hops_path_htlc_minimum_msat,
2510 next_hops_path_penalty_msat,
2511 $next_hops_cltv_delta, $next_hops_path_length);
2522 let mut payment_paths = Vec::<PaymentPath>::new();
2524 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2525 'paths_collection: loop {
2526 // For every new path, start from scratch, except for used_liquidities, which
2527 // helps to avoid reusing previously selected paths in future iterations.
2529 for e in dist.iter_mut() {
2532 hit_minimum_limit = false;
2534 // If first hop is a private channel and the only way to reach the payee, this is the only
2535 // place where it could be added.
2536 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|(first_channels, peer_node_counter)| {
2537 debug_assert_eq!(*peer_node_counter, payee_node_counter);
2538 for details in first_channels {
2539 let candidate = CandidateRouteHop::FirstHop(CandidateFirstHop {
2540 details, payer_node_id: &our_node_id, payer_node_counter,
2541 target_node_counter: payee_node_counter,
2543 let added = add_entry!(&candidate, 0, path_value_msat,
2544 0, 0u64, 0, 0).is_some();
2545 log_trace!(logger, "{} direct route to payee via {}",
2546 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2550 // Add the payee as a target, so that the payee-to-payer
2551 // search algorithm knows what to start with.
2552 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2553 // The payee is not in our network graph, so nothing to add here.
2554 // There is still a chance of reaching them via last_hops though,
2555 // so don't yet fail the payment here.
2556 // If not, targets.pop() will not even let us enter the loop in step 2.
2559 add_entries_to_cheapest_to_target_node!(node, payee, path_value_msat, 0, 0);
2564 // If a caller provided us with last hops, add them to routing targets. Since this happens
2565 // earlier than general path finding, they will be somewhat prioritized, although currently
2566 // it matters only if the fees are exactly the same.
2567 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2568 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2569 let intro_node_counter_opt =
2570 // Only add the hops in this route to our candidate set if either
2571 // we have a direct channel to the first hop or the first hop is
2572 // in the regular network graph.
2573 network_nodes.get(&intro_node_id).map(|node| node.node_counter)
2575 first_hop_targets.get(&intro_node_id).map(|(_, node_counter)| *node_counter)
2577 if intro_node_counter_opt.is_none() || our_node_id == intro_node_id { continue }
2578 let candidate = if hint.1.blinded_hops.len() == 1 {
2579 CandidateRouteHop::OneHopBlinded(CandidateOneHopBlindedPath {
2582 source_node_counter: intro_node_counter_opt.unwrap(),
2585 CandidateRouteHop::Blinded(CandidateBlindedPath {
2588 source_node_counter: intro_node_counter_opt.unwrap(),
2591 let mut path_contribution_msat = path_value_msat;
2592 if let Some(hop_used_msat) = add_entry!(&candidate,
2593 0, path_contribution_msat, 0, 0_u64, 0, 0)
2595 path_contribution_msat = hop_used_msat;
2597 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2598 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2600 for details in first_channels {
2601 let first_hop_candidate = CandidateRouteHop::FirstHop(CandidateFirstHop {
2602 details, payer_node_id: &our_node_id, payer_node_counter,
2603 target_node_counter: *peer_node_counter,
2605 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2609 let path_min = candidate.htlc_minimum_msat().saturating_add(
2610 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2611 add_entry!(&first_hop_candidate, blinded_path_fee,
2612 path_contribution_msat, path_min, 0_u64, candidate.cltv_expiry_delta(),
2613 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2617 for route in payment_params.payee.unblinded_route_hints().iter()
2618 .filter(|route| !route.0.is_empty())
2620 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2621 let first_hop_src_is_reachable =
2622 // Only add the hops in this route to our candidate set if either we are part of
2623 // the first hop, we have a direct channel to the first hop, or the first hop is in
2624 // the regular network graph.
2625 our_node_id == first_hop_src_id ||
2626 first_hop_targets.get(&first_hop_src_id).is_some() ||
2627 network_nodes.get(&first_hop_src_id).is_some();
2628 if first_hop_src_is_reachable {
2629 // We start building the path from reverse, i.e., from payee
2630 // to the first RouteHintHop in the path.
2631 let hop_iter = route.0.iter().rev();
2632 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2633 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2634 let mut hop_used = true;
2635 let mut aggregate_next_hops_fee_msat: u64 = 0;
2636 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2637 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2638 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2639 let mut aggregate_next_hops_path_length: u8 = 0;
2640 let mut aggregate_path_contribution_msat = path_value_msat;
2642 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2643 let (target, private_target_node_counter) = private_hop_key_cache.get(&prev_hop_id).unwrap();
2644 let (_src_id, private_source_node_counter) = private_hop_key_cache.get(&hop.src_node_id).unwrap();
2646 if let Some((first_channels, _)) = first_hop_targets.get(&target) {
2647 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2648 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2649 hop.short_channel_id);
2654 let candidate = network_channels
2655 .get(&hop.short_channel_id)
2656 .and_then(|channel| channel.as_directed_to(&target))
2657 .map(|(info, _)| CandidateRouteHop::PublicHop(CandidatePublicHop {
2659 short_channel_id: hop.short_channel_id,
2661 .unwrap_or_else(|| CandidateRouteHop::PrivateHop(CandidatePrivateHop {
2662 hint: hop, target_node_id: target,
2663 source_node_counter: *private_source_node_counter,
2664 target_node_counter: *private_target_node_counter,
2667 if let Some(hop_used_msat) = add_entry!(&candidate,
2668 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2669 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2670 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2672 aggregate_path_contribution_msat = hop_used_msat;
2674 // If this hop was not used then there is no use checking the preceding
2675 // hops in the RouteHint. We can break by just searching for a direct
2676 // channel between last checked hop and first_hop_targets.
2680 let used_liquidity_msat = used_liquidities
2681 .get(&candidate.id()).copied()
2683 let channel_usage = ChannelUsage {
2684 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2685 inflight_htlc_msat: used_liquidity_msat,
2686 effective_capacity: candidate.effective_capacity(),
2688 let channel_penalty_msat = scorer.channel_penalty_msat(
2689 &candidate, channel_usage, score_params
2691 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2692 .saturating_add(channel_penalty_msat);
2694 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2695 .saturating_add(hop.cltv_expiry_delta as u32);
2697 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2700 // Searching for a direct channel between last checked hop and first_hop_targets
2701 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get_mut(&target) {
2702 sort_first_hop_channels(first_channels, &used_liquidities,
2703 recommended_value_msat, our_node_pubkey);
2704 for details in first_channels {
2705 let first_hop_candidate = CandidateRouteHop::FirstHop(CandidateFirstHop {
2706 details, payer_node_id: &our_node_id, payer_node_counter,
2707 target_node_counter: *peer_node_counter,
2709 add_entry!(&first_hop_candidate,
2710 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2711 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2712 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2720 // In the next values of the iterator, the aggregate fees already reflects
2721 // the sum of value sent from payer (final_value_msat) and routing fees
2722 // for the last node in the RouteHint. We need to just add the fees to
2723 // route through the current node so that the preceding node (next iteration)
2725 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2726 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2727 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2729 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2730 // this route hint's source node to forward said min over this channel.
2731 aggregate_next_hops_path_htlc_minimum_msat = {
2732 let curr_htlc_min = cmp::max(
2733 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2735 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2736 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2739 if idx == route.0.len() - 1 {
2740 // The last hop in this iterator is the first hop in
2741 // overall RouteHint.
2742 // If this hop connects to a node with which we have a direct channel,
2743 // ignore the network graph and, if the last hop was added, add our
2744 // direct channel to the candidate set.
2746 // Note that we *must* check if the last hop was added as `add_entry`
2747 // always assumes that the third argument is a node to which we have a
2749 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2750 sort_first_hop_channels(first_channels, &used_liquidities,
2751 recommended_value_msat, our_node_pubkey);
2752 for details in first_channels {
2753 let first_hop_candidate = CandidateRouteHop::FirstHop(CandidateFirstHop {
2754 details, payer_node_id: &our_node_id, payer_node_counter,
2755 target_node_counter: *peer_node_counter,
2757 add_entry!(&first_hop_candidate,
2758 aggregate_next_hops_fee_msat,
2759 aggregate_path_contribution_msat,
2760 aggregate_next_hops_path_htlc_minimum_msat,
2761 aggregate_next_hops_path_penalty_msat,
2762 aggregate_next_hops_cltv_delta,
2763 aggregate_next_hops_path_length);
2771 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2773 // At this point, targets are filled with the data from first and
2774 // last hops communicated by the caller, and the payment receiver.
2775 let mut found_new_path = false;
2778 // If this loop terminates due the exhaustion of targets, two situations are possible:
2779 // - not enough outgoing liquidity:
2780 // 0 < already_collected_value_msat < final_value_msat
2781 // - enough outgoing liquidity:
2782 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2783 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2784 // paths_collection will be stopped because found_new_path==false.
2785 // This is not necessarily a routing failure.
2786 'path_construction: while let Some(RouteGraphNode { node_id, total_cltv_delta, mut value_contribution_msat, path_length_to_node, .. }) = targets.pop() {
2788 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2789 // traversing the graph and arrange the path out of what we found.
2790 if node_id == our_node_id {
2791 let mut new_entry = dist[payer_node_counter as usize].take().unwrap();
2792 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2795 let mut features_set = false;
2796 let candidate = &ordered_hops.last().unwrap().0.candidate;
2797 let target = candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2798 let target_node_counter = candidate.target_node_counter();
2799 if let Some((first_channels, _)) = first_hop_targets.get(&target) {
2800 for details in first_channels {
2801 if let CandidateRouteHop::FirstHop(CandidateFirstHop { details: last_hop_details, .. })
2802 = ordered_hops.last().unwrap().0.candidate
2804 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2805 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2806 features_set = true;
2813 if let Some(node) = network_nodes.get(&target) {
2814 if let Some(node_info) = node.announcement_info.as_ref() {
2815 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2817 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2820 // We can fill in features for everything except hops which were
2821 // provided via the invoice we're paying. We could guess based on the
2822 // recipient's features but for now we simply avoid guessing at all.
2826 // Means we succesfully traversed from the payer to the payee, now
2827 // save this path for the payment route. Also, update the liquidity
2828 // remaining on the used hops, so that we take them into account
2829 // while looking for more paths.
2830 if target_node_counter.is_none() {
2833 if target_node_counter == Some(payee_node_counter) { break 'path_walk; }
2835 new_entry = match dist[target_node_counter.unwrap() as usize].take() {
2836 Some(payment_hop) => payment_hop,
2837 // We can't arrive at None because, if we ever add an entry to targets,
2838 // we also fill in the entry in dist (see add_entry!).
2839 None => unreachable!(),
2841 // We "propagate" the fees one hop backward (topologically) here,
2842 // so that fees paid for a HTLC forwarding on the current channel are
2843 // associated with the previous channel (where they will be subtracted).
2844 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2845 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2847 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2848 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2850 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2851 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2853 let mut payment_path = PaymentPath {hops: ordered_hops};
2855 // We could have possibly constructed a slightly inconsistent path: since we reduce
2856 // value being transferred along the way, we could have violated htlc_minimum_msat
2857 // on some channels we already passed (assuming dest->source direction). Here, we
2858 // recompute the fees again, so that if that's the case, we match the currently
2859 // underpaid htlc_minimum_msat with fees.
2860 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2861 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2862 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2864 // Since a path allows to transfer as much value as
2865 // the smallest channel it has ("bottleneck"), we should recompute
2866 // the fees so sender HTLC don't overpay fees when traversing
2867 // larger channels than the bottleneck. This may happen because
2868 // when we were selecting those channels we were not aware how much value
2869 // this path will transfer, and the relative fee for them
2870 // might have been computed considering a larger value.
2871 // Remember that we used these channels so that we don't rely
2872 // on the same liquidity in future paths.
2873 let mut prevented_redundant_path_selection = false;
2874 for (hop, _) in payment_path.hops.iter() {
2875 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2876 let used_liquidity_msat = used_liquidities
2877 .entry(hop.candidate.id())
2878 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2879 .or_insert(spent_on_hop_msat);
2880 let hop_capacity = hop.candidate.effective_capacity();
2881 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2882 if *used_liquidity_msat == hop_max_msat {
2883 // If this path used all of this channel's available liquidity, we know
2884 // this path will not be selected again in the next loop iteration.
2885 prevented_redundant_path_selection = true;
2887 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2889 if !prevented_redundant_path_selection {
2890 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2891 // we'll probably end up picking the same path again on the next iteration.
2892 // Decrease the available liquidity of a hop in the middle of the path.
2893 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2894 let exhausted = u64::max_value();
2896 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2897 LoggedCandidateHop(victim_candidate));
2898 if let Some(scid) = victim_candidate.short_channel_id() {
2899 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2900 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2904 // Track the total amount all our collected paths allow to send so that we know
2905 // when to stop looking for more paths
2906 already_collected_value_msat += value_contribution_msat;
2908 payment_paths.push(payment_path);
2909 found_new_path = true;
2910 break 'path_construction;
2913 // If we found a path back to the payee, we shouldn't try to process it again. This is
2914 // the equivalent of the `elem.was_processed` check in
2915 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2916 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2918 // Otherwise, since the current target node is not us,
2919 // keep "unrolling" the payment graph from payee to payer by
2920 // finding a way to reach the current target from the payer side.
2921 match network_nodes.get(&node_id) {
2924 add_entries_to_cheapest_to_target_node!(node, node_id,
2925 value_contribution_msat,
2926 total_cltv_delta, path_length_to_node);
2932 if !found_new_path && channel_saturation_pow_half != 0 {
2933 channel_saturation_pow_half = 0;
2934 continue 'paths_collection;
2936 // If we don't support MPP, no use trying to gather more value ever.
2937 break 'paths_collection;
2941 // Stop either when the recommended value is reached or if no new path was found in this
2943 // In the latter case, making another path finding attempt won't help,
2944 // because we deterministically terminated the search due to low liquidity.
2945 if !found_new_path && channel_saturation_pow_half != 0 {
2946 channel_saturation_pow_half = 0;
2947 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2948 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
2949 path_value_msat = recommended_value_msat;
2950 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2951 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2952 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2953 break 'paths_collection;
2954 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2955 // Further, if this was our first walk of the graph, and we weren't limited by an
2956 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2957 // limited by an htlc_minimum_msat value, find another path with a higher value,
2958 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2959 // still keeping a lower total fee than this path.
2960 if !hit_minimum_limit {
2961 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2962 break 'paths_collection;
2964 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.");
2965 path_value_msat = recommended_value_msat;
2969 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2970 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
2971 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
2972 num_ignored_total_fee_limit;
2973 if num_ignored_total > 0 {
2975 "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.",
2976 num_ignored_value_contribution, num_ignored_path_length_limit,
2977 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
2978 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
2979 num_ignored_total_fee_limit, num_ignored_total);
2983 if payment_paths.len() == 0 {
2984 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2987 if already_collected_value_msat < final_value_msat {
2988 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2992 let mut selected_route = payment_paths;
2994 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2995 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2997 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2998 // the value they contribute towards the payment amount.
2999 // We sort in descending order as we will remove from the front in `retain`, next.
3000 selected_route.sort_unstable_by(|a, b|
3001 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
3002 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
3005 // We should make sure that at least 1 path left.
3006 let mut paths_left = selected_route.len();
3007 selected_route.retain(|path| {
3008 if paths_left == 1 {
3011 let path_value_msat = path.get_value_msat();
3012 if path_value_msat <= overpaid_value_msat {
3013 overpaid_value_msat -= path_value_msat;
3019 debug_assert!(selected_route.len() > 0);
3021 if overpaid_value_msat != 0 {
3023 // Now, subtract the remaining overpaid value from the most-expensive path.
3024 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
3025 // so that the sender pays less fees overall. And also htlc_minimum_msat.
3026 selected_route.sort_unstable_by(|a, b| {
3027 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3028 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3029 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
3031 let expensive_payment_path = selected_route.first_mut().unwrap();
3033 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
3034 // can't go negative.
3035 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
3036 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
3040 // Sort by the path itself and combine redundant paths.
3041 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
3042 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
3044 selected_route.sort_unstable_by_key(|path| {
3045 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
3046 debug_assert!(path.hops.len() <= key.len());
3047 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
3052 for idx in 0..(selected_route.len() - 1) {
3053 if idx + 1 >= selected_route.len() { break; }
3054 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
3055 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
3056 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
3057 selected_route[idx].update_value_and_recompute_fees(new_value);
3058 selected_route.remove(idx + 1);
3062 let mut paths = Vec::new();
3063 for payment_path in selected_route {
3064 let mut hops = Vec::with_capacity(payment_path.hops.len());
3065 for (hop, node_features) in payment_path.hops.iter()
3066 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
3068 let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
3069 let maybe_announced_channel = if let CandidateRouteHop::PublicHop(_) = hop.candidate {
3070 // If we sourced the hop from the graph we're sure the target node is announced.
3072 } else if let CandidateRouteHop::FirstHop(first_hop) = &hop.candidate {
3073 // If this is a first hop we also know if it's announced.
3074 first_hop.details.is_public
3076 // If we sourced it any other way, we double-check the network graph to see if
3077 // there are announced channels between the endpoints. If so, the hop might be
3078 // referring to any of the announced channels, as its `short_channel_id` might be
3079 // an alias, in which case we don't take any chances here.
3080 network_graph.node(&target).map_or(false, |hop_node|
3081 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
3082 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
3086 hops.push(RouteHop {
3087 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
3088 node_features: node_features.clone(),
3089 short_channel_id: hop.candidate.short_channel_id().unwrap(),
3090 channel_features: hop.candidate.features(),
3091 fee_msat: hop.fee_msat,
3092 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
3093 maybe_announced_channel,
3096 let mut final_cltv_delta = final_cltv_expiry_delta;
3097 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
3098 if let Some(blinded_path) = h.candidate.blinded_path() {
3099 final_cltv_delta = h.candidate.cltv_expiry_delta();
3101 hops: blinded_path.blinded_hops.clone(),
3102 blinding_point: blinded_path.blinding_point,
3103 excess_final_cltv_expiry_delta: 0,
3104 final_value_msat: h.fee_msat,
3108 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
3109 // applicable for the previous hop.
3110 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
3111 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
3114 paths.push(Path { hops, blinded_tail });
3116 // Make sure we would never create a route with more paths than we allow.
3117 debug_assert!(paths.len() <= payment_params.max_path_count.into());
3119 if let Some(node_features) = payment_params.payee.node_features() {
3120 for path in paths.iter_mut() {
3121 path.hops.last_mut().unwrap().node_features = node_features.clone();
3125 let route = Route { paths, route_params: Some(route_params.clone()) };
3127 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
3128 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
3129 if route.get_total_fees() > max_total_routing_fee_msat {
3130 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
3131 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
3135 log_info!(logger, "Got route: {}", log_route!(route));
3139 // When an adversarial intermediary node observes a payment, it may be able to infer its
3140 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
3141 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
3142 // payment path by adding a randomized 'shadow route' offset to the final hop.
3143 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
3144 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
3146 let network_channels = network_graph.channels();
3147 let network_nodes = network_graph.nodes();
3149 for path in route.paths.iter_mut() {
3150 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
3152 // Remember the last three nodes of the random walk and avoid looping back on them.
3153 // Init with the last three nodes from the actual path, if possible.
3154 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
3155 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
3156 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
3158 // Choose the last publicly known node as the starting point for the random walk.
3159 let mut cur_hop: Option<NodeId> = None;
3160 let mut path_nonce = [0u8; 12];
3161 if let Some(starting_hop) = path.hops.iter().rev()
3162 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
3163 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
3164 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
3167 // Init PRNG with the path-dependant nonce, which is static for private paths.
3168 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
3169 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
3171 // Pick a random path length in [1 .. 3]
3172 prng.process_in_place(&mut random_path_bytes);
3173 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
3175 for random_hop in 0..random_walk_length {
3176 // If we don't find a suitable offset in the public network graph, we default to
3177 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3178 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
3180 if let Some(cur_node_id) = cur_hop {
3181 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
3182 // Randomly choose the next unvisited hop.
3183 prng.process_in_place(&mut random_path_bytes);
3184 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
3185 .checked_rem(cur_node.channels.len())
3186 .and_then(|index| cur_node.channels.get(index))
3187 .and_then(|id| network_channels.get(id)) {
3188 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
3189 if !nodes_to_avoid.iter().any(|x| x == next_id) {
3190 nodes_to_avoid[random_hop] = *next_id;
3191 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
3192 cur_hop = Some(*next_id);
3199 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
3200 .checked_add(random_hop_offset)
3201 .unwrap_or(shadow_ctlv_expiry_delta_offset);
3204 // Limit the total offset to reduce the worst-case locked liquidity timevalue
3205 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
3206 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
3208 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
3209 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3210 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
3211 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
3212 max_path_offset = cmp::max(
3213 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
3214 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
3215 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
3217 // Add 'shadow' CLTV offset to the final hop
3218 if let Some(tail) = path.blinded_tail.as_mut() {
3219 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
3220 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
3222 if let Some(last_hop) = path.hops.last_mut() {
3223 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
3224 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
3229 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
3230 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
3232 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
3233 pub fn build_route_from_hops<L: Deref, GL: Deref>(
3234 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3235 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
3236 ) -> Result<Route, LightningError>
3237 where L::Target: Logger, GL::Target: Logger {
3238 let graph_lock = network_graph.read_only();
3239 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
3240 &graph_lock, logger, random_seed_bytes)?;
3241 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
3245 fn build_route_from_hops_internal<L: Deref>(
3246 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3247 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
3248 ) -> Result<Route, LightningError> where L::Target: Logger {
3251 our_node_id: NodeId,
3252 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
3255 impl ScoreLookUp for HopScorer {
3256 type ScoreParams = ();
3257 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
3258 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
3260 let mut cur_id = self.our_node_id;
3261 for i in 0..self.hop_ids.len() {
3262 if let Some(next_id) = self.hop_ids[i] {
3263 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
3275 impl<'a> Writeable for HopScorer {
3277 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
3282 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
3283 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
3286 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
3287 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
3288 for i in 0..hops.len() {
3289 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
3292 let scorer = HopScorer { our_node_id, hop_ids };
3294 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
3299 use crate::blinded_path::{BlindedHop, BlindedPath};
3300 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
3301 use crate::routing::utxo::UtxoResult;
3302 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
3303 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
3304 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop, CandidatePublicHop};
3305 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
3306 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
3307 use crate::chain::transaction::OutPoint;
3308 use crate::sign::EntropySource;
3309 use crate::ln::ChannelId;
3310 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
3311 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
3312 use crate::ln::channelmanager;
3313 use crate::offers::invoice::BlindedPayInfo;
3314 use crate::util::config::UserConfig;
3315 use crate::util::test_utils as ln_test_utils;
3316 use crate::util::chacha20::ChaCha20;
3317 use crate::util::ser::{Readable, Writeable};
3319 use crate::util::ser::Writer;
3321 use bitcoin::hashes::Hash;
3322 use bitcoin::network::constants::Network;
3323 use bitcoin::blockdata::constants::ChainHash;
3324 use bitcoin::blockdata::script::Builder;
3325 use bitcoin::blockdata::opcodes;
3326 use bitcoin::blockdata::transaction::TxOut;
3327 use bitcoin::hashes::hex::FromHex;
3328 use bitcoin::secp256k1::{PublicKey,SecretKey};
3329 use bitcoin::secp256k1::Secp256k1;
3331 use crate::io::Cursor;
3332 use crate::prelude::*;
3333 use crate::sync::Arc;
3335 use core::convert::TryInto;
3337 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3338 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
3339 channelmanager::ChannelDetails {
3340 channel_id: ChannelId::new_zero(),
3341 counterparty: channelmanager::ChannelCounterparty {
3344 unspendable_punishment_reserve: 0,
3345 forwarding_info: None,
3346 outbound_htlc_minimum_msat: None,
3347 outbound_htlc_maximum_msat: None,
3349 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3352 outbound_scid_alias: None,
3353 inbound_scid_alias: None,
3354 channel_value_satoshis: 0,
3357 outbound_capacity_msat,
3358 next_outbound_htlc_limit_msat: outbound_capacity_msat,
3359 next_outbound_htlc_minimum_msat: 0,
3360 inbound_capacity_msat: 42,
3361 unspendable_punishment_reserve: None,
3362 confirmations_required: None,
3363 confirmations: None,
3364 force_close_spend_delay: None,
3365 is_outbound: true, is_channel_ready: true,
3366 is_usable: true, is_public: true,
3367 inbound_htlc_minimum_msat: None,
3368 inbound_htlc_maximum_msat: None,
3370 feerate_sat_per_1000_weight: None,
3371 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
3376 fn simple_route_test() {
3377 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3378 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3379 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3380 let scorer = ln_test_utils::TestScorer::new();
3381 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3382 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3384 // Simple route to 2 via 1
3386 let route_params = RouteParameters::from_payment_params_and_value(
3387 payment_params.clone(), 0);
3388 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3389 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3390 &Default::default(), &random_seed_bytes) {
3391 assert_eq!(err, "Cannot send a payment of 0 msat");
3392 } else { panic!(); }
3394 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3395 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3396 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3397 assert_eq!(route.paths[0].hops.len(), 2);
3399 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3400 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3401 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3402 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3403 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3404 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3406 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3407 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3408 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3409 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3410 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3411 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3415 fn invalid_first_hop_test() {
3416 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3417 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3418 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3419 let scorer = ln_test_utils::TestScorer::new();
3420 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3421 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3423 // Simple route to 2 via 1
3425 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3427 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3428 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3429 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3430 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3431 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3432 } else { panic!(); }
3434 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3435 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3436 assert_eq!(route.paths[0].hops.len(), 2);
3440 fn htlc_minimum_test() {
3441 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3442 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3443 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3444 let scorer = ln_test_utils::TestScorer::new();
3445 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3446 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3448 // Simple route to 2 via 1
3450 // Disable other paths
3451 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3452 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3453 short_channel_id: 12,
3455 flags: 2, // to disable
3456 cltv_expiry_delta: 0,
3457 htlc_minimum_msat: 0,
3458 htlc_maximum_msat: MAX_VALUE_MSAT,
3460 fee_proportional_millionths: 0,
3461 excess_data: Vec::new()
3463 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3464 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3465 short_channel_id: 3,
3467 flags: 2, // to disable
3468 cltv_expiry_delta: 0,
3469 htlc_minimum_msat: 0,
3470 htlc_maximum_msat: MAX_VALUE_MSAT,
3472 fee_proportional_millionths: 0,
3473 excess_data: Vec::new()
3475 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3476 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3477 short_channel_id: 13,
3479 flags: 2, // to disable
3480 cltv_expiry_delta: 0,
3481 htlc_minimum_msat: 0,
3482 htlc_maximum_msat: MAX_VALUE_MSAT,
3484 fee_proportional_millionths: 0,
3485 excess_data: Vec::new()
3487 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3488 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3489 short_channel_id: 6,
3491 flags: 2, // to disable
3492 cltv_expiry_delta: 0,
3493 htlc_minimum_msat: 0,
3494 htlc_maximum_msat: MAX_VALUE_MSAT,
3496 fee_proportional_millionths: 0,
3497 excess_data: Vec::new()
3499 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3500 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3501 short_channel_id: 7,
3503 flags: 2, // to disable
3504 cltv_expiry_delta: 0,
3505 htlc_minimum_msat: 0,
3506 htlc_maximum_msat: MAX_VALUE_MSAT,
3508 fee_proportional_millionths: 0,
3509 excess_data: Vec::new()
3512 // Check against amount_to_transfer_over_msat.
3513 // Set minimal HTLC of 200_000_000 msat.
3514 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3515 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3516 short_channel_id: 2,
3519 cltv_expiry_delta: 0,
3520 htlc_minimum_msat: 200_000_000,
3521 htlc_maximum_msat: MAX_VALUE_MSAT,
3523 fee_proportional_millionths: 0,
3524 excess_data: Vec::new()
3527 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3529 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3530 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3531 short_channel_id: 4,
3534 cltv_expiry_delta: 0,
3535 htlc_minimum_msat: 0,
3536 htlc_maximum_msat: 199_999_999,
3538 fee_proportional_millionths: 0,
3539 excess_data: Vec::new()
3542 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3543 let route_params = RouteParameters::from_payment_params_and_value(
3544 payment_params, 199_999_999);
3545 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3546 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3547 &Default::default(), &random_seed_bytes) {
3548 assert_eq!(err, "Failed to find a path to the given destination");
3549 } else { panic!(); }
3551 // Lift the restriction on the first hop.
3552 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3553 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3554 short_channel_id: 2,
3557 cltv_expiry_delta: 0,
3558 htlc_minimum_msat: 0,
3559 htlc_maximum_msat: MAX_VALUE_MSAT,
3561 fee_proportional_millionths: 0,
3562 excess_data: Vec::new()
3565 // A payment above the minimum should pass
3566 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3567 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3568 assert_eq!(route.paths[0].hops.len(), 2);
3572 fn htlc_minimum_overpay_test() {
3573 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3574 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3575 let config = UserConfig::default();
3576 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3577 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3579 let scorer = ln_test_utils::TestScorer::new();
3580 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3581 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3583 // A route to node#2 via two paths.
3584 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3585 // Thus, they can't send 60 without overpaying.
3586 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3587 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3588 short_channel_id: 2,
3591 cltv_expiry_delta: 0,
3592 htlc_minimum_msat: 35_000,
3593 htlc_maximum_msat: 40_000,
3595 fee_proportional_millionths: 0,
3596 excess_data: Vec::new()
3598 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3599 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3600 short_channel_id: 12,
3603 cltv_expiry_delta: 0,
3604 htlc_minimum_msat: 35_000,
3605 htlc_maximum_msat: 40_000,
3607 fee_proportional_millionths: 0,
3608 excess_data: Vec::new()
3612 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3613 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3614 short_channel_id: 13,
3617 cltv_expiry_delta: 0,
3618 htlc_minimum_msat: 0,
3619 htlc_maximum_msat: MAX_VALUE_MSAT,
3621 fee_proportional_millionths: 0,
3622 excess_data: Vec::new()
3624 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3625 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3626 short_channel_id: 4,
3629 cltv_expiry_delta: 0,
3630 htlc_minimum_msat: 0,
3631 htlc_maximum_msat: MAX_VALUE_MSAT,
3633 fee_proportional_millionths: 0,
3634 excess_data: Vec::new()
3637 // Disable other paths
3638 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3639 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3640 short_channel_id: 1,
3642 flags: 2, // to disable
3643 cltv_expiry_delta: 0,
3644 htlc_minimum_msat: 0,
3645 htlc_maximum_msat: MAX_VALUE_MSAT,
3647 fee_proportional_millionths: 0,
3648 excess_data: Vec::new()
3651 let mut route_params = RouteParameters::from_payment_params_and_value(
3652 payment_params.clone(), 60_000);
3653 route_params.max_total_routing_fee_msat = Some(15_000);
3654 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3655 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3656 // Overpay fees to hit htlc_minimum_msat.
3657 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3658 // TODO: this could be better balanced to overpay 10k and not 15k.
3659 assert_eq!(overpaid_fees, 15_000);
3661 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3662 // while taking even more fee to match htlc_minimum_msat.
3663 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3664 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3665 short_channel_id: 12,
3668 cltv_expiry_delta: 0,
3669 htlc_minimum_msat: 65_000,
3670 htlc_maximum_msat: 80_000,
3672 fee_proportional_millionths: 0,
3673 excess_data: Vec::new()
3675 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3676 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3677 short_channel_id: 2,
3680 cltv_expiry_delta: 0,
3681 htlc_minimum_msat: 0,
3682 htlc_maximum_msat: MAX_VALUE_MSAT,
3684 fee_proportional_millionths: 0,
3685 excess_data: Vec::new()
3687 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3688 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3689 short_channel_id: 4,
3692 cltv_expiry_delta: 0,
3693 htlc_minimum_msat: 0,
3694 htlc_maximum_msat: MAX_VALUE_MSAT,
3696 fee_proportional_millionths: 100_000,
3697 excess_data: Vec::new()
3700 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3701 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3702 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3703 assert_eq!(route.paths.len(), 1);
3704 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3705 let fees = route.paths[0].hops[0].fee_msat;
3706 assert_eq!(fees, 5_000);
3708 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3709 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3710 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3711 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3712 // the other channel.
3713 assert_eq!(route.paths.len(), 1);
3714 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3715 let fees = route.paths[0].hops[0].fee_msat;
3716 assert_eq!(fees, 5_000);
3720 fn htlc_minimum_recipient_overpay_test() {
3721 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3722 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3723 let config = UserConfig::default();
3724 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3725 let scorer = ln_test_utils::TestScorer::new();
3726 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3727 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3729 // Route to node2 over a single path which requires overpaying the recipient themselves.
3731 // First disable all paths except the us -> node1 -> node2 path
3732 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3733 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3734 short_channel_id: 13,
3737 cltv_expiry_delta: 0,
3738 htlc_minimum_msat: 0,
3739 htlc_maximum_msat: 0,
3741 fee_proportional_millionths: 0,
3742 excess_data: Vec::new()
3745 // Set channel 4 to free but with a high htlc_minimum_msat
3746 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3747 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3748 short_channel_id: 4,
3751 cltv_expiry_delta: 0,
3752 htlc_minimum_msat: 15_000,
3753 htlc_maximum_msat: MAX_VALUE_MSAT,
3755 fee_proportional_millionths: 0,
3756 excess_data: Vec::new()
3759 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3760 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3761 // what we try to find a route for, so this test only just happens to work out to exactly
3763 let mut route_params = RouteParameters::from_payment_params_and_value(
3764 payment_params.clone(), 5_000);
3765 route_params.max_total_routing_fee_msat = Some(9_999);
3766 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3767 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3768 &Default::default(), &random_seed_bytes) {
3769 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3770 } else { panic!(); }
3772 let mut route_params = RouteParameters::from_payment_params_and_value(
3773 payment_params.clone(), 5_000);
3774 route_params.max_total_routing_fee_msat = Some(10_000);
3775 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3776 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3777 assert_eq!(route.get_total_fees(), 10_000);
3781 fn disable_channels_test() {
3782 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3783 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3784 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3785 let scorer = ln_test_utils::TestScorer::new();
3786 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3787 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3789 // // Disable channels 4 and 12 by flags=2
3790 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3791 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3792 short_channel_id: 4,
3794 flags: 2, // to disable
3795 cltv_expiry_delta: 0,
3796 htlc_minimum_msat: 0,
3797 htlc_maximum_msat: MAX_VALUE_MSAT,
3799 fee_proportional_millionths: 0,
3800 excess_data: Vec::new()
3802 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3803 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3804 short_channel_id: 12,
3806 flags: 2, // to disable
3807 cltv_expiry_delta: 0,
3808 htlc_minimum_msat: 0,
3809 htlc_maximum_msat: MAX_VALUE_MSAT,
3811 fee_proportional_millionths: 0,
3812 excess_data: Vec::new()
3815 // If all the channels require some features we don't understand, route should fail
3816 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3817 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3818 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3819 &Default::default(), &random_seed_bytes) {
3820 assert_eq!(err, "Failed to find a path to the given destination");
3821 } else { panic!(); }
3823 // If we specify a channel to node7, that overrides our local channel view and that gets used
3824 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3825 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3826 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3827 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3828 &Default::default(), &random_seed_bytes).unwrap();
3829 assert_eq!(route.paths[0].hops.len(), 2);
3831 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3832 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3833 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3834 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3835 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3836 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3838 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3839 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3840 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3841 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3842 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3843 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3847 fn disable_node_test() {
3848 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3849 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3850 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3851 let scorer = ln_test_utils::TestScorer::new();
3852 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3853 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3855 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3856 let mut unknown_features = NodeFeatures::empty();
3857 unknown_features.set_unknown_feature_required();
3858 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3859 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3860 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3862 // If all nodes require some features we don't understand, route should fail
3863 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3864 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3865 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3866 &Default::default(), &random_seed_bytes) {
3867 assert_eq!(err, "Failed to find a path to the given destination");
3868 } else { panic!(); }
3870 // If we specify a channel to node7, that overrides our local channel view and that gets used
3871 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3872 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3873 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3874 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3875 &Default::default(), &random_seed_bytes).unwrap();
3876 assert_eq!(route.paths[0].hops.len(), 2);
3878 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3879 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3880 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3881 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3882 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3883 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3885 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3886 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3887 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3888 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3889 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3890 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3892 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3893 // naively) assume that the user checked the feature bits on the invoice, which override
3894 // the node_announcement.
3898 fn our_chans_test() {
3899 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3900 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3901 let scorer = ln_test_utils::TestScorer::new();
3902 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3903 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3905 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3906 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3907 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3908 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3909 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3910 assert_eq!(route.paths[0].hops.len(), 3);
3912 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3913 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3914 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3915 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3916 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3917 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3919 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3920 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3921 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3922 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3923 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3924 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3926 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3927 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3928 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3929 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3930 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3931 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3933 // If we specify a channel to node7, that overrides our local channel view and that gets used
3934 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3935 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3936 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3937 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3938 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3939 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3940 &Default::default(), &random_seed_bytes).unwrap();
3941 assert_eq!(route.paths[0].hops.len(), 2);
3943 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3944 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3945 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3946 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3947 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3948 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3950 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3951 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3952 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3953 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3954 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3955 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3958 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3959 let zero_fees = RoutingFees {
3961 proportional_millionths: 0,
3963 vec![RouteHint(vec![RouteHintHop {
3964 src_node_id: nodes[3],
3965 short_channel_id: 8,
3967 cltv_expiry_delta: (8 << 4) | 1,
3968 htlc_minimum_msat: None,
3969 htlc_maximum_msat: None,
3971 ]), RouteHint(vec![RouteHintHop {
3972 src_node_id: nodes[4],
3973 short_channel_id: 9,
3976 proportional_millionths: 0,
3978 cltv_expiry_delta: (9 << 4) | 1,
3979 htlc_minimum_msat: None,
3980 htlc_maximum_msat: None,
3981 }]), RouteHint(vec![RouteHintHop {
3982 src_node_id: nodes[5],
3983 short_channel_id: 10,
3985 cltv_expiry_delta: (10 << 4) | 1,
3986 htlc_minimum_msat: None,
3987 htlc_maximum_msat: None,
3991 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3992 let zero_fees = RoutingFees {
3994 proportional_millionths: 0,
3996 vec![RouteHint(vec![RouteHintHop {
3997 src_node_id: nodes[2],
3998 short_channel_id: 5,
4001 proportional_millionths: 0,
4003 cltv_expiry_delta: (5 << 4) | 1,
4004 htlc_minimum_msat: None,
4005 htlc_maximum_msat: None,
4007 src_node_id: nodes[3],
4008 short_channel_id: 8,
4010 cltv_expiry_delta: (8 << 4) | 1,
4011 htlc_minimum_msat: None,
4012 htlc_maximum_msat: None,
4014 ]), RouteHint(vec![RouteHintHop {
4015 src_node_id: nodes[4],
4016 short_channel_id: 9,
4019 proportional_millionths: 0,
4021 cltv_expiry_delta: (9 << 4) | 1,
4022 htlc_minimum_msat: None,
4023 htlc_maximum_msat: None,
4024 }]), RouteHint(vec![RouteHintHop {
4025 src_node_id: nodes[5],
4026 short_channel_id: 10,
4028 cltv_expiry_delta: (10 << 4) | 1,
4029 htlc_minimum_msat: None,
4030 htlc_maximum_msat: None,
4035 fn partial_route_hint_test() {
4036 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4037 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4038 let scorer = ln_test_utils::TestScorer::new();
4039 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4040 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4042 // Simple test across 2, 3, 5, and 4 via a last_hop channel
4043 // Tests the behaviour when the RouteHint contains a suboptimal hop.
4044 // RouteHint may be partially used by the algo to build the best path.
4046 // First check that last hop can't have its source as the payee.
4047 let invalid_last_hop = RouteHint(vec![RouteHintHop {
4048 src_node_id: nodes[6],
4049 short_channel_id: 8,
4052 proportional_millionths: 0,
4054 cltv_expiry_delta: (8 << 4) | 1,
4055 htlc_minimum_msat: None,
4056 htlc_maximum_msat: None,
4059 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
4060 invalid_last_hops.push(invalid_last_hop);
4062 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4063 .with_route_hints(invalid_last_hops).unwrap();
4064 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4065 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
4066 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
4067 &Default::default(), &random_seed_bytes) {
4068 assert_eq!(err, "Route hint cannot have the payee as the source.");
4069 } else { panic!(); }
4072 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4073 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
4074 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4075 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4076 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4077 assert_eq!(route.paths[0].hops.len(), 5);
4079 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4080 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4081 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4082 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4083 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4084 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4086 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4087 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4088 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4089 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4090 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4091 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4093 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4094 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4095 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4096 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4097 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4098 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4100 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4101 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4102 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4103 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4104 // If we have a peer in the node map, we'll use their features here since we don't have
4105 // a way of figuring out their features from the invoice:
4106 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4107 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4109 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4110 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4111 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4112 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4113 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4114 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4117 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4118 let zero_fees = RoutingFees {
4120 proportional_millionths: 0,
4122 vec![RouteHint(vec![RouteHintHop {
4123 src_node_id: nodes[3],
4124 short_channel_id: 8,
4126 cltv_expiry_delta: (8 << 4) | 1,
4127 htlc_minimum_msat: None,
4128 htlc_maximum_msat: None,
4129 }]), RouteHint(vec![
4131 ]), RouteHint(vec![RouteHintHop {
4132 src_node_id: nodes[5],
4133 short_channel_id: 10,
4135 cltv_expiry_delta: (10 << 4) | 1,
4136 htlc_minimum_msat: None,
4137 htlc_maximum_msat: None,
4142 fn ignores_empty_last_hops_test() {
4143 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4144 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4145 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
4146 let scorer = ln_test_utils::TestScorer::new();
4147 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4148 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4150 // Test handling of an empty RouteHint passed in Invoice.
4151 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4152 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4153 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4154 assert_eq!(route.paths[0].hops.len(), 5);
4156 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4157 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4158 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4159 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4160 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4161 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4163 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4164 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4165 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4166 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4167 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4168 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4170 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4171 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4172 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4173 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4174 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4175 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4177 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4178 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4179 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4180 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4181 // If we have a peer in the node map, we'll use their features here since we don't have
4182 // a way of figuring out their features from the invoice:
4183 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4184 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4186 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4187 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4188 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4189 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4190 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4191 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4194 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
4196 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
4197 let zero_fees = RoutingFees {
4199 proportional_millionths: 0,
4201 vec![RouteHint(vec![RouteHintHop {
4202 src_node_id: hint_hops[0],
4203 short_channel_id: 0xff00,
4206 proportional_millionths: 0,
4208 cltv_expiry_delta: (5 << 4) | 1,
4209 htlc_minimum_msat: None,
4210 htlc_maximum_msat: None,
4212 src_node_id: hint_hops[1],
4213 short_channel_id: 0xff01,
4215 cltv_expiry_delta: (8 << 4) | 1,
4216 htlc_minimum_msat: None,
4217 htlc_maximum_msat: None,
4222 fn multi_hint_last_hops_test() {
4223 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4224 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4225 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
4226 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4227 let scorer = ln_test_utils::TestScorer::new();
4228 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4229 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4230 // Test through channels 2, 3, 0xff00, 0xff01.
4231 // Test shows that multiple hop hints are considered.
4233 // Disabling channels 6 & 7 by flags=2
4234 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4235 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4236 short_channel_id: 6,
4238 flags: 2, // to disable
4239 cltv_expiry_delta: 0,
4240 htlc_minimum_msat: 0,
4241 htlc_maximum_msat: MAX_VALUE_MSAT,
4243 fee_proportional_millionths: 0,
4244 excess_data: Vec::new()
4246 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4247 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4248 short_channel_id: 7,
4250 flags: 2, // to disable
4251 cltv_expiry_delta: 0,
4252 htlc_minimum_msat: 0,
4253 htlc_maximum_msat: MAX_VALUE_MSAT,
4255 fee_proportional_millionths: 0,
4256 excess_data: Vec::new()
4259 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4260 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4261 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4262 assert_eq!(route.paths[0].hops.len(), 4);
4264 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4265 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4266 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4267 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4268 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4269 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4271 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4272 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4273 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4274 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4275 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4276 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4278 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4279 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4280 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4281 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4282 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4283 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4285 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4286 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4287 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4288 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4289 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4290 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4294 fn private_multi_hint_last_hops_test() {
4295 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4296 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4298 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4299 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4301 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4302 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4303 let scorer = ln_test_utils::TestScorer::new();
4304 // Test through channels 2, 3, 0xff00, 0xff01.
4305 // Test shows that multiple hop hints are considered.
4307 // Disabling channels 6 & 7 by flags=2
4308 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4309 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4310 short_channel_id: 6,
4312 flags: 2, // to disable
4313 cltv_expiry_delta: 0,
4314 htlc_minimum_msat: 0,
4315 htlc_maximum_msat: MAX_VALUE_MSAT,
4317 fee_proportional_millionths: 0,
4318 excess_data: Vec::new()
4320 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4321 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4322 short_channel_id: 7,
4324 flags: 2, // to disable
4325 cltv_expiry_delta: 0,
4326 htlc_minimum_msat: 0,
4327 htlc_maximum_msat: MAX_VALUE_MSAT,
4329 fee_proportional_millionths: 0,
4330 excess_data: Vec::new()
4333 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4334 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4335 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4336 assert_eq!(route.paths[0].hops.len(), 4);
4338 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4339 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4340 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4341 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4342 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4343 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4345 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4346 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4347 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4348 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4349 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4350 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4352 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4353 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4354 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4355 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4356 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4357 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4359 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4360 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4361 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4362 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4363 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4364 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4367 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4368 let zero_fees = RoutingFees {
4370 proportional_millionths: 0,
4372 vec![RouteHint(vec![RouteHintHop {
4373 src_node_id: nodes[4],
4374 short_channel_id: 11,
4376 cltv_expiry_delta: (11 << 4) | 1,
4377 htlc_minimum_msat: None,
4378 htlc_maximum_msat: None,
4380 src_node_id: nodes[3],
4381 short_channel_id: 8,
4383 cltv_expiry_delta: (8 << 4) | 1,
4384 htlc_minimum_msat: None,
4385 htlc_maximum_msat: None,
4386 }]), RouteHint(vec![RouteHintHop {
4387 src_node_id: nodes[4],
4388 short_channel_id: 9,
4391 proportional_millionths: 0,
4393 cltv_expiry_delta: (9 << 4) | 1,
4394 htlc_minimum_msat: None,
4395 htlc_maximum_msat: None,
4396 }]), RouteHint(vec![RouteHintHop {
4397 src_node_id: nodes[5],
4398 short_channel_id: 10,
4400 cltv_expiry_delta: (10 << 4) | 1,
4401 htlc_minimum_msat: None,
4402 htlc_maximum_msat: None,
4407 fn last_hops_with_public_channel_test() {
4408 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4409 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4410 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4411 let scorer = ln_test_utils::TestScorer::new();
4412 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4413 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4414 // This test shows that public routes can be present in the invoice
4415 // which would be handled in the same manner.
4417 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4418 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4419 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4420 assert_eq!(route.paths[0].hops.len(), 5);
4422 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4423 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4424 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4425 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4426 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4427 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4429 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4430 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4431 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4432 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4433 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4434 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4436 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4437 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4438 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4439 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4440 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4441 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4443 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4444 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4445 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4446 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4447 // If we have a peer in the node map, we'll use their features here since we don't have
4448 // a way of figuring out their features from the invoice:
4449 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4450 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4452 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4453 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4454 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4455 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4456 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4457 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4461 fn our_chans_last_hop_connect_test() {
4462 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4463 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4464 let scorer = ln_test_utils::TestScorer::new();
4465 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4466 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4468 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4469 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4470 let mut last_hops = last_hops(&nodes);
4471 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4472 .with_route_hints(last_hops.clone()).unwrap();
4473 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4474 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4475 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4476 &Default::default(), &random_seed_bytes).unwrap();
4477 assert_eq!(route.paths[0].hops.len(), 2);
4479 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4480 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4481 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4482 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4483 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4484 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4486 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4487 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4488 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4489 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4490 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4491 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4493 last_hops[0].0[0].fees.base_msat = 1000;
4495 // Revert to via 6 as the fee on 8 goes up
4496 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4497 .with_route_hints(last_hops).unwrap();
4498 let route_params = RouteParameters::from_payment_params_and_value(
4499 payment_params.clone(), 100);
4500 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4501 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4502 assert_eq!(route.paths[0].hops.len(), 4);
4504 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4505 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4506 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4507 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4508 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4509 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4511 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4512 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4513 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4514 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4515 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4516 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4518 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4519 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4520 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4521 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4522 // If we have a peer in the node map, we'll use their features here since we don't have
4523 // a way of figuring out their features from the invoice:
4524 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4525 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4527 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4528 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4529 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4530 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4531 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4532 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4534 // ...but still use 8 for larger payments as 6 has a variable feerate
4535 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4536 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4537 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4538 assert_eq!(route.paths[0].hops.len(), 5);
4540 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4541 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4542 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4543 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4544 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4545 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4547 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4548 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4549 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4550 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4551 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4552 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4554 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4555 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4556 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4557 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4558 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4559 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4561 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4562 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4563 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4564 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4565 // If we have a peer in the node map, we'll use their features here since we don't have
4566 // a way of figuring out their features from the invoice:
4567 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4568 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4570 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4571 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4572 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4573 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4574 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4575 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4578 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> {
4579 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4580 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4581 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4583 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4584 let last_hops = RouteHint(vec![RouteHintHop {
4585 src_node_id: middle_node_id,
4586 short_channel_id: 8,
4589 proportional_millionths: last_hop_fee_prop,
4591 cltv_expiry_delta: (8 << 4) | 1,
4592 htlc_minimum_msat: None,
4593 htlc_maximum_msat: last_hop_htlc_max,
4595 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4596 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4597 let scorer = ln_test_utils::TestScorer::new();
4598 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4599 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4600 let logger = ln_test_utils::TestLogger::new();
4601 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4602 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4603 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4604 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4605 &random_seed_bytes);
4610 fn unannounced_path_test() {
4611 // We should be able to send a payment to a destination without any help of a routing graph
4612 // if we have a channel with a common counterparty that appears in the first and last hop
4614 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4616 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4617 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4618 assert_eq!(route.paths[0].hops.len(), 2);
4620 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4621 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4622 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4623 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4624 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4625 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4627 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4628 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4629 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4630 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4631 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4632 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4636 fn overflow_unannounced_path_test_liquidity_underflow() {
4637 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4638 // the last-hop had a fee which overflowed a u64, we'd panic.
4639 // This was due to us adding the first-hop from us unconditionally, causing us to think
4640 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4641 // In this test, we previously hit a subtraction underflow due to having less available
4642 // liquidity at the last hop than 0.
4643 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());
4647 fn overflow_unannounced_path_test_feerate_overflow() {
4648 // This tests for the same case as above, except instead of hitting a subtraction
4649 // underflow, we hit a case where the fee charged at a hop overflowed.
4650 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());
4654 fn available_amount_while_routing_test() {
4655 // Tests whether we choose the correct available channel amount while routing.
4657 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4658 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4659 let scorer = ln_test_utils::TestScorer::new();
4660 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4661 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4662 let config = UserConfig::default();
4663 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4664 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4667 // We will use a simple single-path route from
4668 // our node to node2 via node0: channels {1, 3}.
4670 // First disable all other paths.
4671 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4672 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4673 short_channel_id: 2,
4676 cltv_expiry_delta: 0,
4677 htlc_minimum_msat: 0,
4678 htlc_maximum_msat: 100_000,
4680 fee_proportional_millionths: 0,
4681 excess_data: Vec::new()
4683 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4684 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4685 short_channel_id: 12,
4688 cltv_expiry_delta: 0,
4689 htlc_minimum_msat: 0,
4690 htlc_maximum_msat: 100_000,
4692 fee_proportional_millionths: 0,
4693 excess_data: Vec::new()
4696 // Make the first channel (#1) very permissive,
4697 // and we will be testing all limits on the second channel.
4698 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4699 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4700 short_channel_id: 1,
4703 cltv_expiry_delta: 0,
4704 htlc_minimum_msat: 0,
4705 htlc_maximum_msat: 1_000_000_000,
4707 fee_proportional_millionths: 0,
4708 excess_data: Vec::new()
4711 // First, let's see if routing works if we have absolutely no idea about the available amount.
4712 // In this case, it should be set to 250_000 sats.
4713 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4714 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4715 short_channel_id: 3,
4718 cltv_expiry_delta: 0,
4719 htlc_minimum_msat: 0,
4720 htlc_maximum_msat: 250_000_000,
4722 fee_proportional_millionths: 0,
4723 excess_data: Vec::new()
4727 // Attempt to route more than available results in a failure.
4728 let route_params = RouteParameters::from_payment_params_and_value(
4729 payment_params.clone(), 250_000_001);
4730 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4731 &our_id, &route_params, &network_graph.read_only(), None,
4732 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4733 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4734 } else { panic!(); }
4738 // Now, attempt to route an exact amount we have should be fine.
4739 let route_params = RouteParameters::from_payment_params_and_value(
4740 payment_params.clone(), 250_000_000);
4741 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4742 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4743 assert_eq!(route.paths.len(), 1);
4744 let path = route.paths.last().unwrap();
4745 assert_eq!(path.hops.len(), 2);
4746 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4747 assert_eq!(path.final_value_msat(), 250_000_000);
4750 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4751 // Disable channel #1 and use another first hop.
4752 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4753 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4754 short_channel_id: 1,
4757 cltv_expiry_delta: 0,
4758 htlc_minimum_msat: 0,
4759 htlc_maximum_msat: 1_000_000_000,
4761 fee_proportional_millionths: 0,
4762 excess_data: Vec::new()
4765 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4766 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4769 // Attempt to route more than available results in a failure.
4770 let route_params = RouteParameters::from_payment_params_and_value(
4771 payment_params.clone(), 200_000_001);
4772 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4773 &our_id, &route_params, &network_graph.read_only(),
4774 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4775 &Default::default(), &random_seed_bytes) {
4776 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4777 } else { panic!(); }
4781 // Now, attempt to route an exact amount we have should be fine.
4782 let route_params = RouteParameters::from_payment_params_and_value(
4783 payment_params.clone(), 200_000_000);
4784 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4785 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4786 &Default::default(), &random_seed_bytes).unwrap();
4787 assert_eq!(route.paths.len(), 1);
4788 let path = route.paths.last().unwrap();
4789 assert_eq!(path.hops.len(), 2);
4790 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4791 assert_eq!(path.final_value_msat(), 200_000_000);
4794 // Enable channel #1 back.
4795 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4796 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4797 short_channel_id: 1,
4800 cltv_expiry_delta: 0,
4801 htlc_minimum_msat: 0,
4802 htlc_maximum_msat: 1_000_000_000,
4804 fee_proportional_millionths: 0,
4805 excess_data: Vec::new()
4809 // Now let's see if routing works if we know only htlc_maximum_msat.
4810 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4811 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4812 short_channel_id: 3,
4815 cltv_expiry_delta: 0,
4816 htlc_minimum_msat: 0,
4817 htlc_maximum_msat: 15_000,
4819 fee_proportional_millionths: 0,
4820 excess_data: Vec::new()
4824 // Attempt to route more than available results in a failure.
4825 let route_params = RouteParameters::from_payment_params_and_value(
4826 payment_params.clone(), 15_001);
4827 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4828 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4829 &scorer, &Default::default(), &random_seed_bytes) {
4830 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4831 } else { panic!(); }
4835 // Now, attempt to route an exact amount we have should be fine.
4836 let route_params = RouteParameters::from_payment_params_and_value(
4837 payment_params.clone(), 15_000);
4838 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4839 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4840 assert_eq!(route.paths.len(), 1);
4841 let path = route.paths.last().unwrap();
4842 assert_eq!(path.hops.len(), 2);
4843 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4844 assert_eq!(path.final_value_msat(), 15_000);
4847 // Now let's see if routing works if we know only capacity from the UTXO.
4849 // We can't change UTXO capacity on the fly, so we'll disable
4850 // the existing channel and add another one with the capacity we need.
4851 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4852 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4853 short_channel_id: 3,
4856 cltv_expiry_delta: 0,
4857 htlc_minimum_msat: 0,
4858 htlc_maximum_msat: MAX_VALUE_MSAT,
4860 fee_proportional_millionths: 0,
4861 excess_data: Vec::new()
4864 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4865 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4866 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4867 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4868 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4870 *chain_monitor.utxo_ret.lock().unwrap() =
4871 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4872 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4874 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4875 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4876 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4877 short_channel_id: 333,
4880 cltv_expiry_delta: (3 << 4) | 1,
4881 htlc_minimum_msat: 0,
4882 htlc_maximum_msat: 15_000,
4884 fee_proportional_millionths: 0,
4885 excess_data: Vec::new()
4887 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4888 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4889 short_channel_id: 333,
4892 cltv_expiry_delta: (3 << 4) | 2,
4893 htlc_minimum_msat: 0,
4894 htlc_maximum_msat: 15_000,
4896 fee_proportional_millionths: 0,
4897 excess_data: Vec::new()
4901 // Attempt to route more than available results in a failure.
4902 let route_params = RouteParameters::from_payment_params_and_value(
4903 payment_params.clone(), 15_001);
4904 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4905 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4906 &scorer, &Default::default(), &random_seed_bytes) {
4907 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4908 } else { panic!(); }
4912 // Now, attempt to route an exact amount we have should be fine.
4913 let route_params = RouteParameters::from_payment_params_and_value(
4914 payment_params.clone(), 15_000);
4915 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4916 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4917 assert_eq!(route.paths.len(), 1);
4918 let path = route.paths.last().unwrap();
4919 assert_eq!(path.hops.len(), 2);
4920 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4921 assert_eq!(path.final_value_msat(), 15_000);
4924 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4925 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4926 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4927 short_channel_id: 333,
4930 cltv_expiry_delta: 0,
4931 htlc_minimum_msat: 0,
4932 htlc_maximum_msat: 10_000,
4934 fee_proportional_millionths: 0,
4935 excess_data: Vec::new()
4939 // Attempt to route more than available results in a failure.
4940 let route_params = RouteParameters::from_payment_params_and_value(
4941 payment_params.clone(), 10_001);
4942 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4943 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4944 &scorer, &Default::default(), &random_seed_bytes) {
4945 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4946 } else { panic!(); }
4950 // Now, attempt to route an exact amount we have should be fine.
4951 let route_params = RouteParameters::from_payment_params_and_value(
4952 payment_params.clone(), 10_000);
4953 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4954 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4955 assert_eq!(route.paths.len(), 1);
4956 let path = route.paths.last().unwrap();
4957 assert_eq!(path.hops.len(), 2);
4958 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4959 assert_eq!(path.final_value_msat(), 10_000);
4964 fn available_liquidity_last_hop_test() {
4965 // Check that available liquidity properly limits the path even when only
4966 // one of the latter hops is limited.
4967 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4968 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4969 let scorer = ln_test_utils::TestScorer::new();
4970 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4971 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4972 let config = UserConfig::default();
4973 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4974 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4977 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4978 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4979 // Total capacity: 50 sats.
4981 // Disable other potential paths.
4982 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4983 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4984 short_channel_id: 2,
4987 cltv_expiry_delta: 0,
4988 htlc_minimum_msat: 0,
4989 htlc_maximum_msat: 100_000,
4991 fee_proportional_millionths: 0,
4992 excess_data: Vec::new()
4994 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4995 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4996 short_channel_id: 7,
4999 cltv_expiry_delta: 0,
5000 htlc_minimum_msat: 0,
5001 htlc_maximum_msat: 100_000,
5003 fee_proportional_millionths: 0,
5004 excess_data: Vec::new()
5009 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5010 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5011 short_channel_id: 12,
5014 cltv_expiry_delta: 0,
5015 htlc_minimum_msat: 0,
5016 htlc_maximum_msat: 100_000,
5018 fee_proportional_millionths: 0,
5019 excess_data: Vec::new()
5021 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5022 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5023 short_channel_id: 13,
5026 cltv_expiry_delta: 0,
5027 htlc_minimum_msat: 0,
5028 htlc_maximum_msat: 100_000,
5030 fee_proportional_millionths: 0,
5031 excess_data: Vec::new()
5034 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5035 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5036 short_channel_id: 6,
5039 cltv_expiry_delta: 0,
5040 htlc_minimum_msat: 0,
5041 htlc_maximum_msat: 50_000,
5043 fee_proportional_millionths: 0,
5044 excess_data: Vec::new()
5046 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5047 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5048 short_channel_id: 11,
5051 cltv_expiry_delta: 0,
5052 htlc_minimum_msat: 0,
5053 htlc_maximum_msat: 100_000,
5055 fee_proportional_millionths: 0,
5056 excess_data: Vec::new()
5059 // Attempt to route more than available results in a failure.
5060 let route_params = RouteParameters::from_payment_params_and_value(
5061 payment_params.clone(), 60_000);
5062 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5063 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5064 &scorer, &Default::default(), &random_seed_bytes) {
5065 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5066 } else { panic!(); }
5070 // Now, attempt to route 49 sats (just a bit below the capacity).
5071 let route_params = RouteParameters::from_payment_params_and_value(
5072 payment_params.clone(), 49_000);
5073 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5074 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5075 assert_eq!(route.paths.len(), 1);
5076 let mut total_amount_paid_msat = 0;
5077 for path in &route.paths {
5078 assert_eq!(path.hops.len(), 4);
5079 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5080 total_amount_paid_msat += path.final_value_msat();
5082 assert_eq!(total_amount_paid_msat, 49_000);
5086 // Attempt to route an exact amount is also fine
5087 let route_params = RouteParameters::from_payment_params_and_value(
5088 payment_params, 50_000);
5089 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5090 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5091 assert_eq!(route.paths.len(), 1);
5092 let mut total_amount_paid_msat = 0;
5093 for path in &route.paths {
5094 assert_eq!(path.hops.len(), 4);
5095 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5096 total_amount_paid_msat += path.final_value_msat();
5098 assert_eq!(total_amount_paid_msat, 50_000);
5103 fn ignore_fee_first_hop_test() {
5104 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5105 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5106 let scorer = ln_test_utils::TestScorer::new();
5107 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5108 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5109 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5111 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5112 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5113 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5114 short_channel_id: 1,
5117 cltv_expiry_delta: 0,
5118 htlc_minimum_msat: 0,
5119 htlc_maximum_msat: 100_000,
5120 fee_base_msat: 1_000_000,
5121 fee_proportional_millionths: 0,
5122 excess_data: Vec::new()
5124 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5125 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5126 short_channel_id: 3,
5129 cltv_expiry_delta: 0,
5130 htlc_minimum_msat: 0,
5131 htlc_maximum_msat: 50_000,
5133 fee_proportional_millionths: 0,
5134 excess_data: Vec::new()
5138 let route_params = RouteParameters::from_payment_params_and_value(
5139 payment_params, 50_000);
5140 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5141 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5142 assert_eq!(route.paths.len(), 1);
5143 let mut total_amount_paid_msat = 0;
5144 for path in &route.paths {
5145 assert_eq!(path.hops.len(), 2);
5146 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5147 total_amount_paid_msat += path.final_value_msat();
5149 assert_eq!(total_amount_paid_msat, 50_000);
5154 fn simple_mpp_route_test() {
5155 let (secp_ctx, _, _, _, _) = build_graph();
5156 let (_, _, _, nodes) = get_nodes(&secp_ctx);
5157 let config = UserConfig::default();
5158 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5159 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5161 do_simple_mpp_route_test(clear_payment_params);
5163 // MPP to a 1-hop blinded path for nodes[2]
5164 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
5165 let blinded_path = BlindedPath {
5166 introduction_node_id: nodes[2],
5167 blinding_point: ln_test_utils::pubkey(42),
5168 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
5170 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
5172 fee_proportional_millionths: 0,
5173 htlc_minimum_msat: 0,
5174 htlc_maximum_msat: 0,
5175 cltv_expiry_delta: 0,
5176 features: BlindedHopFeatures::empty(),
5178 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
5179 .with_bolt12_features(bolt12_features.clone()).unwrap();
5180 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
5182 // MPP to 3 2-hop blinded paths
5183 let mut blinded_path_node_0 = blinded_path.clone();
5184 blinded_path_node_0.introduction_node_id = nodes[0];
5185 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
5186 let mut node_0_payinfo = blinded_payinfo.clone();
5187 node_0_payinfo.htlc_maximum_msat = 50_000;
5189 let mut blinded_path_node_7 = blinded_path_node_0.clone();
5190 blinded_path_node_7.introduction_node_id = nodes[7];
5191 let mut node_7_payinfo = blinded_payinfo.clone();
5192 node_7_payinfo.htlc_maximum_msat = 60_000;
5194 let mut blinded_path_node_1 = blinded_path_node_0.clone();
5195 blinded_path_node_1.introduction_node_id = nodes[1];
5196 let mut node_1_payinfo = blinded_payinfo.clone();
5197 node_1_payinfo.htlc_maximum_msat = 180_000;
5199 let two_hop_blinded_payment_params = PaymentParameters::blinded(
5201 (node_0_payinfo, blinded_path_node_0),
5202 (node_7_payinfo, blinded_path_node_7),
5203 (node_1_payinfo, blinded_path_node_1)
5205 .with_bolt12_features(bolt12_features).unwrap();
5206 do_simple_mpp_route_test(two_hop_blinded_payment_params);
5210 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
5211 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5212 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5213 let scorer = ln_test_utils::TestScorer::new();
5214 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5215 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5217 // We need a route consisting of 3 paths:
5218 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5219 // To achieve this, the amount being transferred should be around
5220 // the total capacity of these 3 paths.
5222 // First, we set limits on these (previously unlimited) channels.
5223 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
5225 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5226 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5227 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5228 short_channel_id: 1,
5231 cltv_expiry_delta: 0,
5232 htlc_minimum_msat: 0,
5233 htlc_maximum_msat: 100_000,
5235 fee_proportional_millionths: 0,
5236 excess_data: Vec::new()
5238 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5239 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5240 short_channel_id: 3,
5243 cltv_expiry_delta: 0,
5244 htlc_minimum_msat: 0,
5245 htlc_maximum_msat: 50_000,
5247 fee_proportional_millionths: 0,
5248 excess_data: Vec::new()
5251 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
5252 // (total limit 60).
5253 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5254 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5255 short_channel_id: 12,
5258 cltv_expiry_delta: 0,
5259 htlc_minimum_msat: 0,
5260 htlc_maximum_msat: 60_000,
5262 fee_proportional_millionths: 0,
5263 excess_data: Vec::new()
5265 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5266 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5267 short_channel_id: 13,
5270 cltv_expiry_delta: 0,
5271 htlc_minimum_msat: 0,
5272 htlc_maximum_msat: 60_000,
5274 fee_proportional_millionths: 0,
5275 excess_data: Vec::new()
5278 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5279 // (total capacity 180 sats).
5280 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5281 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5282 short_channel_id: 2,
5285 cltv_expiry_delta: 0,
5286 htlc_minimum_msat: 0,
5287 htlc_maximum_msat: 200_000,
5289 fee_proportional_millionths: 0,
5290 excess_data: Vec::new()
5292 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5293 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5294 short_channel_id: 4,
5297 cltv_expiry_delta: 0,
5298 htlc_minimum_msat: 0,
5299 htlc_maximum_msat: 180_000,
5301 fee_proportional_millionths: 0,
5302 excess_data: Vec::new()
5306 // Attempt to route more than available results in a failure.
5307 let route_params = RouteParameters::from_payment_params_and_value(
5308 payment_params.clone(), 300_000);
5309 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5310 &our_id, &route_params, &network_graph.read_only(), None,
5311 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5312 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5313 } else { panic!(); }
5317 // Attempt to route while setting max_path_count to 0 results in a failure.
5318 let zero_payment_params = payment_params.clone().with_max_path_count(0);
5319 let route_params = RouteParameters::from_payment_params_and_value(
5320 zero_payment_params, 100);
5321 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5322 &our_id, &route_params, &network_graph.read_only(), None,
5323 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5324 assert_eq!(err, "Can't find a route with no paths allowed.");
5325 } else { panic!(); }
5329 // Attempt to route while setting max_path_count to 3 results in a failure.
5330 // This is the case because the minimal_value_contribution_msat would require each path
5331 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5332 let fail_payment_params = payment_params.clone().with_max_path_count(3);
5333 let route_params = RouteParameters::from_payment_params_and_value(
5334 fail_payment_params, 250_000);
5335 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5336 &our_id, &route_params, &network_graph.read_only(), None,
5337 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5338 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5339 } else { panic!(); }
5343 // Now, attempt to route 250 sats (just a bit below the capacity).
5344 // Our algorithm should provide us with these 3 paths.
5345 let route_params = RouteParameters::from_payment_params_and_value(
5346 payment_params.clone(), 250_000);
5347 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5348 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5349 assert_eq!(route.paths.len(), 3);
5350 let mut total_amount_paid_msat = 0;
5351 for path in &route.paths {
5352 if let Some(bt) = &path.blinded_tail {
5353 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5355 assert_eq!(path.hops.len(), 2);
5356 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5358 total_amount_paid_msat += path.final_value_msat();
5360 assert_eq!(total_amount_paid_msat, 250_000);
5364 // Attempt to route an exact amount is also fine
5365 let route_params = RouteParameters::from_payment_params_and_value(
5366 payment_params.clone(), 290_000);
5367 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5368 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5369 assert_eq!(route.paths.len(), 3);
5370 let mut total_amount_paid_msat = 0;
5371 for path in &route.paths {
5372 if payment_params.payee.blinded_route_hints().len() != 0 {
5373 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5374 if let Some(bt) = &path.blinded_tail {
5375 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5376 if bt.hops.len() > 1 {
5377 assert_eq!(path.hops.last().unwrap().pubkey,
5378 payment_params.payee.blinded_route_hints().iter()
5379 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5380 .map(|(_, p)| p.introduction_node_id).unwrap());
5382 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5385 assert_eq!(path.hops.len(), 2);
5386 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5388 total_amount_paid_msat += path.final_value_msat();
5390 assert_eq!(total_amount_paid_msat, 290_000);
5395 fn long_mpp_route_test() {
5396 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5397 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5398 let scorer = ln_test_utils::TestScorer::new();
5399 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5400 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5401 let config = UserConfig::default();
5402 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5403 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5406 // We need a route consisting of 3 paths:
5407 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5408 // Note that these paths overlap (channels 5, 12, 13).
5409 // We will route 300 sats.
5410 // Each path will have 100 sats capacity, those channels which
5411 // are used twice will have 200 sats capacity.
5413 // Disable other potential paths.
5414 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5415 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5416 short_channel_id: 2,
5419 cltv_expiry_delta: 0,
5420 htlc_minimum_msat: 0,
5421 htlc_maximum_msat: 100_000,
5423 fee_proportional_millionths: 0,
5424 excess_data: Vec::new()
5426 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5427 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5428 short_channel_id: 7,
5431 cltv_expiry_delta: 0,
5432 htlc_minimum_msat: 0,
5433 htlc_maximum_msat: 100_000,
5435 fee_proportional_millionths: 0,
5436 excess_data: Vec::new()
5439 // Path via {node0, node2} is channels {1, 3, 5}.
5440 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5441 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5442 short_channel_id: 1,
5445 cltv_expiry_delta: 0,
5446 htlc_minimum_msat: 0,
5447 htlc_maximum_msat: 100_000,
5449 fee_proportional_millionths: 0,
5450 excess_data: Vec::new()
5452 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5453 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5454 short_channel_id: 3,
5457 cltv_expiry_delta: 0,
5458 htlc_minimum_msat: 0,
5459 htlc_maximum_msat: 100_000,
5461 fee_proportional_millionths: 0,
5462 excess_data: Vec::new()
5465 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5466 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5467 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5468 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5469 short_channel_id: 5,
5472 cltv_expiry_delta: 0,
5473 htlc_minimum_msat: 0,
5474 htlc_maximum_msat: 200_000,
5476 fee_proportional_millionths: 0,
5477 excess_data: Vec::new()
5480 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5481 // Add 100 sats to the capacities of {12, 13}, because these channels
5482 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5483 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5484 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5485 short_channel_id: 12,
5488 cltv_expiry_delta: 0,
5489 htlc_minimum_msat: 0,
5490 htlc_maximum_msat: 200_000,
5492 fee_proportional_millionths: 0,
5493 excess_data: Vec::new()
5495 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5496 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5497 short_channel_id: 13,
5500 cltv_expiry_delta: 0,
5501 htlc_minimum_msat: 0,
5502 htlc_maximum_msat: 200_000,
5504 fee_proportional_millionths: 0,
5505 excess_data: Vec::new()
5508 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5509 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5510 short_channel_id: 6,
5513 cltv_expiry_delta: 0,
5514 htlc_minimum_msat: 0,
5515 htlc_maximum_msat: 100_000,
5517 fee_proportional_millionths: 0,
5518 excess_data: Vec::new()
5520 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5521 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5522 short_channel_id: 11,
5525 cltv_expiry_delta: 0,
5526 htlc_minimum_msat: 0,
5527 htlc_maximum_msat: 100_000,
5529 fee_proportional_millionths: 0,
5530 excess_data: Vec::new()
5533 // Path via {node7, node2} is channels {12, 13, 5}.
5534 // We already limited them to 200 sats (they are used twice for 100 sats).
5535 // Nothing to do here.
5538 // Attempt to route more than available results in a failure.
5539 let route_params = RouteParameters::from_payment_params_and_value(
5540 payment_params.clone(), 350_000);
5541 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5542 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5543 &scorer, &Default::default(), &random_seed_bytes) {
5544 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5545 } else { panic!(); }
5549 // Now, attempt to route 300 sats (exact amount we can route).
5550 // Our algorithm should provide us with these 3 paths, 100 sats each.
5551 let route_params = RouteParameters::from_payment_params_and_value(
5552 payment_params, 300_000);
5553 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5554 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5555 assert_eq!(route.paths.len(), 3);
5557 let mut total_amount_paid_msat = 0;
5558 for path in &route.paths {
5559 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5560 total_amount_paid_msat += path.final_value_msat();
5562 assert_eq!(total_amount_paid_msat, 300_000);
5568 fn mpp_cheaper_route_test() {
5569 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5570 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5571 let scorer = ln_test_utils::TestScorer::new();
5572 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5573 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5574 let config = UserConfig::default();
5575 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5576 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5579 // This test checks that if we have two cheaper paths and one more expensive path,
5580 // so that liquidity-wise any 2 of 3 combination is sufficient,
5581 // two cheaper paths will be taken.
5582 // These paths have equal available liquidity.
5584 // We need a combination of 3 paths:
5585 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5586 // Note that these paths overlap (channels 5, 12, 13).
5587 // Each path will have 100 sats capacity, those channels which
5588 // are used twice will have 200 sats capacity.
5590 // Disable other potential paths.
5591 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5592 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5593 short_channel_id: 2,
5596 cltv_expiry_delta: 0,
5597 htlc_minimum_msat: 0,
5598 htlc_maximum_msat: 100_000,
5600 fee_proportional_millionths: 0,
5601 excess_data: Vec::new()
5603 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5604 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5605 short_channel_id: 7,
5608 cltv_expiry_delta: 0,
5609 htlc_minimum_msat: 0,
5610 htlc_maximum_msat: 100_000,
5612 fee_proportional_millionths: 0,
5613 excess_data: Vec::new()
5616 // Path via {node0, node2} is channels {1, 3, 5}.
5617 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5618 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5619 short_channel_id: 1,
5622 cltv_expiry_delta: 0,
5623 htlc_minimum_msat: 0,
5624 htlc_maximum_msat: 100_000,
5626 fee_proportional_millionths: 0,
5627 excess_data: Vec::new()
5629 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5630 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5631 short_channel_id: 3,
5634 cltv_expiry_delta: 0,
5635 htlc_minimum_msat: 0,
5636 htlc_maximum_msat: 100_000,
5638 fee_proportional_millionths: 0,
5639 excess_data: Vec::new()
5642 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5643 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5644 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5645 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5646 short_channel_id: 5,
5649 cltv_expiry_delta: 0,
5650 htlc_minimum_msat: 0,
5651 htlc_maximum_msat: 200_000,
5653 fee_proportional_millionths: 0,
5654 excess_data: Vec::new()
5657 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5658 // Add 100 sats to the capacities of {12, 13}, because these channels
5659 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5660 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5661 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5662 short_channel_id: 12,
5665 cltv_expiry_delta: 0,
5666 htlc_minimum_msat: 0,
5667 htlc_maximum_msat: 200_000,
5669 fee_proportional_millionths: 0,
5670 excess_data: Vec::new()
5672 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5673 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5674 short_channel_id: 13,
5677 cltv_expiry_delta: 0,
5678 htlc_minimum_msat: 0,
5679 htlc_maximum_msat: 200_000,
5681 fee_proportional_millionths: 0,
5682 excess_data: Vec::new()
5685 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5686 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5687 short_channel_id: 6,
5690 cltv_expiry_delta: 0,
5691 htlc_minimum_msat: 0,
5692 htlc_maximum_msat: 100_000,
5693 fee_base_msat: 1_000,
5694 fee_proportional_millionths: 0,
5695 excess_data: Vec::new()
5697 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5698 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5699 short_channel_id: 11,
5702 cltv_expiry_delta: 0,
5703 htlc_minimum_msat: 0,
5704 htlc_maximum_msat: 100_000,
5706 fee_proportional_millionths: 0,
5707 excess_data: Vec::new()
5710 // Path via {node7, node2} is channels {12, 13, 5}.
5711 // We already limited them to 200 sats (they are used twice for 100 sats).
5712 // Nothing to do here.
5715 // Now, attempt to route 180 sats.
5716 // Our algorithm should provide us with these 2 paths.
5717 let route_params = RouteParameters::from_payment_params_and_value(
5718 payment_params, 180_000);
5719 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5720 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5721 assert_eq!(route.paths.len(), 2);
5723 let mut total_value_transferred_msat = 0;
5724 let mut total_paid_msat = 0;
5725 for path in &route.paths {
5726 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5727 total_value_transferred_msat += path.final_value_msat();
5728 for hop in &path.hops {
5729 total_paid_msat += hop.fee_msat;
5732 // If we paid fee, this would be higher.
5733 assert_eq!(total_value_transferred_msat, 180_000);
5734 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5735 assert_eq!(total_fees_paid, 0);
5740 fn fees_on_mpp_route_test() {
5741 // This test makes sure that MPP algorithm properly takes into account
5742 // fees charged on the channels, by making the fees impactful:
5743 // if the fee is not properly accounted for, the behavior is different.
5744 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5745 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5746 let scorer = ln_test_utils::TestScorer::new();
5747 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5748 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5749 let config = UserConfig::default();
5750 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5751 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5754 // We need a route consisting of 2 paths:
5755 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5756 // We will route 200 sats, Each path will have 100 sats capacity.
5758 // This test is not particularly stable: e.g.,
5759 // there's a way to route via {node0, node2, node4}.
5760 // It works while pathfinding is deterministic, but can be broken otherwise.
5761 // It's fine to ignore this concern for now.
5763 // Disable other potential paths.
5764 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5765 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5766 short_channel_id: 2,
5769 cltv_expiry_delta: 0,
5770 htlc_minimum_msat: 0,
5771 htlc_maximum_msat: 100_000,
5773 fee_proportional_millionths: 0,
5774 excess_data: Vec::new()
5777 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5778 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5779 short_channel_id: 7,
5782 cltv_expiry_delta: 0,
5783 htlc_minimum_msat: 0,
5784 htlc_maximum_msat: 100_000,
5786 fee_proportional_millionths: 0,
5787 excess_data: Vec::new()
5790 // Path via {node0, node2} is channels {1, 3, 5}.
5791 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5792 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5793 short_channel_id: 1,
5796 cltv_expiry_delta: 0,
5797 htlc_minimum_msat: 0,
5798 htlc_maximum_msat: 100_000,
5800 fee_proportional_millionths: 0,
5801 excess_data: Vec::new()
5803 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5804 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5805 short_channel_id: 3,
5808 cltv_expiry_delta: 0,
5809 htlc_minimum_msat: 0,
5810 htlc_maximum_msat: 100_000,
5812 fee_proportional_millionths: 0,
5813 excess_data: Vec::new()
5816 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5817 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5818 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5819 short_channel_id: 5,
5822 cltv_expiry_delta: 0,
5823 htlc_minimum_msat: 0,
5824 htlc_maximum_msat: 100_000,
5826 fee_proportional_millionths: 0,
5827 excess_data: Vec::new()
5830 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5831 // All channels should be 100 sats capacity. But for the fee experiment,
5832 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5833 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5834 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5835 // so no matter how large are other channels,
5836 // the whole path will be limited by 100 sats with just these 2 conditions:
5837 // - channel 12 capacity is 250 sats
5838 // - fee for channel 6 is 150 sats
5839 // Let's test this by enforcing these 2 conditions and removing other limits.
5840 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5841 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5842 short_channel_id: 12,
5845 cltv_expiry_delta: 0,
5846 htlc_minimum_msat: 0,
5847 htlc_maximum_msat: 250_000,
5849 fee_proportional_millionths: 0,
5850 excess_data: Vec::new()
5852 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5853 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5854 short_channel_id: 13,
5857 cltv_expiry_delta: 0,
5858 htlc_minimum_msat: 0,
5859 htlc_maximum_msat: MAX_VALUE_MSAT,
5861 fee_proportional_millionths: 0,
5862 excess_data: Vec::new()
5865 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5866 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5867 short_channel_id: 6,
5870 cltv_expiry_delta: 0,
5871 htlc_minimum_msat: 0,
5872 htlc_maximum_msat: MAX_VALUE_MSAT,
5873 fee_base_msat: 150_000,
5874 fee_proportional_millionths: 0,
5875 excess_data: Vec::new()
5877 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5878 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5879 short_channel_id: 11,
5882 cltv_expiry_delta: 0,
5883 htlc_minimum_msat: 0,
5884 htlc_maximum_msat: MAX_VALUE_MSAT,
5886 fee_proportional_millionths: 0,
5887 excess_data: Vec::new()
5891 // Attempt to route more than available results in a failure.
5892 let route_params = RouteParameters::from_payment_params_and_value(
5893 payment_params.clone(), 210_000);
5894 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5895 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5896 &scorer, &Default::default(), &random_seed_bytes) {
5897 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5898 } else { panic!(); }
5902 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5903 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5904 max_total_routing_fee_msat: Some(149_999) };
5905 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5906 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5907 &scorer, &Default::default(), &random_seed_bytes) {
5908 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5909 } else { panic!(); }
5913 // Now, attempt to route 200 sats (exact amount we can route).
5914 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5915 max_total_routing_fee_msat: Some(150_000) };
5916 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5917 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5918 assert_eq!(route.paths.len(), 2);
5920 let mut total_amount_paid_msat = 0;
5921 for path in &route.paths {
5922 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5923 total_amount_paid_msat += path.final_value_msat();
5925 assert_eq!(total_amount_paid_msat, 200_000);
5926 assert_eq!(route.get_total_fees(), 150_000);
5931 fn mpp_with_last_hops() {
5932 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5933 // via a single last-hop route hint, we'd fail to route if we first collected routes
5934 // totaling close but not quite enough to fund the full payment.
5936 // This was because we considered last-hop hints to have exactly the sought payment amount
5937 // instead of the amount we were trying to collect, needlessly limiting our path searching
5938 // at the very first hop.
5940 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5941 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5942 // to only have the remaining to-collect amount in available liquidity.
5944 // This bug appeared in production in some specific channel configurations.
5945 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5946 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5947 let scorer = ln_test_utils::TestScorer::new();
5948 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5949 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5950 let config = UserConfig::default();
5951 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
5952 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
5953 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5954 src_node_id: nodes[2],
5955 short_channel_id: 42,
5956 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5957 cltv_expiry_delta: 42,
5958 htlc_minimum_msat: None,
5959 htlc_maximum_msat: None,
5960 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5962 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5963 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5964 // would first use the no-fee route and then fail to find a path along the second route as
5965 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5966 // under 5% of our payment amount.
5967 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5968 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5969 short_channel_id: 1,
5972 cltv_expiry_delta: (5 << 4) | 5,
5973 htlc_minimum_msat: 0,
5974 htlc_maximum_msat: 99_000,
5975 fee_base_msat: u32::max_value(),
5976 fee_proportional_millionths: u32::max_value(),
5977 excess_data: Vec::new()
5979 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5980 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5981 short_channel_id: 2,
5984 cltv_expiry_delta: (5 << 4) | 3,
5985 htlc_minimum_msat: 0,
5986 htlc_maximum_msat: 99_000,
5987 fee_base_msat: u32::max_value(),
5988 fee_proportional_millionths: u32::max_value(),
5989 excess_data: Vec::new()
5991 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5992 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5993 short_channel_id: 4,
5996 cltv_expiry_delta: (4 << 4) | 1,
5997 htlc_minimum_msat: 0,
5998 htlc_maximum_msat: MAX_VALUE_MSAT,
6000 fee_proportional_millionths: 0,
6001 excess_data: Vec::new()
6003 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6004 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6005 short_channel_id: 13,
6007 flags: 0|2, // Channel disabled
6008 cltv_expiry_delta: (13 << 4) | 1,
6009 htlc_minimum_msat: 0,
6010 htlc_maximum_msat: MAX_VALUE_MSAT,
6012 fee_proportional_millionths: 2000000,
6013 excess_data: Vec::new()
6016 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
6018 let route_params = RouteParameters::from_payment_params_and_value(
6019 payment_params, 100_000);
6020 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6021 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6022 assert_eq!(route.paths.len(), 2);
6023 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
6024 // Paths are manually ordered ordered by SCID, so:
6025 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
6026 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
6027 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
6028 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
6029 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
6030 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
6031 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
6032 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
6033 assert_eq!(route.get_total_fees(), 1);
6034 assert_eq!(route.get_total_amount(), 100_000);
6038 fn drop_lowest_channel_mpp_route_test() {
6039 // This test checks that low-capacity channel is dropped when after
6040 // path finding we realize that we found more capacity than we need.
6041 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6042 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6043 let scorer = ln_test_utils::TestScorer::new();
6044 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6045 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6046 let config = UserConfig::default();
6047 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6048 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6050 .with_max_channel_saturation_power_of_half(0);
6052 // We need a route consisting of 3 paths:
6053 // From our node to node2 via node0, node7, node1 (three paths one hop each).
6055 // The first and the second paths should be sufficient, but the third should be
6056 // cheaper, so that we select it but drop later.
6058 // First, we set limits on these (previously unlimited) channels.
6059 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
6061 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
6062 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6063 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6064 short_channel_id: 1,
6067 cltv_expiry_delta: 0,
6068 htlc_minimum_msat: 0,
6069 htlc_maximum_msat: 100_000,
6071 fee_proportional_millionths: 0,
6072 excess_data: Vec::new()
6074 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6075 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6076 short_channel_id: 3,
6079 cltv_expiry_delta: 0,
6080 htlc_minimum_msat: 0,
6081 htlc_maximum_msat: 50_000,
6083 fee_proportional_millionths: 0,
6084 excess_data: Vec::new()
6087 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
6088 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6089 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6090 short_channel_id: 12,
6093 cltv_expiry_delta: 0,
6094 htlc_minimum_msat: 0,
6095 htlc_maximum_msat: 60_000,
6097 fee_proportional_millionths: 0,
6098 excess_data: Vec::new()
6100 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6101 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6102 short_channel_id: 13,
6105 cltv_expiry_delta: 0,
6106 htlc_minimum_msat: 0,
6107 htlc_maximum_msat: 60_000,
6109 fee_proportional_millionths: 0,
6110 excess_data: Vec::new()
6113 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
6114 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6115 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6116 short_channel_id: 2,
6119 cltv_expiry_delta: 0,
6120 htlc_minimum_msat: 0,
6121 htlc_maximum_msat: 20_000,
6123 fee_proportional_millionths: 0,
6124 excess_data: Vec::new()
6126 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6127 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6128 short_channel_id: 4,
6131 cltv_expiry_delta: 0,
6132 htlc_minimum_msat: 0,
6133 htlc_maximum_msat: 20_000,
6135 fee_proportional_millionths: 0,
6136 excess_data: Vec::new()
6140 // Attempt to route more than available results in a failure.
6141 let route_params = RouteParameters::from_payment_params_and_value(
6142 payment_params.clone(), 150_000);
6143 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6144 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6145 &scorer, &Default::default(), &random_seed_bytes) {
6146 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6147 } else { panic!(); }
6151 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
6152 // Our algorithm should provide us with these 3 paths.
6153 let route_params = RouteParameters::from_payment_params_and_value(
6154 payment_params.clone(), 125_000);
6155 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6156 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6157 assert_eq!(route.paths.len(), 3);
6158 let mut total_amount_paid_msat = 0;
6159 for path in &route.paths {
6160 assert_eq!(path.hops.len(), 2);
6161 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6162 total_amount_paid_msat += path.final_value_msat();
6164 assert_eq!(total_amount_paid_msat, 125_000);
6168 // Attempt to route without the last small cheap channel
6169 let route_params = RouteParameters::from_payment_params_and_value(
6170 payment_params, 90_000);
6171 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6172 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6173 assert_eq!(route.paths.len(), 2);
6174 let mut total_amount_paid_msat = 0;
6175 for path in &route.paths {
6176 assert_eq!(path.hops.len(), 2);
6177 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6178 total_amount_paid_msat += path.final_value_msat();
6180 assert_eq!(total_amount_paid_msat, 90_000);
6185 fn min_criteria_consistency() {
6186 // Test that we don't use an inconsistent metric between updating and walking nodes during
6187 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
6188 // was updated with a different criterion from the heap sorting, resulting in loops in
6189 // calculated paths. We test for that specific case here.
6191 // We construct a network that looks like this:
6193 // node2 -1(3)2- node3
6197 // node1 -1(5)2- node4 -1(1)2- node6
6203 // We create a loop on the side of our real path - our destination is node 6, with a
6204 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
6205 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
6206 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
6207 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
6208 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
6209 // "previous hop" being set to node 3, creating a loop in the path.
6210 let secp_ctx = Secp256k1::new();
6211 let logger = Arc::new(ln_test_utils::TestLogger::new());
6212 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6213 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
6214 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6215 let scorer = ln_test_utils::TestScorer::new();
6216 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6217 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6218 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
6220 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
6221 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6222 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6223 short_channel_id: 6,
6226 cltv_expiry_delta: (6 << 4) | 0,
6227 htlc_minimum_msat: 0,
6228 htlc_maximum_msat: MAX_VALUE_MSAT,
6230 fee_proportional_millionths: 0,
6231 excess_data: Vec::new()
6233 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
6235 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6236 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6237 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6238 short_channel_id: 5,
6241 cltv_expiry_delta: (5 << 4) | 0,
6242 htlc_minimum_msat: 0,
6243 htlc_maximum_msat: MAX_VALUE_MSAT,
6245 fee_proportional_millionths: 0,
6246 excess_data: Vec::new()
6248 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
6250 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
6251 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6252 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6253 short_channel_id: 4,
6256 cltv_expiry_delta: (4 << 4) | 0,
6257 htlc_minimum_msat: 0,
6258 htlc_maximum_msat: MAX_VALUE_MSAT,
6260 fee_proportional_millionths: 0,
6261 excess_data: Vec::new()
6263 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6265 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6266 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
6267 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6268 short_channel_id: 3,
6271 cltv_expiry_delta: (3 << 4) | 0,
6272 htlc_minimum_msat: 0,
6273 htlc_maximum_msat: MAX_VALUE_MSAT,
6275 fee_proportional_millionths: 0,
6276 excess_data: Vec::new()
6278 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6280 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6281 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
6282 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6283 short_channel_id: 2,
6286 cltv_expiry_delta: (2 << 4) | 0,
6287 htlc_minimum_msat: 0,
6288 htlc_maximum_msat: MAX_VALUE_MSAT,
6290 fee_proportional_millionths: 0,
6291 excess_data: Vec::new()
6294 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6295 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6296 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6297 short_channel_id: 1,
6300 cltv_expiry_delta: (1 << 4) | 0,
6301 htlc_minimum_msat: 100,
6302 htlc_maximum_msat: MAX_VALUE_MSAT,
6304 fee_proportional_millionths: 0,
6305 excess_data: Vec::new()
6307 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6310 // Now ensure the route flows simply over nodes 1 and 4 to 6.
6311 let route_params = RouteParameters::from_payment_params_and_value(
6312 payment_params, 10_000);
6313 let route = get_route(&our_id, &route_params, &network.read_only(), None,
6314 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6315 assert_eq!(route.paths.len(), 1);
6316 assert_eq!(route.paths[0].hops.len(), 3);
6318 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6319 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6320 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6321 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6322 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6323 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6325 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6326 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6327 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6328 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6329 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6330 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6332 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6333 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6334 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6335 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6336 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6337 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6343 fn exact_fee_liquidity_limit() {
6344 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6345 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6346 // we calculated fees on a higher value, resulting in us ignoring such paths.
6347 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6348 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6349 let scorer = ln_test_utils::TestScorer::new();
6350 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6351 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6352 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6354 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6356 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6357 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6358 short_channel_id: 2,
6361 cltv_expiry_delta: 0,
6362 htlc_minimum_msat: 0,
6363 htlc_maximum_msat: 85_000,
6365 fee_proportional_millionths: 0,
6366 excess_data: Vec::new()
6369 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6370 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6371 short_channel_id: 12,
6374 cltv_expiry_delta: (4 << 4) | 1,
6375 htlc_minimum_msat: 0,
6376 htlc_maximum_msat: 270_000,
6378 fee_proportional_millionths: 1000000,
6379 excess_data: Vec::new()
6383 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6384 // 200% fee charged channel 13 in the 1-to-2 direction.
6385 let mut route_params = RouteParameters::from_payment_params_and_value(
6386 payment_params, 90_000);
6387 route_params.max_total_routing_fee_msat = Some(90_000*2);
6388 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6389 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6390 assert_eq!(route.paths.len(), 1);
6391 assert_eq!(route.paths[0].hops.len(), 2);
6393 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6394 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6395 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6396 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6397 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6398 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6400 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6401 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6402 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6403 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6404 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6405 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6410 fn htlc_max_reduction_below_min() {
6411 // Test that if, while walking the graph, we reduce the value being sent to meet an
6412 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6413 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6414 // resulting in us thinking there is no possible path, even if other paths exist.
6415 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6416 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6417 let scorer = ln_test_utils::TestScorer::new();
6418 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6419 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6420 let config = UserConfig::default();
6421 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6422 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6425 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6426 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6427 // then try to send 90_000.
6428 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6429 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6430 short_channel_id: 2,
6433 cltv_expiry_delta: 0,
6434 htlc_minimum_msat: 0,
6435 htlc_maximum_msat: 80_000,
6437 fee_proportional_millionths: 0,
6438 excess_data: Vec::new()
6440 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6441 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6442 short_channel_id: 4,
6445 cltv_expiry_delta: (4 << 4) | 1,
6446 htlc_minimum_msat: 90_000,
6447 htlc_maximum_msat: MAX_VALUE_MSAT,
6449 fee_proportional_millionths: 0,
6450 excess_data: Vec::new()
6454 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6455 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6456 // expensive) channels 12-13 path.
6457 let mut route_params = RouteParameters::from_payment_params_and_value(
6458 payment_params, 90_000);
6459 route_params.max_total_routing_fee_msat = Some(90_000*2);
6460 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6461 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6462 assert_eq!(route.paths.len(), 1);
6463 assert_eq!(route.paths[0].hops.len(), 2);
6465 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6466 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6467 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6468 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6469 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6470 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6472 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6473 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6474 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6475 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6476 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6477 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6482 fn multiple_direct_first_hops() {
6483 // Previously we'd only ever considered one first hop path per counterparty.
6484 // However, as we don't restrict users to one channel per peer, we really need to support
6485 // looking at all first hop paths.
6486 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6487 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6488 // route over multiple channels with the same first hop.
6489 let secp_ctx = Secp256k1::new();
6490 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6491 let logger = Arc::new(ln_test_utils::TestLogger::new());
6492 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6493 let scorer = ln_test_utils::TestScorer::new();
6494 let config = UserConfig::default();
6495 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6496 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6498 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6499 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6502 let route_params = RouteParameters::from_payment_params_and_value(
6503 payment_params.clone(), 100_000);
6504 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6505 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6506 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6507 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6508 assert_eq!(route.paths.len(), 1);
6509 assert_eq!(route.paths[0].hops.len(), 1);
6511 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6512 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6513 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6516 let route_params = RouteParameters::from_payment_params_and_value(
6517 payment_params.clone(), 100_000);
6518 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6519 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6520 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6521 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6522 assert_eq!(route.paths.len(), 2);
6523 assert_eq!(route.paths[0].hops.len(), 1);
6524 assert_eq!(route.paths[1].hops.len(), 1);
6526 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6527 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6529 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6530 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6532 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6533 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6537 // If we have a bunch of outbound channels to the same node, where most are not
6538 // sufficient to pay the full payment, but one is, we should default to just using the
6539 // one single channel that has sufficient balance, avoiding MPP.
6541 // If we have several options above the 3xpayment value threshold, we should pick the
6542 // smallest of them, avoiding further fragmenting our available outbound balance to
6544 let route_params = RouteParameters::from_payment_params_and_value(
6545 payment_params, 100_000);
6546 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6547 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6548 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6549 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6550 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6551 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6552 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6553 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6554 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6555 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6556 assert_eq!(route.paths.len(), 1);
6557 assert_eq!(route.paths[0].hops.len(), 1);
6559 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6560 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6561 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6566 fn prefers_shorter_route_with_higher_fees() {
6567 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6568 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6569 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6571 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6572 let scorer = ln_test_utils::TestScorer::new();
6573 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6574 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6575 let route_params = RouteParameters::from_payment_params_and_value(
6576 payment_params.clone(), 100);
6577 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6578 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6579 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6581 assert_eq!(route.get_total_fees(), 100);
6582 assert_eq!(route.get_total_amount(), 100);
6583 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6585 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6586 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6587 let scorer = FixedPenaltyScorer::with_penalty(100);
6588 let route_params = RouteParameters::from_payment_params_and_value(
6589 payment_params, 100);
6590 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6591 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6592 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6594 assert_eq!(route.get_total_fees(), 300);
6595 assert_eq!(route.get_total_amount(), 100);
6596 assert_eq!(path, vec![2, 4, 7, 10]);
6599 struct BadChannelScorer {
6600 short_channel_id: u64,
6604 impl Writeable for BadChannelScorer {
6605 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6607 impl ScoreLookUp for BadChannelScorer {
6608 type ScoreParams = ();
6609 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6610 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6614 struct BadNodeScorer {
6619 impl Writeable for BadNodeScorer {
6620 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6623 impl ScoreLookUp for BadNodeScorer {
6624 type ScoreParams = ();
6625 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6626 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6631 fn avoids_routing_through_bad_channels_and_nodes() {
6632 let (secp_ctx, network, _, _, logger) = build_graph();
6633 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6634 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6635 let network_graph = network.read_only();
6637 // A path to nodes[6] exists when no penalties are applied to any channel.
6638 let scorer = ln_test_utils::TestScorer::new();
6639 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6640 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6641 let route_params = RouteParameters::from_payment_params_and_value(
6642 payment_params, 100);
6643 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6644 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6645 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6647 assert_eq!(route.get_total_fees(), 100);
6648 assert_eq!(route.get_total_amount(), 100);
6649 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6651 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6652 let scorer = BadChannelScorer { short_channel_id: 6 };
6653 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6654 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6655 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6657 assert_eq!(route.get_total_fees(), 300);
6658 assert_eq!(route.get_total_amount(), 100);
6659 assert_eq!(path, vec![2, 4, 7, 10]);
6661 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6662 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6663 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6664 &scorer, &Default::default(), &random_seed_bytes) {
6665 Err(LightningError { err, .. } ) => {
6666 assert_eq!(err, "Failed to find a path to the given destination");
6668 Ok(_) => panic!("Expected error"),
6673 fn total_fees_single_path() {
6675 paths: vec![Path { hops: vec![
6677 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6678 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6679 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6682 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6683 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6684 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6687 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6688 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6689 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6691 ], blinded_tail: None }],
6695 assert_eq!(route.get_total_fees(), 250);
6696 assert_eq!(route.get_total_amount(), 225);
6700 fn total_fees_multi_path() {
6702 paths: vec![Path { hops: vec![
6704 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6705 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6706 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6709 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6710 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6711 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6713 ], blinded_tail: None }, Path { hops: vec![
6715 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6716 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6717 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6720 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6721 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6722 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6724 ], blinded_tail: None }],
6728 assert_eq!(route.get_total_fees(), 200);
6729 assert_eq!(route.get_total_amount(), 300);
6733 fn total_empty_route_no_panic() {
6734 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6735 // would both panic if the route was completely empty. We test to ensure they return 0
6736 // here, even though its somewhat nonsensical as a route.
6737 let route = Route { paths: Vec::new(), route_params: None };
6739 assert_eq!(route.get_total_fees(), 0);
6740 assert_eq!(route.get_total_amount(), 0);
6744 fn limits_total_cltv_delta() {
6745 let (secp_ctx, network, _, _, logger) = build_graph();
6746 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6747 let network_graph = network.read_only();
6749 let scorer = ln_test_utils::TestScorer::new();
6751 // Make sure that generally there is at least one route available
6752 let feasible_max_total_cltv_delta = 1008;
6753 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6754 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6755 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6756 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6757 let route_params = RouteParameters::from_payment_params_and_value(
6758 feasible_payment_params, 100);
6759 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6760 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6761 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6762 assert_ne!(path.len(), 0);
6764 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6765 let fail_max_total_cltv_delta = 23;
6766 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6767 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6768 let route_params = RouteParameters::from_payment_params_and_value(
6769 fail_payment_params, 100);
6770 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6771 &Default::default(), &random_seed_bytes)
6773 Err(LightningError { err, .. } ) => {
6774 assert_eq!(err, "Failed to find a path to the given destination");
6776 Ok(_) => panic!("Expected error"),
6781 fn avoids_recently_failed_paths() {
6782 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6783 // randomly inserting channels into it until we can't find a route anymore.
6784 let (secp_ctx, network, _, _, logger) = build_graph();
6785 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6786 let network_graph = network.read_only();
6788 let scorer = ln_test_utils::TestScorer::new();
6789 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6790 .with_max_path_count(1);
6791 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6792 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6794 // We should be able to find a route initially, and then after we fail a few random
6795 // channels eventually we won't be able to any longer.
6796 let route_params = RouteParameters::from_payment_params_and_value(
6797 payment_params.clone(), 100);
6798 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6799 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6801 let route_params = RouteParameters::from_payment_params_and_value(
6802 payment_params.clone(), 100);
6803 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6804 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6806 for chan in route.paths[0].hops.iter() {
6807 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6809 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6810 % route.paths[0].hops.len();
6811 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6817 fn limits_path_length() {
6818 let (secp_ctx, network, _, _, logger) = build_line_graph();
6819 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6820 let network_graph = network.read_only();
6822 let scorer = ln_test_utils::TestScorer::new();
6823 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6824 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6826 // First check we can actually create a long route on this graph.
6827 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6828 let route_params = RouteParameters::from_payment_params_and_value(
6829 feasible_payment_params, 100);
6830 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6831 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6832 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6833 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6835 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6836 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6837 let route_params = RouteParameters::from_payment_params_and_value(
6838 fail_payment_params, 100);
6839 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6840 &Default::default(), &random_seed_bytes)
6842 Err(LightningError { err, .. } ) => {
6843 assert_eq!(err, "Failed to find a path to the given destination");
6845 Ok(_) => panic!("Expected error"),
6850 fn adds_and_limits_cltv_offset() {
6851 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6852 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6854 let scorer = ln_test_utils::TestScorer::new();
6856 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6857 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6858 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6859 let route_params = RouteParameters::from_payment_params_and_value(
6860 payment_params.clone(), 100);
6861 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6862 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6863 assert_eq!(route.paths.len(), 1);
6865 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6867 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6868 let mut route_default = route.clone();
6869 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6870 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6871 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6872 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6873 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6875 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6876 let mut route_limited = route.clone();
6877 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6878 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6879 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6880 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6881 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6885 fn adds_plausible_cltv_offset() {
6886 let (secp_ctx, network, _, _, logger) = build_graph();
6887 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6888 let network_graph = network.read_only();
6889 let network_nodes = network_graph.nodes();
6890 let network_channels = network_graph.channels();
6891 let scorer = ln_test_utils::TestScorer::new();
6892 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6893 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6894 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6896 let route_params = RouteParameters::from_payment_params_and_value(
6897 payment_params.clone(), 100);
6898 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6899 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6900 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6902 let mut path_plausibility = vec![];
6904 for p in route.paths {
6905 // 1. Select random observation point
6906 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6907 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6909 prng.process_in_place(&mut random_bytes);
6910 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6911 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6913 // 2. Calculate what CLTV expiry delta we would observe there
6914 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6916 // 3. Starting from the observation point, find candidate paths
6917 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6918 candidates.push_back((observation_point, vec![]));
6920 let mut found_plausible_candidate = false;
6922 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6923 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6924 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6925 found_plausible_candidate = true;
6926 break 'candidate_loop;
6930 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6931 for channel_id in &cur_node.channels {
6932 if let Some(channel_info) = network_channels.get(&channel_id) {
6933 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6934 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6935 if cur_path_cltv_deltas.iter().sum::<u32>()
6936 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6937 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6938 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6939 candidates.push_back((*next_id, new_path_cltv_deltas));
6947 path_plausibility.push(found_plausible_candidate);
6949 assert!(path_plausibility.iter().all(|x| *x));
6953 fn builds_correct_path_from_hops() {
6954 let (secp_ctx, network, _, _, logger) = build_graph();
6955 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6956 let network_graph = network.read_only();
6958 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6959 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6961 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6962 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6963 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6964 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6965 Arc::clone(&logger), &random_seed_bytes).unwrap();
6966 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6967 assert_eq!(hops.len(), route.paths[0].hops.len());
6968 for (idx, hop_pubkey) in hops.iter().enumerate() {
6969 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6974 fn avoids_saturating_channels() {
6975 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6976 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6977 let decay_params = ProbabilisticScoringDecayParameters::default();
6978 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6980 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6981 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6982 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6983 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6984 short_channel_id: 4,
6987 cltv_expiry_delta: (4 << 4) | 1,
6988 htlc_minimum_msat: 0,
6989 htlc_maximum_msat: 250_000_000,
6991 fee_proportional_millionths: 0,
6992 excess_data: Vec::new()
6994 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6995 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6996 short_channel_id: 13,
6999 cltv_expiry_delta: (13 << 4) | 1,
7000 htlc_minimum_msat: 0,
7001 htlc_maximum_msat: 250_000_000,
7003 fee_proportional_millionths: 0,
7004 excess_data: Vec::new()
7007 let config = UserConfig::default();
7008 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
7009 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7011 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7012 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7013 // 100,000 sats is less than the available liquidity on each channel, set above.
7014 let route_params = RouteParameters::from_payment_params_and_value(
7015 payment_params, 100_000_000);
7016 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
7017 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
7018 assert_eq!(route.paths.len(), 2);
7019 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
7020 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
7023 #[cfg(not(feature = "no-std"))]
7024 pub(super) fn random_init_seed() -> u64 {
7025 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
7026 use core::hash::{BuildHasher, Hasher};
7027 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
7028 println!("Using seed of {}", seed);
7033 #[cfg(not(feature = "no-std"))]
7034 fn generate_routes() {
7035 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7037 let logger = ln_test_utils::TestLogger::new();
7038 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7046 let params = ProbabilisticScoringFeeParameters::default();
7047 let features = super::Bolt11InvoiceFeatures::empty();
7049 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7053 #[cfg(not(feature = "no-std"))]
7054 fn generate_routes_mpp() {
7055 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7057 let logger = ln_test_utils::TestLogger::new();
7058 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7066 let params = ProbabilisticScoringFeeParameters::default();
7067 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7069 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7073 #[cfg(not(feature = "no-std"))]
7074 fn generate_large_mpp_routes() {
7075 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
7077 let logger = ln_test_utils::TestLogger::new();
7078 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7086 let params = ProbabilisticScoringFeeParameters::default();
7087 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &*graph, &logger);
7088 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7090 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
7094 fn honors_manual_penalties() {
7095 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
7096 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7098 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7099 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7101 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
7102 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
7104 // First check set manual penalties are returned by the scorer.
7105 let usage = ChannelUsage {
7107 inflight_htlc_msat: 0,
7108 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
7110 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
7111 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
7112 let network_graph = network_graph.read_only();
7113 let channels = network_graph.channels();
7114 let channel = channels.get(&5).unwrap();
7115 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
7116 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop(CandidatePublicHop {
7118 short_channel_id: 5,
7120 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
7122 // Then check we can get a normal route
7123 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
7124 let route_params = RouteParameters::from_payment_params_and_value(
7125 payment_params, 100);
7126 let route = get_route(&our_id, &route_params, &network_graph, None,
7127 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
7128 assert!(route.is_ok());
7130 // Then check that we can't get a route if we ban an intermediate node.
7131 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
7132 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7133 assert!(route.is_err());
7135 // Finally make sure we can route again, when we remove the ban.
7136 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
7137 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7138 assert!(route.is_ok());
7142 fn abide_by_route_hint_max_htlc() {
7143 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
7144 // params in the final route.
7145 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7146 let netgraph = network_graph.read_only();
7147 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7148 let scorer = ln_test_utils::TestScorer::new();
7149 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7150 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7151 let config = UserConfig::default();
7153 let max_htlc_msat = 50_000;
7154 let route_hint_1 = RouteHint(vec![RouteHintHop {
7155 src_node_id: nodes[2],
7156 short_channel_id: 42,
7159 proportional_millionths: 0,
7161 cltv_expiry_delta: 10,
7162 htlc_minimum_msat: None,
7163 htlc_maximum_msat: Some(max_htlc_msat),
7165 let dest_node_id = ln_test_utils::pubkey(42);
7166 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7167 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
7168 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7171 // Make sure we'll error if our route hints don't have enough liquidity according to their
7172 // htlc_maximum_msat.
7173 let mut route_params = RouteParameters::from_payment_params_and_value(
7174 payment_params, max_htlc_msat + 1);
7175 route_params.max_total_routing_fee_msat = None;
7176 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
7177 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
7180 assert_eq!(err, "Failed to find a sufficient route to the given destination");
7181 } else { panic!(); }
7183 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
7184 let mut route_hint_2 = route_hint_1.clone();
7185 route_hint_2.0[0].short_channel_id = 43;
7186 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7187 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7188 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7190 let mut route_params = RouteParameters::from_payment_params_and_value(
7191 payment_params, max_htlc_msat + 1);
7192 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
7193 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
7194 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7195 assert_eq!(route.paths.len(), 2);
7196 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7197 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7201 fn direct_channel_to_hints_with_max_htlc() {
7202 // Check that if we have a first hop channel peer that's connected to multiple provided route
7203 // hints, that we properly split the payment between the route hints if needed.
7204 let logger = Arc::new(ln_test_utils::TestLogger::new());
7205 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7206 let scorer = ln_test_utils::TestScorer::new();
7207 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7208 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7209 let config = UserConfig::default();
7211 let our_node_id = ln_test_utils::pubkey(42);
7212 let intermed_node_id = ln_test_utils::pubkey(43);
7213 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7215 let amt_msat = 900_000;
7216 let max_htlc_msat = 500_000;
7217 let route_hint_1 = RouteHint(vec![RouteHintHop {
7218 src_node_id: intermed_node_id,
7219 short_channel_id: 44,
7222 proportional_millionths: 0,
7224 cltv_expiry_delta: 10,
7225 htlc_minimum_msat: None,
7226 htlc_maximum_msat: Some(max_htlc_msat),
7228 src_node_id: intermed_node_id,
7229 short_channel_id: 45,
7232 proportional_millionths: 0,
7234 cltv_expiry_delta: 10,
7235 htlc_minimum_msat: None,
7236 // Check that later route hint max htlcs don't override earlier ones
7237 htlc_maximum_msat: Some(max_htlc_msat - 50),
7239 let mut route_hint_2 = route_hint_1.clone();
7240 route_hint_2.0[0].short_channel_id = 46;
7241 route_hint_2.0[1].short_channel_id = 47;
7242 let dest_node_id = ln_test_utils::pubkey(44);
7243 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7244 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7245 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7248 let route_params = RouteParameters::from_payment_params_and_value(
7249 payment_params, amt_msat);
7250 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7251 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7252 &Default::default(), &random_seed_bytes).unwrap();
7253 assert_eq!(route.paths.len(), 2);
7254 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7255 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7256 assert_eq!(route.get_total_amount(), amt_msat);
7258 // Re-run but with two first hop channels connected to the same route hint peers that must be
7260 let first_hops = vec![
7261 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7262 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7264 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7265 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7266 &Default::default(), &random_seed_bytes).unwrap();
7267 assert_eq!(route.paths.len(), 2);
7268 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7269 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7270 assert_eq!(route.get_total_amount(), amt_msat);
7272 // Make sure this works for blinded route hints.
7273 let blinded_path = BlindedPath {
7274 introduction_node_id: intermed_node_id,
7275 blinding_point: ln_test_utils::pubkey(42),
7277 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
7278 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
7281 let blinded_payinfo = BlindedPayInfo {
7283 fee_proportional_millionths: 0,
7284 htlc_minimum_msat: 1,
7285 htlc_maximum_msat: max_htlc_msat,
7286 cltv_expiry_delta: 10,
7287 features: BlindedHopFeatures::empty(),
7289 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7290 let payment_params = PaymentParameters::blinded(vec![
7291 (blinded_payinfo.clone(), blinded_path.clone()),
7292 (blinded_payinfo.clone(), blinded_path.clone())])
7293 .with_bolt12_features(bolt12_features).unwrap();
7294 let route_params = RouteParameters::from_payment_params_and_value(
7295 payment_params, amt_msat);
7296 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7297 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7298 &Default::default(), &random_seed_bytes).unwrap();
7299 assert_eq!(route.paths.len(), 2);
7300 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7301 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7302 assert_eq!(route.get_total_amount(), amt_msat);
7306 fn blinded_route_ser() {
7307 let blinded_path_1 = BlindedPath {
7308 introduction_node_id: ln_test_utils::pubkey(42),
7309 blinding_point: ln_test_utils::pubkey(43),
7311 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7312 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7315 let blinded_path_2 = BlindedPath {
7316 introduction_node_id: ln_test_utils::pubkey(46),
7317 blinding_point: ln_test_utils::pubkey(47),
7319 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7320 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7323 // (De)serialize a Route with 1 blinded path out of two total paths.
7324 let mut route = Route { paths: vec![Path {
7325 hops: vec![RouteHop {
7326 pubkey: ln_test_utils::pubkey(50),
7327 node_features: NodeFeatures::empty(),
7328 short_channel_id: 42,
7329 channel_features: ChannelFeatures::empty(),
7331 cltv_expiry_delta: 0,
7332 maybe_announced_channel: true,
7334 blinded_tail: Some(BlindedTail {
7335 hops: blinded_path_1.blinded_hops,
7336 blinding_point: blinded_path_1.blinding_point,
7337 excess_final_cltv_expiry_delta: 40,
7338 final_value_msat: 100,
7340 hops: vec![RouteHop {
7341 pubkey: ln_test_utils::pubkey(51),
7342 node_features: NodeFeatures::empty(),
7343 short_channel_id: 43,
7344 channel_features: ChannelFeatures::empty(),
7346 cltv_expiry_delta: 0,
7347 maybe_announced_channel: true,
7348 }], blinded_tail: None }],
7351 let encoded_route = route.encode();
7352 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7353 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7354 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7356 // (De)serialize a Route with two paths, each containing a blinded tail.
7357 route.paths[1].blinded_tail = Some(BlindedTail {
7358 hops: blinded_path_2.blinded_hops,
7359 blinding_point: blinded_path_2.blinding_point,
7360 excess_final_cltv_expiry_delta: 41,
7361 final_value_msat: 101,
7363 let encoded_route = route.encode();
7364 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7365 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7366 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7370 fn blinded_path_inflight_processing() {
7371 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7372 // account for the blinded tail's final amount_msat.
7373 let mut inflight_htlcs = InFlightHtlcs::new();
7374 let blinded_path = BlindedPath {
7375 introduction_node_id: ln_test_utils::pubkey(43),
7376 blinding_point: ln_test_utils::pubkey(48),
7377 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7380 hops: vec![RouteHop {
7381 pubkey: ln_test_utils::pubkey(42),
7382 node_features: NodeFeatures::empty(),
7383 short_channel_id: 42,
7384 channel_features: ChannelFeatures::empty(),
7386 cltv_expiry_delta: 0,
7387 maybe_announced_channel: false,
7390 pubkey: blinded_path.introduction_node_id,
7391 node_features: NodeFeatures::empty(),
7392 short_channel_id: 43,
7393 channel_features: ChannelFeatures::empty(),
7395 cltv_expiry_delta: 0,
7396 maybe_announced_channel: false,
7398 blinded_tail: Some(BlindedTail {
7399 hops: blinded_path.blinded_hops,
7400 blinding_point: blinded_path.blinding_point,
7401 excess_final_cltv_expiry_delta: 0,
7402 final_value_msat: 200,
7405 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7406 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7407 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7411 fn blinded_path_cltv_shadow_offset() {
7412 // Make sure we add a shadow offset when sending to blinded paths.
7413 let blinded_path = BlindedPath {
7414 introduction_node_id: ln_test_utils::pubkey(43),
7415 blinding_point: ln_test_utils::pubkey(44),
7417 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7418 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7421 let mut route = Route { paths: vec![Path {
7422 hops: vec![RouteHop {
7423 pubkey: ln_test_utils::pubkey(42),
7424 node_features: NodeFeatures::empty(),
7425 short_channel_id: 42,
7426 channel_features: ChannelFeatures::empty(),
7428 cltv_expiry_delta: 0,
7429 maybe_announced_channel: false,
7432 pubkey: blinded_path.introduction_node_id,
7433 node_features: NodeFeatures::empty(),
7434 short_channel_id: 43,
7435 channel_features: ChannelFeatures::empty(),
7437 cltv_expiry_delta: 0,
7438 maybe_announced_channel: false,
7441 blinded_tail: Some(BlindedTail {
7442 hops: blinded_path.blinded_hops,
7443 blinding_point: blinded_path.blinding_point,
7444 excess_final_cltv_expiry_delta: 0,
7445 final_value_msat: 200,
7447 }], route_params: None};
7449 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7450 let (_, network_graph, _, _, _) = build_line_graph();
7451 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7452 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7453 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7457 fn simple_blinded_route_hints() {
7458 do_simple_blinded_route_hints(1);
7459 do_simple_blinded_route_hints(2);
7460 do_simple_blinded_route_hints(3);
7463 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7464 // Check that we can generate a route to a blinded path with the expected hops.
7465 let (secp_ctx, network, _, _, logger) = build_graph();
7466 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7467 let network_graph = network.read_only();
7469 let scorer = ln_test_utils::TestScorer::new();
7470 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7471 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7473 let mut blinded_path = BlindedPath {
7474 introduction_node_id: nodes[2],
7475 blinding_point: ln_test_utils::pubkey(42),
7476 blinded_hops: Vec::with_capacity(num_blinded_hops),
7478 for i in 0..num_blinded_hops {
7479 blinded_path.blinded_hops.push(
7480 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7483 let blinded_payinfo = BlindedPayInfo {
7485 fee_proportional_millionths: 500,
7486 htlc_minimum_msat: 1000,
7487 htlc_maximum_msat: 100_000_000,
7488 cltv_expiry_delta: 15,
7489 features: BlindedHopFeatures::empty(),
7492 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7493 let route_params = RouteParameters::from_payment_params_and_value(
7494 payment_params, 1001);
7495 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7496 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7497 assert_eq!(route.paths.len(), 1);
7498 assert_eq!(route.paths[0].hops.len(), 2);
7500 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7501 assert_eq!(tail.hops, blinded_path.blinded_hops);
7502 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7503 assert_eq!(tail.final_value_msat, 1001);
7505 let final_hop = route.paths[0].hops.last().unwrap();
7506 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
7507 if tail.hops.len() > 1 {
7508 assert_eq!(final_hop.fee_msat,
7509 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7510 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7512 assert_eq!(final_hop.fee_msat, 0);
7513 assert_eq!(final_hop.cltv_expiry_delta, 0);
7518 fn blinded_path_routing_errors() {
7519 // Check that we can generate a route to a blinded path with the expected hops.
7520 let (secp_ctx, network, _, _, logger) = build_graph();
7521 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7522 let network_graph = network.read_only();
7524 let scorer = ln_test_utils::TestScorer::new();
7525 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7526 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7528 let mut invalid_blinded_path = BlindedPath {
7529 introduction_node_id: nodes[2],
7530 blinding_point: ln_test_utils::pubkey(42),
7532 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7535 let blinded_payinfo = BlindedPayInfo {
7537 fee_proportional_millionths: 500,
7538 htlc_minimum_msat: 1000,
7539 htlc_maximum_msat: 100_000_000,
7540 cltv_expiry_delta: 15,
7541 features: BlindedHopFeatures::empty(),
7544 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7545 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
7546 let payment_params = PaymentParameters::blinded(vec![
7547 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7548 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7549 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7550 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7551 &scorer, &Default::default(), &random_seed_bytes)
7553 Err(LightningError { err, .. }) => {
7554 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7556 _ => panic!("Expected error")
7559 invalid_blinded_path.introduction_node_id = our_id;
7560 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7561 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7562 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7563 &Default::default(), &random_seed_bytes)
7565 Err(LightningError { err, .. }) => {
7566 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7568 _ => panic!("Expected error")
7571 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
7572 invalid_blinded_path.blinded_hops.clear();
7573 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7574 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7575 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7576 &Default::default(), &random_seed_bytes)
7578 Err(LightningError { err, .. }) => {
7579 assert_eq!(err, "0-hop blinded path provided");
7581 _ => panic!("Expected error")
7586 fn matching_intro_node_paths_provided() {
7587 // Check that if multiple blinded paths with the same intro node are provided in payment
7588 // parameters, we'll return the correct paths in the resulting MPP route.
7589 let (secp_ctx, network, _, _, logger) = build_graph();
7590 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7591 let network_graph = network.read_only();
7593 let scorer = ln_test_utils::TestScorer::new();
7594 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7595 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7596 let config = UserConfig::default();
7598 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7599 let blinded_path_1 = BlindedPath {
7600 introduction_node_id: nodes[2],
7601 blinding_point: ln_test_utils::pubkey(42),
7603 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7604 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7607 let blinded_payinfo_1 = BlindedPayInfo {
7609 fee_proportional_millionths: 0,
7610 htlc_minimum_msat: 0,
7611 htlc_maximum_msat: 30_000,
7612 cltv_expiry_delta: 0,
7613 features: BlindedHopFeatures::empty(),
7616 let mut blinded_path_2 = blinded_path_1.clone();
7617 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7618 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7619 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7621 let blinded_hints = vec![
7622 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7623 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7625 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7626 .with_bolt12_features(bolt12_features).unwrap();
7628 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7629 route_params.max_total_routing_fee_msat = Some(100_000);
7630 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7631 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7632 assert_eq!(route.paths.len(), 2);
7633 let mut total_amount_paid_msat = 0;
7634 for path in route.paths.into_iter() {
7635 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7636 if let Some(bt) = &path.blinded_tail {
7637 assert_eq!(bt.blinding_point,
7638 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7639 .map(|(_, bp)| bp.blinding_point).unwrap());
7640 } else { panic!(); }
7641 total_amount_paid_msat += path.final_value_msat();
7643 assert_eq!(total_amount_paid_msat, 100_000);
7647 fn direct_to_intro_node() {
7648 // This previously caused a debug panic in the router when asserting
7649 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7650 // direct channels we failed to account for the fee charged for use of the blinded path.
7653 // node0 -1(1)2 - node1
7654 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7655 // doesn't account for the blinded path fee.
7657 let secp_ctx = Secp256k1::new();
7658 let logger = Arc::new(ln_test_utils::TestLogger::new());
7659 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7660 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7661 let scorer = ln_test_utils::TestScorer::new();
7662 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7663 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7665 let amt_msat = 10_000_000;
7666 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7667 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7668 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7669 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7670 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7671 short_channel_id: 1,
7674 cltv_expiry_delta: 42,
7675 htlc_minimum_msat: 1_000,
7676 htlc_maximum_msat: 10_000_000,
7678 fee_proportional_millionths: 0,
7679 excess_data: Vec::new()
7681 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7682 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7683 short_channel_id: 1,
7686 cltv_expiry_delta: 42,
7687 htlc_minimum_msat: 1_000,
7688 htlc_maximum_msat: 10_000_000,
7690 fee_proportional_millionths: 0,
7691 excess_data: Vec::new()
7693 let first_hops = vec![
7694 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7696 let blinded_path = BlindedPath {
7697 introduction_node_id: nodes[1],
7698 blinding_point: ln_test_utils::pubkey(42),
7700 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7701 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7704 let blinded_payinfo = BlindedPayInfo {
7705 fee_base_msat: 1000,
7706 fee_proportional_millionths: 0,
7707 htlc_minimum_msat: 1000,
7708 htlc_maximum_msat: MAX_VALUE_MSAT,
7709 cltv_expiry_delta: 0,
7710 features: BlindedHopFeatures::empty(),
7712 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7714 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7716 let netgraph = network_graph.read_only();
7717 let route_params = RouteParameters::from_payment_params_and_value(
7718 payment_params.clone(), amt_msat);
7719 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7720 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7721 &Default::default(), &random_seed_bytes) {
7722 assert_eq!(err, "Failed to find a path to the given destination");
7723 } else { panic!("Expected error") }
7725 // Sending an exact amount accounting for the blinded path fee works.
7726 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7727 let route_params = RouteParameters::from_payment_params_and_value(
7728 payment_params, amt_minus_blinded_path_fee);
7729 let route = get_route(&nodes[0], &route_params, &netgraph,
7730 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7731 &Default::default(), &random_seed_bytes).unwrap();
7732 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7733 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7737 fn direct_to_matching_intro_nodes() {
7738 // This previously caused us to enter `unreachable` code in the following situation:
7739 // 1. We add a route candidate for intro_node contributing a high amount
7740 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7741 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7742 // amount, and update our route candidate for intro_node for the lower amount
7743 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7744 // lower contribution amount, but fail (this was previously caused by failure to account for
7745 // blinded path fees when adding first_hop<>intro_node candidates)
7746 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7747 // candidate still thinks its path is contributing the original higher amount. This caused us
7748 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7750 let secp_ctx = Secp256k1::new();
7751 let logger = Arc::new(ln_test_utils::TestLogger::new());
7752 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7753 let scorer = ln_test_utils::TestScorer::new();
7754 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7755 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7756 let config = UserConfig::default();
7758 // Values are taken from the fuzz input that uncovered this panic.
7759 let amt_msat = 21_7020_5185_1403_2640;
7760 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7761 let first_hops = vec![
7762 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7763 18446744073709551615)];
7765 let blinded_path = BlindedPath {
7766 introduction_node_id: nodes[1],
7767 blinding_point: ln_test_utils::pubkey(42),
7769 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7770 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7773 let blinded_payinfo = BlindedPayInfo {
7774 fee_base_msat: 5046_2720,
7775 fee_proportional_millionths: 0,
7776 htlc_minimum_msat: 4503_5996_2737_0496,
7777 htlc_maximum_msat: 45_0359_9627_3704_9600,
7778 cltv_expiry_delta: 0,
7779 features: BlindedHopFeatures::empty(),
7781 let mut blinded_hints = vec![
7782 (blinded_payinfo.clone(), blinded_path.clone()),
7783 (blinded_payinfo.clone(), blinded_path.clone()),
7785 blinded_hints[1].0.fee_base_msat = 419_4304;
7786 blinded_hints[1].0.fee_proportional_millionths = 257;
7787 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7788 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7789 blinded_hints[1].0.cltv_expiry_delta = 0;
7791 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7792 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7793 .with_bolt12_features(bolt12_features).unwrap();
7795 let netgraph = network_graph.read_only();
7796 let route_params = RouteParameters::from_payment_params_and_value(
7797 payment_params, amt_msat);
7798 let route = get_route(&nodes[0], &route_params, &netgraph,
7799 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7800 &Default::default(), &random_seed_bytes).unwrap();
7801 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7802 assert_eq!(route.get_total_amount(), amt_msat);
7806 fn we_are_intro_node_candidate_hops() {
7807 // This previously led to a panic in the router because we'd generate a Path with only a
7808 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7809 // where the origin node is the intro node. We now fully disallow considering candidate hops
7810 // where the origin node is the intro node.
7811 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7812 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7813 let scorer = ln_test_utils::TestScorer::new();
7814 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7815 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7816 let config = UserConfig::default();
7818 // Values are taken from the fuzz input that uncovered this panic.
7819 let amt_msat = 21_7020_5185_1423_0019;
7821 let blinded_path = BlindedPath {
7822 introduction_node_id: our_id,
7823 blinding_point: ln_test_utils::pubkey(42),
7825 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7826 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7829 let blinded_payinfo = BlindedPayInfo {
7830 fee_base_msat: 5052_9027,
7831 fee_proportional_millionths: 0,
7832 htlc_minimum_msat: 21_7020_5185_1423_0019,
7833 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7834 cltv_expiry_delta: 0,
7835 features: BlindedHopFeatures::empty(),
7837 let mut blinded_hints = vec![
7838 (blinded_payinfo.clone(), blinded_path.clone()),
7839 (blinded_payinfo.clone(), blinded_path.clone()),
7841 blinded_hints[1].1.introduction_node_id = nodes[6];
7843 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7844 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7845 .with_bolt12_features(bolt12_features.clone()).unwrap();
7847 let netgraph = network_graph.read_only();
7848 let route_params = RouteParameters::from_payment_params_and_value(
7849 payment_params, amt_msat);
7850 if let Err(LightningError { err, .. }) = get_route(
7851 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7853 assert_eq!(err, "Failed to find a path to the given destination");
7858 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7859 // This previously led to a debug panic in the router because we'd find an invalid Path with
7860 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7861 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7862 // the payment, when it was intended to only include the final value of the payment.
7863 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7864 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7865 let scorer = ln_test_utils::TestScorer::new();
7866 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7867 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7868 let config = UserConfig::default();
7870 // Values are taken from the fuzz input that uncovered this panic.
7871 let amt_msat = 21_7020_5185_1423_0019;
7873 let blinded_path = BlindedPath {
7874 introduction_node_id: our_id,
7875 blinding_point: ln_test_utils::pubkey(42),
7877 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7878 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7881 let blinded_payinfo = BlindedPayInfo {
7882 fee_base_msat: 10_4425_1395,
7883 fee_proportional_millionths: 0,
7884 htlc_minimum_msat: 21_7301_9934_9094_0931,
7885 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7886 cltv_expiry_delta: 0,
7887 features: BlindedHopFeatures::empty(),
7889 let mut blinded_hints = vec![
7890 (blinded_payinfo.clone(), blinded_path.clone()),
7891 (blinded_payinfo.clone(), blinded_path.clone()),
7892 (blinded_payinfo.clone(), blinded_path.clone()),
7894 blinded_hints[1].0.fee_base_msat = 5052_9027;
7895 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7896 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7898 blinded_hints[2].1.introduction_node_id = nodes[6];
7900 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7901 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7902 .with_bolt12_features(bolt12_features.clone()).unwrap();
7904 let netgraph = network_graph.read_only();
7905 let route_params = RouteParameters::from_payment_params_and_value(
7906 payment_params, amt_msat);
7907 if let Err(LightningError { err, .. }) = get_route(
7908 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7910 assert_eq!(err, "Failed to find a path to the given destination");
7915 fn min_htlc_overpay_violates_max_htlc() {
7916 do_min_htlc_overpay_violates_max_htlc(true);
7917 do_min_htlc_overpay_violates_max_htlc(false);
7919 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7920 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7921 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7922 // to `targets` and build an invalid path with it, and subsquently hit a debug panic asserting
7923 // that the used liquidity for a hop was less than its available liquidity limit.
7924 let secp_ctx = Secp256k1::new();
7925 let logger = Arc::new(ln_test_utils::TestLogger::new());
7926 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7927 let scorer = ln_test_utils::TestScorer::new();
7928 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7929 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7930 let config = UserConfig::default();
7932 // Values are taken from the fuzz input that uncovered this panic.
7933 let amt_msat = 7_4009_8048;
7934 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7935 let first_hop_outbound_capacity = 2_7345_2000;
7936 let first_hops = vec![get_channel_details(
7937 Some(200), nodes[0], channelmanager::provided_init_features(&config),
7938 first_hop_outbound_capacity
7941 let base_fee = 1_6778_3453;
7942 let htlc_min = 2_5165_8240;
7943 let payment_params = if blinded_payee {
7944 let blinded_path = BlindedPath {
7945 introduction_node_id: nodes[0],
7946 blinding_point: ln_test_utils::pubkey(42),
7948 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7949 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7952 let blinded_payinfo = BlindedPayInfo {
7953 fee_base_msat: base_fee,
7954 fee_proportional_millionths: 0,
7955 htlc_minimum_msat: htlc_min,
7956 htlc_maximum_msat: htlc_min * 1000,
7957 cltv_expiry_delta: 0,
7958 features: BlindedHopFeatures::empty(),
7960 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7961 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
7962 .with_bolt12_features(bolt12_features.clone()).unwrap()
7964 let route_hint = RouteHint(vec![RouteHintHop {
7965 src_node_id: nodes[0],
7966 short_channel_id: 42,
7968 base_msat: base_fee,
7969 proportional_millionths: 0,
7971 cltv_expiry_delta: 10,
7972 htlc_minimum_msat: Some(htlc_min),
7973 htlc_maximum_msat: None,
7976 PaymentParameters::from_node_id(nodes[1], 42)
7977 .with_route_hints(vec![route_hint]).unwrap()
7978 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7981 let netgraph = network_graph.read_only();
7982 let route_params = RouteParameters::from_payment_params_and_value(
7983 payment_params, amt_msat);
7984 if let Err(LightningError { err, .. }) = get_route(
7985 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7986 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7988 assert_eq!(err, "Failed to find a path to the given destination");
7993 fn previously_used_liquidity_violates_max_htlc() {
7994 do_previously_used_liquidity_violates_max_htlc(true);
7995 do_previously_used_liquidity_violates_max_htlc(false);
7998 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
7999 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
8000 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
8001 // candidate. In this case, the candidate does not have enough due to a previous path taking up
8002 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
8003 // asserting that the used liquidity for a hop was less than its available liquidity limit.
8004 let secp_ctx = Secp256k1::new();
8005 let logger = Arc::new(ln_test_utils::TestLogger::new());
8006 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8007 let scorer = ln_test_utils::TestScorer::new();
8008 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8009 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8010 let config = UserConfig::default();
8012 // Values are taken from the fuzz input that uncovered this panic.
8013 let amt_msat = 52_4288;
8014 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8015 let first_hops = vec![get_channel_details(
8016 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
8017 ), get_channel_details(
8018 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
8021 let base_fees = [0, 425_9840, 0, 0];
8022 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
8023 let payment_params = if blinded_payee {
8024 let blinded_path = BlindedPath {
8025 introduction_node_id: nodes[0],
8026 blinding_point: ln_test_utils::pubkey(42),
8028 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8029 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8032 let mut blinded_hints = Vec::new();
8033 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
8034 blinded_hints.push((BlindedPayInfo {
8035 fee_base_msat: *base_fee,
8036 fee_proportional_millionths: 0,
8037 htlc_minimum_msat: *htlc_min,
8038 htlc_maximum_msat: htlc_min * 100,
8039 cltv_expiry_delta: 10,
8040 features: BlindedHopFeatures::empty(),
8041 }, blinded_path.clone()));
8043 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8044 PaymentParameters::blinded(blinded_hints.clone())
8045 .with_bolt12_features(bolt12_features.clone()).unwrap()
8047 let mut route_hints = Vec::new();
8048 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
8049 route_hints.push(RouteHint(vec![RouteHintHop {
8050 src_node_id: nodes[0],
8051 short_channel_id: 42 + idx as u64,
8053 base_msat: *base_fee,
8054 proportional_millionths: 0,
8056 cltv_expiry_delta: 10,
8057 htlc_minimum_msat: Some(*htlc_min),
8058 htlc_maximum_msat: Some(htlc_min * 100),
8061 PaymentParameters::from_node_id(nodes[1], 42)
8062 .with_route_hints(route_hints).unwrap()
8063 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8066 let netgraph = network_graph.read_only();
8067 let route_params = RouteParameters::from_payment_params_and_value(
8068 payment_params, amt_msat);
8070 let route = get_route(
8071 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8072 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8074 assert_eq!(route.paths.len(), 1);
8075 assert_eq!(route.get_total_amount(), amt_msat);
8079 fn candidate_path_min() {
8080 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
8081 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
8082 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
8083 // would add a connecting first_hop node that did not have enough contribution amount, leading
8084 // to a debug panic upon invalid path construction.
8085 let secp_ctx = Secp256k1::new();
8086 let logger = Arc::new(ln_test_utils::TestLogger::new());
8087 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8088 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
8089 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8090 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8091 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8092 let config = UserConfig::default();
8094 // Values are taken from the fuzz input that uncovered this panic.
8095 let amt_msat = 7_4009_8048;
8096 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
8097 let first_hops = vec![get_channel_details(
8098 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
8101 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
8102 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8103 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8104 short_channel_id: 6,
8107 cltv_expiry_delta: (6 << 4) | 0,
8108 htlc_minimum_msat: 0,
8109 htlc_maximum_msat: MAX_VALUE_MSAT,
8111 fee_proportional_millionths: 0,
8112 excess_data: Vec::new()
8114 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
8116 let htlc_min = 2_5165_8240;
8117 let blinded_hints = vec![
8119 fee_base_msat: 1_6778_3453,
8120 fee_proportional_millionths: 0,
8121 htlc_minimum_msat: htlc_min,
8122 htlc_maximum_msat: htlc_min * 100,
8123 cltv_expiry_delta: 10,
8124 features: BlindedHopFeatures::empty(),
8126 introduction_node_id: nodes[0],
8127 blinding_point: ln_test_utils::pubkey(42),
8129 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8130 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8134 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8135 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8136 .with_bolt12_features(bolt12_features.clone()).unwrap();
8137 let route_params = RouteParameters::from_payment_params_and_value(
8138 payment_params, amt_msat);
8139 let netgraph = network_graph.read_only();
8141 if let Err(LightningError { err, .. }) = get_route(
8142 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8143 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8146 assert_eq!(err, "Failed to find a path to the given destination");
8151 fn path_contribution_includes_min_htlc_overpay() {
8152 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
8153 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
8154 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
8155 // selection, both tested here.
8156 let secp_ctx = Secp256k1::new();
8157 let logger = Arc::new(ln_test_utils::TestLogger::new());
8158 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8159 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8160 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8161 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8162 let config = UserConfig::default();
8164 // Values are taken from the fuzz input that uncovered this panic.
8165 let amt_msat = 562_0000;
8166 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8167 let first_hops = vec![
8168 get_channel_details(
8169 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
8173 let htlc_mins = [49_0000, 1125_0000];
8174 let payment_params = {
8175 let blinded_path = BlindedPath {
8176 introduction_node_id: nodes[0],
8177 blinding_point: ln_test_utils::pubkey(42),
8179 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8180 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8183 let mut blinded_hints = Vec::new();
8184 for htlc_min in htlc_mins.iter() {
8185 blinded_hints.push((BlindedPayInfo {
8187 fee_proportional_millionths: 0,
8188 htlc_minimum_msat: *htlc_min,
8189 htlc_maximum_msat: *htlc_min * 100,
8190 cltv_expiry_delta: 10,
8191 features: BlindedHopFeatures::empty(),
8192 }, blinded_path.clone()));
8194 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8195 PaymentParameters::blinded(blinded_hints.clone())
8196 .with_bolt12_features(bolt12_features.clone()).unwrap()
8199 let netgraph = network_graph.read_only();
8200 let route_params = RouteParameters::from_payment_params_and_value(
8201 payment_params, amt_msat);
8202 let route = get_route(
8203 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8204 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8207 assert_eq!(route.paths.len(), 1);
8208 assert_eq!(route.get_total_amount(), amt_msat);
8212 fn first_hop_preferred_over_hint() {
8213 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
8214 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
8215 let secp_ctx = Secp256k1::new();
8216 let logger = Arc::new(ln_test_utils::TestLogger::new());
8217 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8218 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
8219 let scorer = ln_test_utils::TestScorer::new();
8220 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8221 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8222 let config = UserConfig::default();
8224 let amt_msat = 1_000_000;
8225 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
8227 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
8228 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
8229 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8230 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8231 short_channel_id: 1,
8234 cltv_expiry_delta: 42,
8235 htlc_minimum_msat: 1_000,
8236 htlc_maximum_msat: 10_000_000,
8238 fee_proportional_millionths: 0,
8239 excess_data: Vec::new()
8241 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8242 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8243 short_channel_id: 1,
8246 cltv_expiry_delta: 42,
8247 htlc_minimum_msat: 1_000,
8248 htlc_maximum_msat: 10_000_000,
8250 fee_proportional_millionths: 0,
8251 excess_data: Vec::new()
8254 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
8255 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
8256 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8257 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8258 short_channel_id: 2,
8261 cltv_expiry_delta: 42,
8262 htlc_minimum_msat: 1_000,
8263 htlc_maximum_msat: 10_000_000,
8265 fee_proportional_millionths: 0,
8266 excess_data: Vec::new()
8268 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8269 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8270 short_channel_id: 2,
8273 cltv_expiry_delta: 42,
8274 htlc_minimum_msat: 1_000,
8275 htlc_maximum_msat: 10_000_000,
8277 fee_proportional_millionths: 0,
8278 excess_data: Vec::new()
8281 let dest_node_id = nodes[2];
8283 let route_hint = RouteHint(vec![RouteHintHop {
8284 src_node_id: our_node_id,
8285 short_channel_id: 44,
8288 proportional_millionths: 0,
8290 cltv_expiry_delta: 10,
8291 htlc_minimum_msat: None,
8292 htlc_maximum_msat: Some(5_000_000),
8295 src_node_id: nodes[0],
8296 short_channel_id: 45,
8299 proportional_millionths: 0,
8301 cltv_expiry_delta: 10,
8302 htlc_minimum_msat: None,
8303 htlc_maximum_msat: None,
8306 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8307 .with_route_hints(vec![route_hint]).unwrap()
8308 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8309 let route_params = RouteParameters::from_payment_params_and_value(
8310 payment_params, amt_msat);
8312 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8314 let first_hop = get_channel_details(Some(1), nodes[0],
8315 channelmanager::provided_init_features(&config), 999_999);
8316 let first_hops = vec![first_hop];
8318 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8319 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8320 &Default::default(), &random_seed_bytes).unwrap();
8321 assert_eq!(route.paths.len(), 1);
8322 assert_eq!(route.get_total_amount(), amt_msat);
8323 assert_eq!(route.paths[0].hops.len(), 2);
8324 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8325 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8326 assert_eq!(route.get_total_fees(), 123);
8328 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8329 // for a first hop channel.
8330 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8331 first_hop.outbound_scid_alias = Some(44);
8332 let first_hops = vec![first_hop];
8334 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8335 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8336 &Default::default(), &random_seed_bytes);
8337 assert!(route_res.is_err());
8339 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8340 // use the cheaper second hop of the route hint.
8341 let mut first_hop = get_channel_details(Some(1), nodes[0],
8342 channelmanager::provided_init_features(&config), 10_000_000);
8343 first_hop.outbound_scid_alias = Some(44);
8344 let first_hops = vec![first_hop];
8346 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8347 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8348 &Default::default(), &random_seed_bytes).unwrap();
8349 assert_eq!(route.paths.len(), 1);
8350 assert_eq!(route.get_total_amount(), amt_msat);
8351 assert_eq!(route.paths[0].hops.len(), 2);
8352 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8353 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8354 assert_eq!(route.get_total_fees(), 123);
8358 fn allow_us_being_first_hint() {
8359 // Check that we consider a route hint even if we are the src of the first hop.
8360 let secp_ctx = Secp256k1::new();
8361 let logger = Arc::new(ln_test_utils::TestLogger::new());
8362 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8363 let scorer = ln_test_utils::TestScorer::new();
8364 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8365 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8366 let config = UserConfig::default();
8368 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8370 let amt_msat = 1_000_000;
8371 let dest_node_id = nodes[1];
8373 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8374 let first_hops = vec![first_hop];
8376 let route_hint = RouteHint(vec![RouteHintHop {
8377 src_node_id: our_node_id,
8378 short_channel_id: 44,
8381 proportional_millionths: 0,
8383 cltv_expiry_delta: 10,
8384 htlc_minimum_msat: None,
8385 htlc_maximum_msat: None,
8388 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8389 .with_route_hints(vec![route_hint]).unwrap()
8390 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8392 let route_params = RouteParameters::from_payment_params_and_value(
8393 payment_params, amt_msat);
8396 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8397 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8398 &Default::default(), &random_seed_bytes).unwrap();
8400 assert_eq!(route.paths.len(), 1);
8401 assert_eq!(route.get_total_amount(), amt_msat);
8402 assert_eq!(route.get_total_fees(), 0);
8403 assert_eq!(route.paths[0].hops.len(), 1);
8405 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8409 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
8410 pub(crate) mod bench_utils {
8414 use bitcoin::hashes::Hash;
8415 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
8417 use crate::chain::transaction::OutPoint;
8418 use crate::routing::scoring::ScoreUpdate;
8419 use crate::sign::{EntropySource, KeysManager};
8420 use crate::ln::ChannelId;
8421 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
8422 use crate::ln::features::Bolt11InvoiceFeatures;
8423 use crate::routing::gossip::NetworkGraph;
8424 use crate::routing::scoring::ProbabilisticScorer;
8425 use crate::util::config::UserConfig;
8426 use crate::util::ser::ReadableArgs;
8427 use crate::util::test_utils::TestLogger;
8428 use crate::sync::Arc;
8430 /// Tries to open a network graph file, or panics with a URL to fetch it.
8431 pub(crate) fn get_graph_scorer_file() -> Result<(std::fs::File, std::fs::File), &'static str> {
8432 let load_file = |fname, err_str| {
8433 File::open(fname) // By default we're run in RL/lightning
8434 .or_else(|_| File::open(&format!("lightning/{}", fname))) // We may be run manually in RL/
8435 .or_else(|_| { // Fall back to guessing based on the binary location
8436 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8437 let mut path = std::env::current_exe().unwrap();
8438 path.pop(); // lightning-...
8440 path.pop(); // debug
8441 path.pop(); // target
8442 path.push("lightning");
8446 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8447 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8448 let mut path = std::env::current_exe().unwrap();
8449 path.pop(); // bench...
8451 path.pop(); // debug
8452 path.pop(); // target
8453 path.pop(); // bench
8454 path.push("lightning");
8458 .map_err(|_| err_str)
8460 let graph_res = load_file(
8461 "net_graph-2023-12-10.bin",
8462 "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"
8464 let scorer_res = load_file(
8465 "scorer-2023-12-10.bin",
8466 "Please fetch https://bitcoin.ninja/ldk-scorer-v0.0.118-2023-12-10.bin and place it at scorer-2023-12-10.bin"
8468 #[cfg(require_route_graph_test)]
8469 return Ok((graph_res.unwrap(), scorer_res.unwrap()));
8470 #[cfg(not(require_route_graph_test))]
8471 return Ok((graph_res?, scorer_res?));
8474 pub(crate) fn read_graph_scorer(logger: &TestLogger)
8475 -> Result<(Arc<NetworkGraph<&TestLogger>>, ProbabilisticScorer<Arc<NetworkGraph<&TestLogger>>, &TestLogger>), &'static str> {
8476 let (mut graph_file, mut scorer_file) = get_graph_scorer_file()?;
8477 let graph = Arc::new(NetworkGraph::read(&mut graph_file, logger).unwrap());
8478 let scorer_args = (Default::default(), Arc::clone(&graph), logger);
8479 let scorer = ProbabilisticScorer::read(&mut scorer_file, scorer_args).unwrap();
8483 pub(crate) fn payer_pubkey() -> PublicKey {
8484 let secp_ctx = Secp256k1::new();
8485 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8489 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8491 channel_id: ChannelId::new_zero(),
8492 counterparty: ChannelCounterparty {
8493 features: channelmanager::provided_init_features(&UserConfig::default()),
8495 unspendable_punishment_reserve: 0,
8496 forwarding_info: None,
8497 outbound_htlc_minimum_msat: None,
8498 outbound_htlc_maximum_msat: None,
8500 funding_txo: Some(OutPoint {
8501 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8504 short_channel_id: Some(1),
8505 inbound_scid_alias: None,
8506 outbound_scid_alias: None,
8507 channel_value_satoshis: 10_000_000_000,
8509 balance_msat: 10_000_000_000,
8510 outbound_capacity_msat: 10_000_000_000,
8511 next_outbound_htlc_minimum_msat: 0,
8512 next_outbound_htlc_limit_msat: 10_000_000_000,
8513 inbound_capacity_msat: 0,
8514 unspendable_punishment_reserve: None,
8515 confirmations_required: None,
8516 confirmations: None,
8517 force_close_spend_delay: None,
8519 is_channel_ready: true,
8522 inbound_htlc_minimum_msat: None,
8523 inbound_htlc_maximum_msat: None,
8525 feerate_sat_per_1000_weight: None,
8526 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
8530 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8531 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8532 starting_amount: u64, route_count: usize,
8533 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8534 let payer = payer_pubkey();
8535 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8536 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8538 let nodes = graph.read_only().nodes().clone();
8539 let mut route_endpoints = Vec::new();
8540 for _ in 0..route_count {
8542 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8543 let src = PublicKey::from_slice(nodes.unordered_keys()
8544 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8545 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8546 let dst = PublicKey::from_slice(nodes.unordered_keys()
8547 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8548 let params = PaymentParameters::from_node_id(dst, 42)
8549 .with_bolt11_features(features.clone()).unwrap();
8550 let first_hop = first_hop(src);
8551 let amt_msat = starting_amount + seed % 1_000_000;
8552 let route_params = RouteParameters::from_payment_params_and_value(
8553 params.clone(), amt_msat);
8555 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8556 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8558 route_endpoints.push((first_hop, params, amt_msat));
8564 // Because we've changed channel scores, it's possible we'll take different routes to the
8565 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
8566 // requires a too-high CLTV delta.
8567 route_endpoints.retain(|(first_hop, params, amt_msat)| {
8568 let route_params = RouteParameters::from_payment_params_and_value(
8569 params.clone(), *amt_msat);
8570 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8571 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
8573 route_endpoints.truncate(route_count);
8574 assert_eq!(route_endpoints.len(), route_count);
8582 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8583 use crate::sign::{EntropySource, KeysManager};
8584 use crate::ln::channelmanager;
8585 use crate::ln::features::Bolt11InvoiceFeatures;
8586 use crate::routing::gossip::NetworkGraph;
8587 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScoringFeeParameters};
8588 use crate::util::config::UserConfig;
8589 use crate::util::logger::{Logger, Record};
8590 use crate::util::test_utils::TestLogger;
8592 use criterion::Criterion;
8594 struct DummyLogger {}
8595 impl Logger for DummyLogger {
8596 fn log(&self, _record: Record) {}
8599 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8600 let logger = TestLogger::new();
8601 let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap();
8602 let scorer = FixedPenaltyScorer::with_penalty(0);
8603 generate_routes(bench, &network_graph, scorer, &Default::default(),
8604 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8607 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8608 let logger = TestLogger::new();
8609 let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap();
8610 let scorer = FixedPenaltyScorer::with_penalty(0);
8611 generate_routes(bench, &network_graph, scorer, &Default::default(),
8612 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8613 "generate_mpp_routes_with_zero_penalty_scorer");
8616 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8617 let logger = TestLogger::new();
8618 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8619 let params = ProbabilisticScoringFeeParameters::default();
8620 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8621 "generate_routes_with_probabilistic_scorer");
8624 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8625 let logger = TestLogger::new();
8626 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8627 let params = ProbabilisticScoringFeeParameters::default();
8628 generate_routes(bench, &network_graph, scorer, ¶ms,
8629 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8630 "generate_mpp_routes_with_probabilistic_scorer");
8633 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8634 let logger = TestLogger::new();
8635 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8636 let params = ProbabilisticScoringFeeParameters::default();
8637 generate_routes(bench, &network_graph, scorer, ¶ms,
8638 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8639 "generate_large_mpp_routes_with_probabilistic_scorer");
8642 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8643 let logger = TestLogger::new();
8644 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8645 let mut params = ProbabilisticScoringFeeParameters::default();
8646 params.linear_success_probability = false;
8647 generate_routes(bench, &network_graph, scorer, ¶ms,
8648 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8649 "generate_routes_with_nonlinear_probabilistic_scorer");
8652 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8653 let logger = TestLogger::new();
8654 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8655 let mut params = ProbabilisticScoringFeeParameters::default();
8656 params.linear_success_probability = false;
8657 generate_routes(bench, &network_graph, scorer, ¶ms,
8658 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8659 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8662 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8663 let logger = TestLogger::new();
8664 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8665 let mut params = ProbabilisticScoringFeeParameters::default();
8666 params.linear_success_probability = false;
8667 generate_routes(bench, &network_graph, scorer, ¶ms,
8668 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8669 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8672 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8673 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8674 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8675 bench_name: &'static str,
8677 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8678 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8680 // ...then benchmark finding paths between the nodes we learned.
8681 do_route_bench(bench, graph, scorer, score_params, bench_name, route_endpoints);
8685 fn do_route_bench<S: ScoreLookUp + ScoreUpdate>(
8686 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, scorer: S,
8687 score_params: &S::ScoreParams, bench_name: &'static str,
8688 route_endpoints: Vec<(ChannelDetails, PaymentParameters, u64)>,
8690 let payer = bench_utils::payer_pubkey();
8691 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8692 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8695 bench.bench_function(bench_name, |b| b.iter(|| {
8696 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8697 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8698 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8699 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());