1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The router finds paths within a [`NetworkGraph`] for a payment.
12 use bitcoin::secp256k1::{PublicKey, Secp256k1, self};
13 use bitcoin::hashes::Hash;
14 use bitcoin::hashes::sha256::Hash as Sha256;
16 use crate::blinded_path::{BlindedHop, BlindedPath};
17 use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, PaymentConstraints, PaymentRelay, ReceiveTlvs};
18 use crate::ln::PaymentHash;
19 use crate::ln::channelmanager::{ChannelDetails, PaymentId};
20 use crate::ln::features::{BlindedHopFeatures, Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
21 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
22 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice};
23 use crate::onion_message::messenger::{DefaultMessageRouter, Destination, MessageRouter, OnionMessagePath};
24 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
25 use crate::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp};
26 use crate::sign::EntropySource;
27 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
28 use crate::util::logger::{Level, Logger};
29 use crate::crypto::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) => match forwarding_info.try_into() {
118 Ok(payment_relay) => payment_relay,
119 Err(()) => return None,
124 let cltv_expiry_delta = payment_relay.cltv_expiry_delta as u32;
125 let payment_constraints = PaymentConstraints {
126 max_cltv_expiry: tlvs.payment_constraints.max_cltv_expiry + cltv_expiry_delta,
127 htlc_minimum_msat: details.inbound_htlc_minimum_msat.unwrap_or(0),
134 features: BlindedHopFeatures::empty(),
136 node_id: details.counterparty.node_id,
137 htlc_maximum_msat: details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX),
140 .map(|forward_node| {
141 BlindedPath::new_for_payment(
142 &[forward_node], recipient, tlvs.clone(), u64::MAX, entropy_source, secp_ctx
145 .take(MAX_PAYMENT_PATHS)
146 .collect::<Result<Vec<_>, _>>();
149 Ok(paths) if !paths.is_empty() => Ok(paths),
151 if network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient)) {
152 BlindedPath::one_hop_for_payment(recipient, tlvs, entropy_source, secp_ctx)
153 .map(|path| vec![path])
162 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
164 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
167 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
168 ) -> Result<OnionMessagePath, ()> {
169 self.message_router.find_path(sender, peers, destination)
172 fn create_blinded_paths<
173 ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
175 &self, recipient: PublicKey, peers: Vec<PublicKey>, entropy_source: &ES,
176 secp_ctx: &Secp256k1<T>
177 ) -> Result<Vec<BlindedPath>, ()> {
178 self.message_router.create_blinded_paths(recipient, peers, entropy_source, secp_ctx)
182 /// A trait defining behavior for routing a payment.
183 pub trait Router: MessageRouter {
184 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
186 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
187 /// and [`RouteParameters::final_value_msat`], respectively.
189 &self, payer: &PublicKey, route_params: &RouteParameters,
190 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
191 ) -> Result<Route, LightningError>;
193 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
195 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
196 /// and [`RouteParameters::final_value_msat`], respectively.
198 /// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
200 fn find_route_with_id(
201 &self, payer: &PublicKey, route_params: &RouteParameters,
202 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
203 _payment_hash: PaymentHash, _payment_id: PaymentId
204 ) -> Result<Route, LightningError> {
205 self.find_route(payer, route_params, first_hops, inflight_htlcs)
208 /// Creates [`BlindedPath`]s for payment to the `recipient` node. The channels in `first_hops`
209 /// are assumed to be with the `recipient`'s peers. The payment secret and any constraints are
211 fn create_blinded_payment_paths<
212 ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
214 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
215 amount_msats: u64, entropy_source: &ES, secp_ctx: &Secp256k1<T>
216 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()>;
219 /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
221 /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
224 /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
225 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> where S::Target: ScoreLookUp {
227 // Maps a channel's short channel id and its direction to the liquidity used up.
228 inflight_htlcs: &'a InFlightHtlcs,
230 impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
231 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
232 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
233 ScorerAccountingForInFlightHtlcs {
240 impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
241 type ScoreParams = <S::Target as ScoreLookUp>::ScoreParams;
242 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
243 let target = match candidate.target() {
244 Some(target) => target,
245 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
247 let short_channel_id = match candidate.short_channel_id() {
248 Some(short_channel_id) => short_channel_id,
249 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
251 let source = candidate.source();
252 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
253 &source, &target, short_channel_id
255 let usage = ChannelUsage {
256 inflight_htlc_msat: usage.inflight_htlc_msat.saturating_add(used_liquidity),
260 self.scorer.channel_penalty_msat(candidate, usage, score_params)
262 self.scorer.channel_penalty_msat(candidate, usage, score_params)
267 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
268 /// in-use channel liquidity.
270 pub struct InFlightHtlcs(
271 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
272 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
273 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
275 HashMap<(u64, bool), u64>
279 /// Constructs an empty `InFlightHtlcs`.
280 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
282 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
283 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
284 if path.hops.is_empty() { return };
286 let mut cumulative_msat = 0;
287 if let Some(tail) = &path.blinded_tail {
288 cumulative_msat += tail.final_value_msat;
291 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
292 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
293 // the router excludes the payer node. In the following lines, the payer's information is
294 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
295 // in our sliding window of two.
296 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
297 .map(|hop| hop.pubkey)
298 .chain(core::iter::once(payer_node_id));
300 // Taking the reversed vector from above, we zip it with just the reversed hops list to
301 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
302 // the total amount sent.
303 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
304 cumulative_msat += next_hop.fee_msat;
306 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
307 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
308 .or_insert(cumulative_msat);
312 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
314 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
316 .entry((channel_scid, source < target))
317 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
318 .or_insert(used_msat);
321 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
323 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
324 self.0.get(&(channel_scid, source < target)).map(|v| *v)
328 impl Writeable for InFlightHtlcs {
329 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
332 impl Readable for InFlightHtlcs {
333 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
334 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
335 Ok(Self(infight_map))
339 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
340 /// that leads to it.
341 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
342 pub struct RouteHop {
343 /// The node_id of the node at this hop.
344 pub pubkey: PublicKey,
345 /// The node_announcement features of the node at this hop. For the last hop, these may be
346 /// amended to match the features present in the invoice this node generated.
347 pub node_features: NodeFeatures,
348 /// The channel that should be used from the previous hop to reach this node.
349 pub short_channel_id: u64,
350 /// The channel_announcement features of the channel that should be used from the previous hop
351 /// to reach this node.
352 pub channel_features: ChannelFeatures,
353 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
354 /// If this is the last hop in [`Path::hops`]:
355 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
356 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
358 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
360 /// The CLTV delta added for this hop.
361 /// If this is the last hop in [`Path::hops`]:
362 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
363 /// * otherwise, this is the CLTV delta expected at the destination
365 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
366 pub cltv_expiry_delta: u32,
367 /// Indicates whether this hop is possibly announced in the public network graph.
369 /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
370 /// either know for sure it's announced in the public graph, or if any public channels exist
371 /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
372 /// the channel to be unannounced.
374 /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
375 pub maybe_announced_channel: bool,
378 impl_writeable_tlv_based!(RouteHop, {
379 (0, pubkey, required),
380 (1, maybe_announced_channel, (default_value, true)),
381 (2, node_features, required),
382 (4, short_channel_id, required),
383 (6, channel_features, required),
384 (8, fee_msat, required),
385 (10, cltv_expiry_delta, required),
388 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
389 /// their [`Bolt12Invoice`].
391 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
392 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
393 pub struct BlindedTail {
394 /// The hops of the [`BlindedPath`] provided by the recipient.
396 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
397 pub hops: Vec<BlindedHop>,
398 /// The blinding point of the [`BlindedPath`] provided by the recipient.
400 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
401 pub blinding_point: PublicKey,
402 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
403 /// inferring the destination. May be 0.
404 pub excess_final_cltv_expiry_delta: u32,
405 /// The total amount paid on this [`Path`], excluding the fees.
406 pub final_value_msat: u64,
409 impl_writeable_tlv_based!(BlindedTail, {
410 (0, hops, required_vec),
411 (2, blinding_point, required),
412 (4, excess_final_cltv_expiry_delta, required),
413 (6, final_value_msat, required),
416 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
417 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
418 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
420 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
421 pub hops: Vec<RouteHop>,
422 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
423 pub blinded_tail: Option<BlindedTail>,
427 /// Gets the fees for a given path, excluding any excess paid to the recipient.
428 pub fn fee_msat(&self) -> u64 {
429 match &self.blinded_tail {
430 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
432 // Do not count last hop of each path since that's the full value of the payment
433 self.hops.split_last().map_or(0,
434 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
439 /// Gets the total amount paid on this [`Path`], excluding the fees.
440 pub fn final_value_msat(&self) -> u64 {
441 match &self.blinded_tail {
442 Some(blinded_tail) => blinded_tail.final_value_msat,
443 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
447 /// Gets the final hop's CLTV expiry delta.
448 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
449 match &self.blinded_tail {
451 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
456 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
457 /// it can take multiple paths. Each path is composed of one or more hops through the network.
458 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
460 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
461 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
463 pub paths: Vec<Path>,
464 /// The `route_params` parameter passed to [`find_route`].
466 /// This is used by `ChannelManager` to track information which may be required for retries.
468 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
469 pub route_params: Option<RouteParameters>,
473 /// Returns the total amount of fees paid on this [`Route`].
475 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
476 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
477 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
479 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
480 pub fn get_total_fees(&self) -> u64 {
481 let overpaid_value_msat = self.route_params.as_ref()
482 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
483 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
486 /// Returns the total amount paid on this [`Route`], excluding the fees.
488 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
489 /// we had to reach the [`htlc_minimum_msat`] limits.
491 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
492 pub fn get_total_amount(&self) -> u64 {
493 self.paths.iter().map(|path| path.final_value_msat()).sum()
497 impl fmt::Display for Route {
498 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
499 log_route!(self).fmt(f)
503 const SERIALIZATION_VERSION: u8 = 1;
504 const MIN_SERIALIZATION_VERSION: u8 = 1;
506 impl Writeable for Route {
507 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
508 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
509 (self.paths.len() as u64).write(writer)?;
510 let mut blinded_tails = Vec::new();
511 for (idx, path) in self.paths.iter().enumerate() {
512 (path.hops.len() as u8).write(writer)?;
513 for hop in path.hops.iter() {
516 if let Some(blinded_tail) = &path.blinded_tail {
517 if blinded_tails.is_empty() {
518 blinded_tails = Vec::with_capacity(path.hops.len());
520 blinded_tails.push(None);
523 blinded_tails.push(Some(blinded_tail));
524 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
526 write_tlv_fields!(writer, {
527 // For compatibility with LDK versions prior to 0.0.117, we take the individual
528 // RouteParameters' fields and reconstruct them on read.
529 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
530 (2, blinded_tails, optional_vec),
531 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
532 (5, self.route_params.as_ref().and_then(|p| p.max_total_routing_fee_msat), option),
538 impl Readable for Route {
539 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
540 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
541 let path_count: u64 = Readable::read(reader)?;
542 if path_count == 0 { return Err(DecodeError::InvalidValue); }
543 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
544 let mut min_final_cltv_expiry_delta = u32::max_value();
545 for _ in 0..path_count {
546 let hop_count: u8 = Readable::read(reader)?;
547 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
548 for _ in 0..hop_count {
549 hops.push(Readable::read(reader)?);
551 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
552 min_final_cltv_expiry_delta =
553 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
554 paths.push(Path { hops, blinded_tail: None });
556 _init_and_read_len_prefixed_tlv_fields!(reader, {
557 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
558 (2, blinded_tails, optional_vec),
559 (3, final_value_msat, option),
560 (5, max_total_routing_fee_msat, option)
562 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
563 if blinded_tails.len() != 0 {
564 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
565 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
566 path.blinded_tail = blinded_tail_opt;
570 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
571 let route_params = match (payment_params, final_value_msat) {
572 (Some(payment_params), Some(final_value_msat)) => {
573 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
578 Ok(Route { paths, route_params })
582 /// Parameters needed to find a [`Route`].
584 /// Passed to [`find_route`] and [`build_route_from_hops`].
585 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
586 pub struct RouteParameters {
587 /// The parameters of the failed payment path.
588 pub payment_params: PaymentParameters,
590 /// The amount in msats sent on the failed payment path.
591 pub final_value_msat: u64,
593 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
595 /// This limit also applies to the total fees that may arise while retrying failed payment
598 /// Note that values below a few sats may result in some paths being spuriously ignored.
599 pub max_total_routing_fee_msat: Option<u64>,
602 impl RouteParameters {
603 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
605 /// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
606 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
607 Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
611 impl Writeable for RouteParameters {
612 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
613 write_tlv_fields!(writer, {
614 (0, self.payment_params, required),
615 (1, self.max_total_routing_fee_msat, option),
616 (2, self.final_value_msat, required),
617 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
618 // `RouteParameters` directly. For compatibility, we write it here.
619 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
625 impl Readable for RouteParameters {
626 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
627 _init_and_read_len_prefixed_tlv_fields!(reader, {
628 (0, payment_params, (required: ReadableArgs, 0)),
629 (1, max_total_routing_fee_msat, option),
630 (2, final_value_msat, required),
631 (4, final_cltv_delta, option),
633 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
634 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
635 if final_cltv_expiry_delta == &0 {
636 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
641 final_value_msat: final_value_msat.0.unwrap(),
642 max_total_routing_fee_msat,
647 /// Maximum total CTLV difference we allow for a full payment path.
648 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
650 /// Maximum number of paths we allow an (MPP) payment to have.
651 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
652 // limits, but for now more than 10 paths likely carries too much one-path failure.
653 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
655 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
657 // The median hop CLTV expiry delta currently seen in the network.
658 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
660 // During routing, we only consider paths shorter than our maximum length estimate.
661 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
662 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
663 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
665 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
666 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
667 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
668 // (payment_secret and total_msat) = 93 bytes for the final hop.
669 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
670 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
671 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
673 /// Information used to route a payment.
674 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
675 pub struct PaymentParameters {
676 /// Information about the payee, such as their features and route hints for their channels.
679 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
680 pub expiry_time: Option<u64>,
682 /// The maximum total CLTV delta we accept for the route.
683 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
684 pub max_total_cltv_expiry_delta: u32,
686 /// The maximum number of paths that may be used by (MPP) payments.
687 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
688 pub max_path_count: u8,
690 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
691 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
692 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
693 /// increasing failure probability for those paths.
695 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
696 /// restriction have been found. While paths which meet this criteria will be searched for, it
697 /// is ultimately up to the scorer to select them over other paths.
699 /// A value of 0 will allow payments up to and including a channel's total announced usable
700 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
703 pub max_channel_saturation_power_of_half: u8,
705 /// A list of SCIDs which this payment was previously attempted over and which caused the
706 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
708 pub previously_failed_channels: Vec<u64>,
710 /// A list of indices corresponding to blinded paths in [`Payee::Blinded::route_hints`] which this
711 /// payment was previously attempted over and which caused the payment to fail. Future attempts
712 /// for the same payment shouldn't be relayed through any of these blinded paths.
713 pub previously_failed_blinded_path_idxs: 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),
735 (11, self.previously_failed_blinded_path_idxs, required_vec),
741 impl ReadableArgs<u32> for PaymentParameters {
742 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
743 _init_and_read_len_prefixed_tlv_fields!(reader, {
744 (0, payee_pubkey, option),
745 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
746 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
747 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
748 (4, clear_route_hints, required_vec),
749 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
750 (6, expiry_time, option),
751 (7, previously_failed_channels, optional_vec),
752 (8, blinded_route_hints, optional_vec),
753 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
754 (11, previously_failed_blinded_path_idxs, optional_vec),
756 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
757 let payee = if blinded_route_hints.len() != 0 {
758 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
760 route_hints: blinded_route_hints,
761 features: features.and_then(|f: Features| f.bolt12()),
765 route_hints: clear_route_hints,
766 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
767 features: features.and_then(|f| f.bolt11()),
768 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
772 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
773 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
775 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
777 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
778 previously_failed_blinded_path_idxs: previously_failed_blinded_path_idxs.unwrap_or(Vec::new()),
784 impl PaymentParameters {
785 /// Creates a payee with the node id of the given `pubkey`.
787 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
789 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
791 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
793 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
794 max_path_count: DEFAULT_MAX_PATH_COUNT,
795 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
796 previously_failed_channels: Vec::new(),
797 previously_failed_blinded_path_idxs: Vec::new(),
801 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
803 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
806 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
807 /// whether your router will be allowed to find a multi-part route for this payment. If you
808 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
809 /// [`RecipientOnionFields::secret_only`].
811 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
812 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
813 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
814 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
815 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
818 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
819 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
820 /// [`PaymentParameters::expiry_time`].
821 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
822 Self::blinded(invoice.payment_paths().to_vec())
823 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
824 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
827 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
828 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
830 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
832 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
833 max_path_count: DEFAULT_MAX_PATH_COUNT,
834 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
835 previously_failed_channels: Vec::new(),
836 previously_failed_blinded_path_idxs: Vec::new(),
840 /// Includes the payee's features. Errors if the parameters were not initialized with
841 /// [`PaymentParameters::from_bolt12_invoice`].
843 /// This is not exported to bindings users since bindings don't support move semantics
844 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
846 Payee::Clear { .. } => Err(()),
847 Payee::Blinded { route_hints, .. } =>
848 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
852 /// Includes the payee's features. Errors if the parameters were initialized with
853 /// [`PaymentParameters::from_bolt12_invoice`].
855 /// This is not exported to bindings users since bindings don't support move semantics
856 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
858 Payee::Blinded { .. } => Err(()),
859 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
861 payee: Payee::Clear {
862 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
868 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
869 /// [`PaymentParameters::from_bolt12_invoice`].
871 /// This is not exported to bindings users since bindings don't support move semantics
872 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
874 Payee::Blinded { .. } => Err(()),
875 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
877 payee: Payee::Clear {
878 route_hints, node_id, features, final_cltv_expiry_delta,
884 /// Includes a payment expiration in seconds relative to the UNIX epoch.
886 /// This is not exported to bindings users since bindings don't support move semantics
887 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
888 Self { expiry_time: Some(expiry_time), ..self }
891 /// Includes a limit for the total CLTV expiry delta which is considered during routing
893 /// This is not exported to bindings users since bindings don't support move semantics
894 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
895 Self { max_total_cltv_expiry_delta, ..self }
898 /// Includes a limit for the maximum number of payment paths that may be used.
900 /// This is not exported to bindings users since bindings don't support move semantics
901 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
902 Self { max_path_count, ..self }
905 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
906 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
908 /// This is not exported to bindings users since bindings don't support move semantics
909 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
910 Self { max_channel_saturation_power_of_half, ..self }
913 pub(crate) fn insert_previously_failed_blinded_path(&mut self, failed_blinded_tail: &BlindedTail) {
914 let mut found_blinded_tail = false;
915 for (idx, (_, path)) in self.payee.blinded_route_hints().iter().enumerate() {
916 if failed_blinded_tail.hops == path.blinded_hops &&
917 failed_blinded_tail.blinding_point == path.blinding_point
919 self.previously_failed_blinded_path_idxs.push(idx as u64);
920 found_blinded_tail = true;
923 debug_assert!(found_blinded_tail);
927 /// The recipient of a payment, differing based on whether they've hidden their identity with route
929 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
931 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
932 /// will be included in the final [`Route`].
934 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
936 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
937 /// Features supported by the payee.
939 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
941 features: Option<Bolt12InvoiceFeatures>,
943 /// The recipient included these route hints in their BOLT11 invoice.
945 /// The node id of the payee.
947 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
948 route_hints: Vec<RouteHint>,
949 /// Features supported by the payee.
951 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
952 /// does not contain any features.
954 /// [`for_keysend`]: PaymentParameters::for_keysend
955 features: Option<Bolt11InvoiceFeatures>,
956 /// The minimum CLTV delta at the end of the route. This value must not be zero.
957 final_cltv_expiry_delta: u32,
962 fn node_id(&self) -> Option<PublicKey> {
964 Self::Clear { node_id, .. } => Some(*node_id),
968 fn node_features(&self) -> Option<NodeFeatures> {
970 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
971 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
974 fn supports_basic_mpp(&self) -> bool {
976 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
977 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
980 fn features(&self) -> Option<FeaturesRef> {
982 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
983 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
986 fn final_cltv_expiry_delta(&self) -> Option<u32> {
988 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
992 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
994 Self::Blinded { route_hints, .. } => &route_hints[..],
995 Self::Clear { .. } => &[]
999 fn unblinded_route_hints(&self) -> &[RouteHint] {
1001 Self::Blinded { .. } => &[],
1002 Self::Clear { route_hints, .. } => &route_hints[..]
1007 enum FeaturesRef<'a> {
1008 Bolt11(&'a Bolt11InvoiceFeatures),
1009 Bolt12(&'a Bolt12InvoiceFeatures),
1012 Bolt11(Bolt11InvoiceFeatures),
1013 Bolt12(Bolt12InvoiceFeatures),
1017 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
1019 Self::Bolt12(f) => Some(f),
1023 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
1025 Self::Bolt11(f) => Some(f),
1031 impl<'a> Writeable for FeaturesRef<'a> {
1032 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1034 Self::Bolt11(f) => Ok(f.write(w)?),
1035 Self::Bolt12(f) => Ok(f.write(w)?),
1040 impl ReadableArgs<bool> for Features {
1041 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
1042 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
1043 Ok(Self::Bolt12(Readable::read(reader)?))
1047 /// A list of hops along a payment path terminating with a channel to the recipient.
1048 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1049 pub struct RouteHint(pub Vec<RouteHintHop>);
1051 impl Writeable for RouteHint {
1052 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1053 (self.0.len() as u64).write(writer)?;
1054 for hop in self.0.iter() {
1061 impl Readable for RouteHint {
1062 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1063 let hop_count: u64 = Readable::read(reader)?;
1064 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
1065 for _ in 0..hop_count {
1066 hops.push(Readable::read(reader)?);
1072 /// A channel descriptor for a hop along a payment path.
1074 /// While this generally comes from BOLT 11's `r` field, this struct includes more fields than are
1075 /// available in BOLT 11. Thus, encoding and decoding this via `lightning-invoice` is lossy, as
1076 /// fields not supported in BOLT 11 will be stripped.
1077 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1078 pub struct RouteHintHop {
1079 /// The node_id of the non-target end of the route
1080 pub src_node_id: PublicKey,
1081 /// The short_channel_id of this channel
1082 pub short_channel_id: u64,
1083 /// The fees which must be paid to use this channel
1084 pub fees: RoutingFees,
1085 /// The difference in CLTV values between this node and the next node.
1086 pub cltv_expiry_delta: u16,
1087 /// The minimum value, in msat, which must be relayed to the next hop.
1088 pub htlc_minimum_msat: Option<u64>,
1089 /// The maximum value in msat available for routing with a single HTLC.
1090 pub htlc_maximum_msat: Option<u64>,
1093 impl_writeable_tlv_based!(RouteHintHop, {
1094 (0, src_node_id, required),
1095 (1, htlc_minimum_msat, option),
1096 (2, short_channel_id, required),
1097 (3, htlc_maximum_msat, option),
1098 (4, fees, required),
1099 (6, cltv_expiry_delta, required),
1102 #[derive(Eq, PartialEq)]
1103 #[repr(align(64))] // Force the size to 64 bytes
1104 struct RouteGraphNode {
1107 // The maximum value a yet-to-be-constructed payment path might flow through this node.
1108 // This value is upper-bounded by us by:
1109 // - how much is needed for a path being constructed
1110 // - how much value can channels following this node (up to the destination) can contribute,
1111 // considering their capacity and fees
1112 value_contribution_msat: u64,
1113 total_cltv_delta: u32,
1114 /// The number of hops walked up to this node.
1115 path_length_to_node: u8,
1118 impl cmp::Ord for RouteGraphNode {
1119 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
1120 other.score.cmp(&self.score).then_with(|| other.node_id.cmp(&self.node_id))
1124 impl cmp::PartialOrd for RouteGraphNode {
1125 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
1126 Some(self.cmp(other))
1130 // While RouteGraphNode can be laid out with fewer bytes, performance appears to be improved
1131 // substantially when it is laid out at exactly 64 bytes.
1133 // Thus, we use `#[repr(C)]` on the struct to force a suboptimal layout and check that it stays 64
1135 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1136 const _GRAPH_NODE_SMALL: usize = 64 - core::mem::size_of::<RouteGraphNode>();
1137 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1138 const _GRAPH_NODE_FIXED_SIZE: usize = core::mem::size_of::<RouteGraphNode>() - 64;
1140 /// A [`CandidateRouteHop::FirstHop`] entry.
1141 #[derive(Clone, Debug)]
1142 pub struct FirstHopCandidate<'a> {
1143 /// Channel details of the first hop
1145 /// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1146 /// has been funded and is able to pay), and accessor methods may panic otherwise.
1148 /// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1150 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1151 pub details: &'a ChannelDetails,
1152 /// The node id of the payer, which is also the source side of this candidate route hop.
1154 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1155 pub payer_node_id: &'a NodeId,
1158 /// A [`CandidateRouteHop::PublicHop`] entry.
1159 #[derive(Clone, Debug)]
1160 pub struct PublicHopCandidate<'a> {
1161 /// Information about the channel, including potentially its capacity and
1162 /// direction-specific information.
1164 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1165 pub info: DirectedChannelInfo<'a>,
1166 /// The short channel ID of the channel, i.e. the identifier by which we refer to this
1168 pub short_channel_id: u64,
1171 /// A [`CandidateRouteHop::PrivateHop`] entry.
1172 #[derive(Clone, Debug)]
1173 pub struct PrivateHopCandidate<'a> {
1174 /// Information about the private hop communicated via BOLT 11.
1176 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1177 pub hint: &'a RouteHintHop,
1178 /// Node id of the next hop in BOLT 11 route hint.
1180 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1181 pub target_node_id: &'a NodeId
1184 /// A [`CandidateRouteHop::Blinded`] entry.
1185 #[derive(Clone, Debug)]
1186 pub struct BlindedPathCandidate<'a> {
1187 /// Information about the blinded path including the fee, HTLC amount limits, and
1188 /// cryptographic material required to build an HTLC through the given path.
1190 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1191 pub hint: &'a (BlindedPayInfo, BlindedPath),
1192 /// Index of the hint in the original list of blinded hints.
1194 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1195 /// a short channel ID for this hop.
1199 /// A [`CandidateRouteHop::OneHopBlinded`] entry.
1200 #[derive(Clone, Debug)]
1201 pub struct OneHopBlindedPathCandidate<'a> {
1202 /// Information about the blinded path including the fee, HTLC amount limits, and
1203 /// cryptographic material required to build an HTLC terminating with the given path.
1205 /// Note that the [`BlindedPayInfo`] is ignored here.
1207 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1208 pub hint: &'a (BlindedPayInfo, BlindedPath),
1209 /// Index of the hint in the original list of blinded hints.
1211 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1212 /// a short channel ID for this hop.
1216 /// A wrapper around the various hop representations.
1218 /// Can be used to examine the properties of a hop,
1219 /// potentially to decide whether to include it in a route.
1220 #[derive(Clone, Debug)]
1221 pub enum CandidateRouteHop<'a> {
1222 /// A hop from the payer, where the outbound liquidity is known.
1223 FirstHop(FirstHopCandidate<'a>),
1224 /// A hop found in the [`ReadOnlyNetworkGraph`].
1225 PublicHop(PublicHopCandidate<'a>),
1226 /// A private hop communicated by the payee, generally via a BOLT 11 invoice.
1228 /// Because BOLT 11 route hints can take multiple hops to get to the destination, this may not
1229 /// terminate at the payee.
1230 PrivateHop(PrivateHopCandidate<'a>),
1231 /// A blinded path which starts with an introduction point and ultimately terminates with the
1234 /// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1235 /// `None` in this state.
1237 /// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1238 /// path, the full path is treated as a single [`CandidateRouteHop`].
1239 Blinded(BlindedPathCandidate<'a>),
1240 /// Similar to [`Self::Blinded`], but the path here only has one hop.
1242 /// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1243 /// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1244 /// payee's identity - it's the introduction point!
1246 /// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1247 /// to the hops *between* the introduction node and the destination.
1249 /// This primarily exists to track that we need to included a blinded path at the end of our
1250 /// [`Route`], even though it doesn't actually add an additional hop in the payment.
1251 OneHopBlinded(OneHopBlindedPathCandidate<'a>),
1254 impl<'a> CandidateRouteHop<'a> {
1255 /// Returns the short channel ID for this hop, if one is known.
1257 /// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1258 /// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1260 /// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1261 /// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1262 /// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1263 /// (which is always true for channels which are funded and ready for use).
1265 /// In other words, this should always return `Some` as long as the candidate hop is not a
1266 /// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1268 /// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1269 /// define a global namespace.
1271 fn short_channel_id(&self) -> Option<u64> {
1273 CandidateRouteHop::FirstHop(hop) => hop.details.get_outbound_payment_scid(),
1274 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1275 CandidateRouteHop::PrivateHop(hop) => Some(hop.hint.short_channel_id),
1276 CandidateRouteHop::Blinded(_) => None,
1277 CandidateRouteHop::OneHopBlinded(_) => None,
1281 /// Returns the globally unique short channel ID for this hop, if one is known.
1283 /// This only returns `Some` if the channel is public (either our own, or one we've learned
1284 /// from the public network graph), and thus the short channel ID we have for this channel is
1285 /// globally unique and identifies this channel in a global namespace.
1287 pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1289 CandidateRouteHop::FirstHop(hop) => if hop.details.is_public { hop.details.short_channel_id } else { None },
1290 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1291 CandidateRouteHop::PrivateHop(_) => None,
1292 CandidateRouteHop::Blinded(_) => None,
1293 CandidateRouteHop::OneHopBlinded(_) => None,
1297 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1298 fn features(&self) -> ChannelFeatures {
1300 CandidateRouteHop::FirstHop(hop) => hop.details.counterparty.features.to_context(),
1301 CandidateRouteHop::PublicHop(hop) => hop.info.channel().features.clone(),
1302 CandidateRouteHop::PrivateHop(_) => ChannelFeatures::empty(),
1303 CandidateRouteHop::Blinded(_) => ChannelFeatures::empty(),
1304 CandidateRouteHop::OneHopBlinded(_) => ChannelFeatures::empty(),
1308 /// Returns the required difference in HTLC CLTV expiry between the [`Self::source`] and the
1309 /// next-hop for an HTLC taking this hop.
1311 /// This is the time that the node(s) in this hop have to claim the HTLC on-chain if the
1312 /// next-hop goes on chain with a payment preimage.
1314 pub fn cltv_expiry_delta(&self) -> u32 {
1316 CandidateRouteHop::FirstHop(_) => 0,
1317 CandidateRouteHop::PublicHop(hop) => hop.info.direction().cltv_expiry_delta as u32,
1318 CandidateRouteHop::PrivateHop(hop) => hop.hint.cltv_expiry_delta as u32,
1319 CandidateRouteHop::Blinded(hop) => hop.hint.0.cltv_expiry_delta as u32,
1320 CandidateRouteHop::OneHopBlinded(_) => 0,
1324 /// Returns the minimum amount that can be sent over this hop, in millisatoshis.
1326 pub fn htlc_minimum_msat(&self) -> u64 {
1328 CandidateRouteHop::FirstHop(hop) => hop.details.next_outbound_htlc_minimum_msat,
1329 CandidateRouteHop::PublicHop(hop) => hop.info.direction().htlc_minimum_msat,
1330 CandidateRouteHop::PrivateHop(hop) => hop.hint.htlc_minimum_msat.unwrap_or(0),
1331 CandidateRouteHop::Blinded(hop) => hop.hint.0.htlc_minimum_msat,
1332 CandidateRouteHop::OneHopBlinded { .. } => 0,
1336 /// Returns the fees that must be paid to route an HTLC over this channel.
1338 pub fn fees(&self) -> RoutingFees {
1340 CandidateRouteHop::FirstHop(_) => RoutingFees {
1341 base_msat: 0, proportional_millionths: 0,
1343 CandidateRouteHop::PublicHop(hop) => hop.info.direction().fees,
1344 CandidateRouteHop::PrivateHop(hop) => hop.hint.fees,
1345 CandidateRouteHop::Blinded(hop) => {
1347 base_msat: hop.hint.0.fee_base_msat,
1348 proportional_millionths: hop.hint.0.fee_proportional_millionths
1351 CandidateRouteHop::OneHopBlinded(_) =>
1352 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1356 /// Fetch the effective capacity of this hop.
1358 /// Note that this may be somewhat expensive, so calls to this should be limited and results
1360 fn effective_capacity(&self) -> EffectiveCapacity {
1362 CandidateRouteHop::FirstHop(hop) => EffectiveCapacity::ExactLiquidity {
1363 liquidity_msat: hop.details.next_outbound_htlc_limit_msat,
1365 CandidateRouteHop::PublicHop(hop) => hop.info.effective_capacity(),
1366 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. }) =>
1367 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1368 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. }) =>
1369 EffectiveCapacity::Infinite,
1370 CandidateRouteHop::Blinded(hop) =>
1371 EffectiveCapacity::HintMaxHTLC { amount_msat: hop.hint.0.htlc_maximum_msat },
1372 CandidateRouteHop::OneHopBlinded(_) => EffectiveCapacity::Infinite,
1376 /// Returns an ID describing the given hop.
1378 /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1380 fn id(&self) -> CandidateHopId {
1382 CandidateRouteHop::Blinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1383 CandidateRouteHop::OneHopBlinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1384 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1387 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1389 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1395 fn blinded_hint_idx(&self) -> Option<usize> {
1397 Self::Blinded(BlindedPathCandidate { hint_idx, .. }) |
1398 Self::OneHopBlinded(OneHopBlindedPathCandidate { hint_idx, .. }) => {
1404 /// Returns the source node id of current hop.
1406 /// Source node id refers to the node forwarding the HTLC through this hop.
1408 /// For [`Self::FirstHop`] we return payer's node id.
1410 pub fn source(&self) -> NodeId {
1412 CandidateRouteHop::FirstHop(hop) => *hop.payer_node_id,
1413 CandidateRouteHop::PublicHop(hop) => *hop.info.source(),
1414 CandidateRouteHop::PrivateHop(hop) => hop.hint.src_node_id.into(),
1415 CandidateRouteHop::Blinded(hop) => hop.hint.1.introduction_node_id.into(),
1416 CandidateRouteHop::OneHopBlinded(hop) => hop.hint.1.introduction_node_id.into(),
1419 /// Returns the target node id of this hop, if known.
1421 /// Target node id refers to the node receiving the HTLC after this hop.
1423 /// For [`Self::Blinded`] we return `None` because the ultimate destination after the blinded
1424 /// path is unknown.
1426 /// For [`Self::OneHopBlinded`] we return `None` because the target is the same as the source,
1427 /// and such a return value would be somewhat nonsensical.
1429 pub fn target(&self) -> Option<NodeId> {
1431 CandidateRouteHop::FirstHop(hop) => Some(hop.details.counterparty.node_id.into()),
1432 CandidateRouteHop::PublicHop(hop) => Some(*hop.info.target()),
1433 CandidateRouteHop::PrivateHop(hop) => Some(*hop.target_node_id),
1434 CandidateRouteHop::Blinded(_) => None,
1435 CandidateRouteHop::OneHopBlinded(_) => None,
1440 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1442 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1444 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1445 /// isn't guaranteed to be unique at all.
1447 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1448 /// difficult-to-use API.
1449 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1450 enum CandidateHopId {
1451 /// Contains (scid, src_node_id < target_node_id)
1453 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1458 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1459 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1461 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1462 EffectiveCapacity::Infinite => u64::max_value(),
1463 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1464 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1465 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1466 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1467 // expected to have been generated from up-to-date capacity information.
1468 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1469 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1470 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1474 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1475 -> bool where I1::Item: PartialEq<I2::Item> {
1477 let a = iter_a.next();
1478 let b = iter_b.next();
1479 if a.is_none() && b.is_none() { return true; }
1480 if a.is_none() || b.is_none() { return false; }
1481 if a.unwrap().ne(&b.unwrap()) { return false; }
1485 /// It's useful to keep track of the hops associated with the fees required to use them,
1486 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1487 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1488 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1490 #[repr(C)] // Force fields to appear in the order we define them.
1491 struct PathBuildingHop<'a> {
1492 candidate: CandidateRouteHop<'a>,
1493 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1494 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1495 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1496 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1497 /// avoid processing them again.
1498 was_processed: bool,
1499 /// Used to compare channels when choosing the for routing.
1500 /// Includes paying for the use of a hop and the following hops, as well as
1501 /// an estimated cost of reaching this hop.
1502 /// Might get stale when fees are recomputed. Primarily for internal use.
1503 total_fee_msat: u64,
1504 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1505 /// walk and may be invalid thereafter.
1506 path_htlc_minimum_msat: u64,
1507 /// All penalties incurred from this channel on the way to the destination, as calculated using
1508 /// channel scoring.
1509 path_penalty_msat: u64,
1511 // The last 16 bytes are on the next cache line by default in glibc's malloc. Thus, we should
1512 // only place fields which are not hot there. Luckily, the next three fields are only read if
1513 // we end up on the selected path, and only in the final path layout phase, so we don't care
1514 // too much if reading them is slow.
1518 /// All the fees paid *after* this channel on the way to the destination
1519 next_hops_fee_msat: u64,
1520 /// Fee paid for the use of the current channel (see candidate.fees()).
1521 /// The value will be actually deducted from the counterparty balance on the previous link.
1522 hop_use_fee_msat: u64,
1524 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1525 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1526 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1527 // value_contribution_msat, which requires tracking it here. See comments below where it is
1528 // used for more info.
1529 value_contribution_msat: u64,
1532 // Checks that the entries in the `find_route` `dist` map fit in (exactly) two standard x86-64
1533 // cache lines. Sadly, they're not guaranteed to actually lie on a cache line (and in fact,
1534 // generally won't, because at least glibc's malloc will align to a nice, big, round
1535 // boundary...plus 16), but at least it will reduce the amount of data we'll need to load.
1537 // Note that these assertions only pass on somewhat recent rustc, and thus are gated on the
1540 const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::<(NodeId, PathBuildingHop)>();
1542 const _NODE_MAP_SIZE_EXACTLY_CACHE_LINES: usize = core::mem::size_of::<(NodeId, PathBuildingHop)>() - 128;
1544 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1545 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1546 let mut debug_struct = f.debug_struct("PathBuildingHop");
1548 .field("node_id", &self.candidate.target())
1549 .field("short_channel_id", &self.candidate.short_channel_id())
1550 .field("total_fee_msat", &self.total_fee_msat)
1551 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1552 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1553 .field("total_fee_msat - (next_hops_fee_msat + hop_use_fee_msat)", &(&self.total_fee_msat - (&self.next_hops_fee_msat + &self.hop_use_fee_msat)))
1554 .field("path_penalty_msat", &self.path_penalty_msat)
1555 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1556 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1557 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1558 let debug_struct = debug_struct
1559 .field("value_contribution_msat", &self.value_contribution_msat);
1560 debug_struct.finish()
1564 // Instantiated with a list of hops with correct data in them collected during path finding,
1565 // an instance of this struct should be further modified only via given methods.
1567 struct PaymentPath<'a> {
1568 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1571 impl<'a> PaymentPath<'a> {
1572 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1573 fn get_value_msat(&self) -> u64 {
1574 self.hops.last().unwrap().0.fee_msat
1577 fn get_path_penalty_msat(&self) -> u64 {
1578 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1581 fn get_total_fee_paid_msat(&self) -> u64 {
1582 if self.hops.len() < 1 {
1586 // Can't use next_hops_fee_msat because it gets outdated.
1587 for (i, (hop, _)) in self.hops.iter().enumerate() {
1588 if i != self.hops.len() - 1 {
1589 result += hop.fee_msat;
1595 fn get_cost_msat(&self) -> u64 {
1596 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1599 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1600 // to change fees may result in an inconsistency.
1602 // Sometimes we call this function right after constructing a path which is inconsistent in
1603 // that it the value being transferred has decreased while we were doing path finding, leading
1604 // to the fees being paid not lining up with the actual limits.
1606 // Note that this function is not aware of the available_liquidity limit, and thus does not
1607 // support increasing the value being transferred beyond what was selected during the initial
1610 // Returns the amount that this path contributes to the total payment value, which may be greater
1611 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1612 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1613 let mut extra_contribution_msat = 0;
1614 let mut total_fee_paid_msat = 0 as u64;
1615 for i in (0..self.hops.len()).rev() {
1616 let last_hop = i == self.hops.len() - 1;
1618 // For non-last-hop, this value will represent the fees paid on the current hop. It
1619 // will consist of the fees for the use of the next hop, and extra fees to match
1620 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1621 let mut cur_hop_fees_msat = 0;
1623 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1626 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1627 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1628 cur_hop.path_penalty_msat += extra_contribution_msat;
1629 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1630 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1631 // set it too high just to maliciously take more fees by exploiting this
1632 // match htlc_minimum_msat logic.
1633 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1634 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1635 // Note that there is a risk that *previous hops* (those closer to us, as we go
1636 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1638 // This might make us end up with a broken route, although this should be super-rare
1639 // in practice, both because of how healthy channels look like, and how we pick
1640 // channels in add_entry.
1641 // Also, this can't be exploited more heavily than *announce a free path and fail
1643 cur_hop_transferred_amount_msat += extra_fees_msat;
1645 // We remember and return the extra fees on the final hop to allow accounting for
1646 // them in the path's value contribution.
1648 extra_contribution_msat = extra_fees_msat;
1650 total_fee_paid_msat += extra_fees_msat;
1651 cur_hop_fees_msat += extra_fees_msat;
1656 // Final hop is a special case: it usually has just value_msat (by design), but also
1657 // it still could overpay for the htlc_minimum_msat.
1658 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1660 // Propagate updated fees for the use of the channels to one hop back, where they
1661 // will be actually paid (fee_msat). The last hop is handled above separately.
1662 cur_hop.fee_msat = cur_hop_fees_msat;
1665 // Fee for the use of the current hop which will be deducted on the previous hop.
1666 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1667 // this channel is free for us.
1669 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1670 cur_hop.hop_use_fee_msat = new_fee;
1671 total_fee_paid_msat += new_fee;
1673 // It should not be possible because this function is called only to reduce the
1674 // value. In that case, compute_fee was already called with the same fees for
1675 // larger amount and there was no overflow.
1680 value_msat + extra_contribution_msat
1685 /// Calculate the fees required to route the given amount over a channel with the given fees.
1686 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1687 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1688 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1692 /// Calculate the fees required to route the given amount over a channel with the given fees,
1693 /// saturating to [`u64::max_value`].
1694 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1695 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1696 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1697 .saturating_add(channel_fees.base_msat as u64)
1700 /// The default `features` we assume for a node in a route, when no `features` are known about that
1703 /// Default features are:
1704 /// * variable_length_onion_optional
1705 fn default_node_features() -> NodeFeatures {
1706 let mut features = NodeFeatures::empty();
1707 features.set_variable_length_onion_optional();
1711 struct LoggedPayeePubkey(Option<PublicKey>);
1712 impl fmt::Display for LoggedPayeePubkey {
1713 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1716 "payee node id ".fmt(f)?;
1720 "blinded payee".fmt(f)
1726 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1727 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1728 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1730 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1731 "blinded route hint with introduction node id ".fmt(f)?;
1732 hint.1.introduction_node_id.fmt(f)?;
1733 " and blinding point ".fmt(f)?;
1734 hint.1.blinding_point.fmt(f)
1736 CandidateRouteHop::FirstHop(_) => {
1737 "first hop with SCID ".fmt(f)?;
1738 self.0.short_channel_id().unwrap().fmt(f)
1740 CandidateRouteHop::PrivateHop(_) => {
1741 "route hint with SCID ".fmt(f)?;
1742 self.0.short_channel_id().unwrap().fmt(f)
1746 self.0.short_channel_id().unwrap().fmt(f)
1753 fn sort_first_hop_channels(
1754 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1755 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1757 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1758 // most like to use.
1760 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1761 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1764 // Second, because simply always sorting in descending order would always use our largest
1765 // available outbound capacity, needlessly fragmenting our available channel capacities,
1766 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1767 // which have enough, but not too much, capacity for the payment.
1769 // Available outbound balances factor in liquidity already reserved for previously found paths.
1770 channels.sort_unstable_by(|chan_a, chan_b| {
1771 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1772 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1773 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1774 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1775 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1776 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1777 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1778 // Sort in descending order
1779 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1781 // Sort in ascending order
1782 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1787 /// Finds a route from us (payer) to the given target node (payee).
1789 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1790 /// in the given [`RouteParameters::payment_params`].
1791 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1793 /// Private routing paths between a public node and the target may be included in the `payee` field
1794 /// of [`RouteParameters::payment_params`].
1796 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1797 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1798 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1800 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1801 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1802 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1806 /// Panics if first_hops contains channels without `short_channel_id`s;
1807 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1809 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1810 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1811 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1812 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1813 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1814 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1815 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1816 ) -> Result<Route, LightningError>
1817 where L::Target: Logger, GL::Target: Logger {
1818 let graph_lock = network_graph.read_only();
1819 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1820 scorer, score_params, random_seed_bytes)?;
1821 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1825 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1826 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1827 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1828 _random_seed_bytes: &[u8; 32]
1829 ) -> Result<Route, LightningError>
1830 where L::Target: Logger {
1832 let payment_params = &route_params.payment_params;
1833 let final_value_msat = route_params.final_value_msat;
1834 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1835 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1836 // so use a dummy id for this in the blinded case.
1837 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1838 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1839 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1840 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1841 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1843 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1844 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1846 if our_node_id == maybe_dummy_payee_node_id {
1847 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1850 if final_value_msat > MAX_VALUE_MSAT {
1851 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1854 if final_value_msat == 0 {
1855 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1858 match &payment_params.payee {
1859 Payee::Clear { route_hints, node_id, .. } => {
1860 for route in route_hints.iter() {
1861 for hop in &route.0 {
1862 if hop.src_node_id == *node_id {
1863 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1868 Payee::Blinded { route_hints, .. } => {
1869 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1870 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});
1872 for (_, blinded_path) in route_hints.iter() {
1873 if blinded_path.blinded_hops.len() == 0 {
1874 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1875 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1876 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1877 } else if blinded_path.blinded_hops.len() == 1 &&
1878 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1879 && p.introduction_node_id != blinded_path.introduction_node_id)
1881 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1886 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1887 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1888 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});
1891 // The general routing idea is the following:
1892 // 1. Fill first/last hops communicated by the caller.
1893 // 2. Attempt to construct a path from payer to payee for transferring
1894 // any ~sufficient (described later) value.
1895 // If succeed, remember which channels were used and how much liquidity they have available,
1896 // so that future paths don't rely on the same liquidity.
1897 // 3. Proceed to the next step if:
1898 // - we hit the recommended target value;
1899 // - OR if we could not construct a new path. Any next attempt will fail too.
1900 // Otherwise, repeat step 2.
1901 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1902 // (not recommended value).
1903 // 5. If yes, proceed. If not, fail routing.
1904 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1905 // transferred up to the transfer target value.
1906 // 7. Reduce the value of the last path until we are sending only the target value.
1907 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1908 // them so that we're not sending two HTLCs along the same path.
1910 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1911 // distance from the payee
1913 // We are not a faithful Dijkstra's implementation because we can change values which impact
1914 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1915 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1916 // the value we are currently attempting to send over a path, we simply reduce the value being
1917 // sent along the path for any hops after that channel. This may imply that later fees (which
1918 // we've already tabulated) are lower because a smaller value is passing through the channels
1919 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1920 // channels which were selected earlier (and which may still be used for other paths without a
1921 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1924 // One potentially problematic case for this algorithm would be if there are many
1925 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1926 // graph walking), we may never find a path which is not liquidity-limited and has lower
1927 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1928 // Because we only consider paths with at least 5% of the total value being sent, the damage
1929 // from such a case should be limited, however this could be further reduced in the future by
1930 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1931 // limits for the purposes of fee calculation.
1933 // Alternatively, we could store more detailed path information in the heap (targets, below)
1934 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1935 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1936 // and practically (as we would need to store dynamically-allocated path information in heap
1937 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1938 // results of such an algorithm would likely be biased towards lower-value paths.
1940 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1941 // outside of our current search value, running a path search more times to gather candidate
1942 // paths at different values. While this may be acceptable, further path searches may increase
1943 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1944 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1945 // the same time, remaining generic across different payment values.
1947 let network_channels = network_graph.channels();
1948 let network_nodes = network_graph.nodes();
1950 if payment_params.max_path_count == 0 {
1951 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1954 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1955 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1957 let allow_mpp = if payment_params.max_path_count == 1 {
1959 } else if payment_params.payee.supports_basic_mpp() {
1961 } else if let Some(payee) = payee_node_id_opt {
1962 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1963 |info| info.features.supports_basic_mpp()))
1966 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1968 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph with a fee limit of {} msat",
1969 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
1970 if allow_mpp { "with" } else { "without" },
1971 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " },
1972 max_total_routing_fee_msat);
1975 // Prepare the data we'll use for payee-to-payer search by
1976 // inserting first hops suggested by the caller as targets.
1977 // Our search will then attempt to reach them while traversing from the payee node.
1978 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1979 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1980 if let Some(hops) = first_hops {
1982 if chan.get_outbound_payment_scid().is_none() {
1983 panic!("first_hops should be filled in with usable channels, not pending ones");
1985 if chan.counterparty.node_id == *our_node_pubkey {
1986 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1989 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1990 .or_insert(Vec::new())
1993 if first_hop_targets.is_empty() {
1994 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1998 let mut private_hop_key_cache = HashMap::with_capacity(
1999 payment_params.payee.unblinded_route_hints().iter().map(|path| path.0.len()).sum()
2002 // Because we store references to private hop node_ids in `dist`, below, we need them to exist
2003 // (as `NodeId`, not `PublicKey`) for the lifetime of `dist`. Thus, we calculate all the keys
2004 // we'll need here and simply fetch them when routing.
2005 private_hop_key_cache.insert(maybe_dummy_payee_pk, NodeId::from_pubkey(&maybe_dummy_payee_pk));
2006 for route in payment_params.payee.unblinded_route_hints().iter() {
2007 for hop in route.0.iter() {
2008 private_hop_key_cache.insert(hop.src_node_id, NodeId::from_pubkey(&hop.src_node_id));
2012 // The main heap containing all candidate next-hops sorted by their score (max(fee,
2013 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
2014 // adding duplicate entries when we find a better path to a given node.
2015 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
2017 // Map from node_id to information about the best current path to that node, including feerate
2019 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
2021 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
2022 // indicating that we may wish to try again with a higher value, potentially paying to meet an
2023 // htlc_minimum with extra fees while still finding a cheaper path.
2024 let mut hit_minimum_limit;
2026 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
2027 // We start with a path_value of the exact amount we want, and if that generates a route we may
2028 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
2029 // amount we want in total across paths, selecting the best subset at the end.
2030 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
2031 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
2032 let mut path_value_msat = final_value_msat;
2034 // Routing Fragmentation Mitigation heuristic:
2036 // Routing fragmentation across many payment paths increases the overall routing
2037 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
2038 // Taking too many smaller paths also increases the chance of payment failure.
2039 // Thus to avoid this effect, we require from our collected links to provide
2040 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
2041 // This requirement is currently set to be 1/max_path_count of the payment
2042 // value to ensure we only ever return routes that do not violate this limit.
2043 let minimal_value_contribution_msat: u64 = if allow_mpp {
2044 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
2049 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
2050 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
2051 // drop the requirement by setting this to 0.
2052 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
2054 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
2055 // determine if the channel can be used by additional MPP paths or to inform path finding
2056 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
2057 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
2059 let mut used_liquidities: HashMap<CandidateHopId, u64> =
2060 HashMap::with_capacity(network_nodes.len());
2062 // Keeping track of how much value we already collected across other paths. Helps to decide
2063 // when we want to stop looking for new paths.
2064 let mut already_collected_value_msat = 0;
2066 for (_, channels) in first_hop_targets.iter_mut() {
2067 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
2071 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
2072 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
2074 // Remember how many candidates we ignored to allow for some logging afterwards.
2075 let mut num_ignored_value_contribution: u32 = 0;
2076 let mut num_ignored_path_length_limit: u32 = 0;
2077 let mut num_ignored_cltv_delta_limit: u32 = 0;
2078 let mut num_ignored_previously_failed: u32 = 0;
2079 let mut num_ignored_total_fee_limit: u32 = 0;
2080 let mut num_ignored_avoid_overpayment: u32 = 0;
2081 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
2083 macro_rules! add_entry {
2084 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
2085 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
2086 // since that value has to be transferred over this channel.
2087 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
2088 ( $candidate: expr, $next_hops_fee_msat: expr,
2089 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
2090 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
2091 // We "return" whether we updated the path at the end, and how much we can route via
2092 // this channel, via this:
2093 let mut hop_contribution_amt_msat = None;
2094 // Channels to self should not be used. This is more of belt-and-suspenders, because in
2095 // practice these cases should be caught earlier:
2096 // - for regular channels at channel announcement (TODO)
2097 // - for first and last hops early in get_route
2098 let src_node_id = $candidate.source();
2099 if Some(src_node_id) != $candidate.target() {
2100 let scid_opt = $candidate.short_channel_id();
2101 let effective_capacity = $candidate.effective_capacity();
2102 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
2104 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
2105 // It may be misleading because we might later choose to reduce the value transferred
2106 // over these channels, and the channel which was insufficient might become sufficient.
2107 // Worst case: we drop a good channel here because it can't cover the high following
2108 // fees caused by one expensive channel, but then this channel could have been used
2109 // if the amount being transferred over this path is lower.
2110 // We do this for now, but this is a subject for removal.
2111 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
2112 let used_liquidity_msat = used_liquidities
2113 .get(&$candidate.id())
2114 .map_or(0, |used_liquidity_msat| {
2115 available_value_contribution_msat = available_value_contribution_msat
2116 .saturating_sub(*used_liquidity_msat);
2117 *used_liquidity_msat
2120 // Verify the liquidity offered by this channel complies to the minimal contribution.
2121 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
2122 // Do not consider candidate hops that would exceed the maximum path length.
2123 let path_length_to_node = $next_hops_path_length + 1;
2124 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
2126 // Do not consider candidates that exceed the maximum total cltv expiry limit.
2127 // In order to already account for some of the privacy enhancing random CLTV
2128 // expiry delta offset we add on top later, we subtract a rough estimate
2129 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
2130 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
2131 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
2132 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
2133 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
2134 .saturating_add($candidate.cltv_expiry_delta());
2135 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
2137 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
2138 // Includes paying fees for the use of the following channels.
2139 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
2140 Some(result) => result,
2141 // Can't overflow due to how the values were computed right above.
2142 None => unreachable!(),
2144 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2145 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
2146 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
2148 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2149 let may_overpay_to_meet_path_minimum_msat =
2150 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
2151 recommended_value_msat >= $candidate.htlc_minimum_msat()) ||
2152 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
2153 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
2155 let payment_failed_on_this_channel = match scid_opt {
2156 Some(scid) => payment_params.previously_failed_channels.contains(&scid),
2157 None => match $candidate.blinded_hint_idx() {
2159 payment_params.previously_failed_blinded_path_idxs.contains(&(idx as u64))
2165 let (should_log_candidate, first_hop_details) = match $candidate {
2166 CandidateRouteHop::FirstHop(hop) => (true, Some(hop.details)),
2167 CandidateRouteHop::PrivateHop(_) => (true, None),
2168 CandidateRouteHop::Blinded(_) => (true, None),
2169 CandidateRouteHop::OneHopBlinded(_) => (true, None),
2173 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
2174 // bother considering this channel. If retrying with recommended_value_msat may
2175 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
2176 // around again with a higher amount.
2177 if !contributes_sufficient_value {
2178 if should_log_candidate {
2179 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
2181 if let Some(details) = first_hop_details {
2183 "First hop candidate next_outbound_htlc_limit_msat: {}",
2184 details.next_outbound_htlc_limit_msat,
2188 num_ignored_value_contribution += 1;
2189 } else if exceeds_max_path_length {
2190 if should_log_candidate {
2191 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
2193 num_ignored_path_length_limit += 1;
2194 } else if exceeds_cltv_delta_limit {
2195 if should_log_candidate {
2196 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
2198 if let Some(_) = first_hop_details {
2200 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
2201 hop_total_cltv_delta,
2202 max_total_cltv_expiry_delta,
2206 num_ignored_cltv_delta_limit += 1;
2207 } else if payment_failed_on_this_channel {
2208 if should_log_candidate {
2209 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
2211 num_ignored_previously_failed += 1;
2212 } else if may_overpay_to_meet_path_minimum_msat {
2213 if should_log_candidate {
2215 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit.",
2216 LoggedCandidateHop(&$candidate));
2218 if let Some(details) = first_hop_details {
2220 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2221 details.next_outbound_htlc_minimum_msat,
2225 num_ignored_avoid_overpayment += 1;
2226 hit_minimum_limit = true;
2227 } else if over_path_minimum_msat {
2228 // Note that low contribution here (limited by available_liquidity_msat)
2229 // might violate htlc_minimum_msat on the hops which are next along the
2230 // payment path (upstream to the payee). To avoid that, we recompute
2231 // path fees knowing the final path contribution after constructing it.
2232 let curr_min = cmp::max(
2233 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
2235 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
2236 .saturating_add(curr_min);
2237 let hm_entry = dist.entry(src_node_id);
2238 let old_entry = hm_entry.or_insert_with(|| {
2239 // If there was previously no known way to access the source node
2240 // (recall it goes payee-to-payer) of short_channel_id, first add a
2241 // semi-dummy record just to compute the fees to reach the source node.
2242 // This will affect our decision on selecting short_channel_id
2243 // as a way to reach the $candidate.target() node.
2245 candidate: $candidate.clone(),
2247 next_hops_fee_msat: u64::max_value(),
2248 hop_use_fee_msat: u64::max_value(),
2249 total_fee_msat: u64::max_value(),
2250 path_htlc_minimum_msat,
2251 path_penalty_msat: u64::max_value(),
2252 was_processed: false,
2253 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2254 value_contribution_msat,
2258 #[allow(unused_mut)] // We only use the mut in cfg(test)
2259 let mut should_process = !old_entry.was_processed;
2260 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2262 // In test/fuzzing builds, we do extra checks to make sure the skipping
2263 // of already-seen nodes only happens in cases we expect (see below).
2264 if !should_process { should_process = true; }
2268 let mut hop_use_fee_msat = 0;
2269 let mut total_fee_msat: u64 = $next_hops_fee_msat;
2271 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2272 // will have the same effective-fee
2273 if src_node_id != our_node_id {
2274 // Note that `u64::max_value` means we'll always fail the
2275 // `old_entry.total_fee_msat > total_fee_msat` check below
2276 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
2277 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2280 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2281 if total_fee_msat > max_total_routing_fee_msat {
2282 if should_log_candidate {
2283 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2285 if let Some(_) = first_hop_details {
2287 "First hop candidate routing fee: {}. Limit: {}",
2289 max_total_routing_fee_msat,
2293 num_ignored_total_fee_limit += 1;
2295 let channel_usage = ChannelUsage {
2296 amount_msat: amount_to_transfer_over_msat,
2297 inflight_htlc_msat: used_liquidity_msat,
2300 let channel_penalty_msat =
2301 scorer.channel_penalty_msat($candidate,
2304 let path_penalty_msat = $next_hops_path_penalty_msat
2305 .saturating_add(channel_penalty_msat);
2307 // Update the way of reaching $candidate.source()
2308 // with the given short_channel_id (from $candidate.target()),
2309 // if this way is cheaper than the already known
2310 // (considering the cost to "reach" this channel from the route destination,
2311 // the cost of using this channel,
2312 // and the cost of routing to the source node of this channel).
2313 // Also, consider that htlc_minimum_msat_difference, because we might end up
2314 // paying it. Consider the following exploit:
2315 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2316 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2317 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2318 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2320 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2321 // but it may require additional tracking - we don't want to double-count
2322 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2323 // can't use something that may decrease on future hops.
2324 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2325 .saturating_add(old_entry.path_penalty_msat);
2326 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2327 .saturating_add(path_penalty_msat);
2329 if !old_entry.was_processed && new_cost < old_cost {
2330 let new_graph_node = RouteGraphNode {
2331 node_id: src_node_id,
2332 score: cmp::max(total_fee_msat, path_htlc_minimum_msat).saturating_add(path_penalty_msat),
2333 total_cltv_delta: hop_total_cltv_delta,
2334 value_contribution_msat,
2335 path_length_to_node,
2337 targets.push(new_graph_node);
2338 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2339 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2340 old_entry.total_fee_msat = total_fee_msat;
2341 old_entry.candidate = $candidate.clone();
2342 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2343 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2344 old_entry.path_penalty_msat = path_penalty_msat;
2345 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2347 old_entry.value_contribution_msat = value_contribution_msat;
2349 hop_contribution_amt_msat = Some(value_contribution_msat);
2350 } else if old_entry.was_processed && new_cost < old_cost {
2351 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2353 // If we're skipping processing a node which was previously
2354 // processed even though we found another path to it with a
2355 // cheaper fee, check that it was because the second path we
2356 // found (which we are processing now) has a lower value
2357 // contribution due to an HTLC minimum limit.
2359 // e.g. take a graph with two paths from node 1 to node 2, one
2360 // through channel A, and one through channel B. Channel A and
2361 // B are both in the to-process heap, with their scores set by
2362 // a higher htlc_minimum than fee.
2363 // Channel A is processed first, and the channels onwards from
2364 // node 1 are added to the to-process heap. Thereafter, we pop
2365 // Channel B off of the heap, note that it has a much more
2366 // restrictive htlc_maximum_msat, and recalculate the fees for
2367 // all of node 1's channels using the new, reduced, amount.
2369 // This would be bogus - we'd be selecting a higher-fee path
2370 // with a lower htlc_maximum_msat instead of the one we'd
2371 // already decided to use.
2372 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2374 value_contribution_msat + path_penalty_msat <
2375 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2382 if should_log_candidate {
2384 "Ignoring {} due to its htlc_minimum_msat limit.",
2385 LoggedCandidateHop(&$candidate));
2387 if let Some(details) = first_hop_details {
2389 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2390 details.next_outbound_htlc_minimum_msat,
2394 num_ignored_htlc_minimum_msat_limit += 1;
2398 hop_contribution_amt_msat
2402 let default_node_features = default_node_features();
2404 // Find ways (channels with destination) to reach a given node and store them
2405 // in the corresponding data structures (routing graph etc).
2406 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2407 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2408 // This data can later be helpful to optimize routing (pay lower fees).
2409 macro_rules! add_entries_to_cheapest_to_target_node {
2410 ( $node: expr, $node_id: expr, $next_hops_value_contribution: expr,
2411 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2412 let fee_to_target_msat;
2413 let next_hops_path_htlc_minimum_msat;
2414 let next_hops_path_penalty_msat;
2415 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
2416 let was_processed = elem.was_processed;
2417 elem.was_processed = true;
2418 fee_to_target_msat = elem.total_fee_msat;
2419 next_hops_path_htlc_minimum_msat = elem.path_htlc_minimum_msat;
2420 next_hops_path_penalty_msat = elem.path_penalty_msat;
2423 // Entries are added to dist in add_entry!() when there is a channel from a node.
2424 // Because there are no channels from payee, it will not have a dist entry at this point.
2425 // If we're processing any other node, it is always be the result of a channel from it.
2426 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2427 fee_to_target_msat = 0;
2428 next_hops_path_htlc_minimum_msat = 0;
2429 next_hops_path_penalty_msat = 0;
2434 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
2435 for details in first_channels {
2436 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2437 details, payer_node_id: &our_node_id,
2439 add_entry!(&candidate, fee_to_target_msat,
2440 $next_hops_value_contribution,
2441 next_hops_path_htlc_minimum_msat, next_hops_path_penalty_msat,
2442 $next_hops_cltv_delta, $next_hops_path_length);
2446 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2449 &default_node_features
2452 if !features.requires_unknown_bits() {
2453 for chan_id in $node.channels.iter() {
2454 let chan = network_channels.get(chan_id).unwrap();
2455 if !chan.features.requires_unknown_bits() {
2456 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2457 if first_hops.is_none() || *source != our_node_id {
2458 if directed_channel.direction().enabled {
2459 let candidate = CandidateRouteHop::PublicHop(PublicHopCandidate {
2460 info: directed_channel,
2461 short_channel_id: *chan_id,
2463 add_entry!(&candidate,
2465 $next_hops_value_contribution,
2466 next_hops_path_htlc_minimum_msat,
2467 next_hops_path_penalty_msat,
2468 $next_hops_cltv_delta, $next_hops_path_length);
2479 let mut payment_paths = Vec::<PaymentPath>::new();
2481 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2482 'paths_collection: loop {
2483 // For every new path, start from scratch, except for used_liquidities, which
2484 // helps to avoid reusing previously selected paths in future iterations.
2487 hit_minimum_limit = false;
2489 // If first hop is a private channel and the only way to reach the payee, this is the only
2490 // place where it could be added.
2491 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2492 for details in first_channels {
2493 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2494 details, payer_node_id: &our_node_id,
2496 let added = add_entry!(&candidate, 0, path_value_msat,
2497 0, 0u64, 0, 0).is_some();
2498 log_trace!(logger, "{} direct route to payee via {}",
2499 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2503 // Add the payee as a target, so that the payee-to-payer
2504 // search algorithm knows what to start with.
2505 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2506 // The payee is not in our network graph, so nothing to add here.
2507 // There is still a chance of reaching them via last_hops though,
2508 // so don't yet fail the payment here.
2509 // If not, targets.pop() will not even let us enter the loop in step 2.
2512 add_entries_to_cheapest_to_target_node!(node, payee, path_value_msat, 0, 0);
2517 // If a caller provided us with last hops, add them to routing targets. Since this happens
2518 // earlier than general path finding, they will be somewhat prioritized, although currently
2519 // it matters only if the fees are exactly the same.
2520 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2521 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2522 let have_intro_node_in_graph =
2523 // Only add the hops in this route to our candidate set if either
2524 // we have a direct channel to the first hop or the first hop is
2525 // in the regular network graph.
2526 first_hop_targets.get(&intro_node_id).is_some() ||
2527 network_nodes.get(&intro_node_id).is_some();
2528 if !have_intro_node_in_graph || our_node_id == intro_node_id { continue }
2529 let candidate = if hint.1.blinded_hops.len() == 1 {
2530 CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, hint_idx })
2531 } else { CandidateRouteHop::Blinded(BlindedPathCandidate { hint, hint_idx }) };
2532 let mut path_contribution_msat = path_value_msat;
2533 if let Some(hop_used_msat) = add_entry!(&candidate,
2534 0, path_contribution_msat, 0, 0_u64, 0, 0)
2536 path_contribution_msat = hop_used_msat;
2538 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2539 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2541 for details in first_channels {
2542 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2543 details, payer_node_id: &our_node_id,
2545 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2549 let path_min = candidate.htlc_minimum_msat().saturating_add(
2550 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2551 add_entry!(&first_hop_candidate, blinded_path_fee,
2552 path_contribution_msat, path_min, 0_u64, candidate.cltv_expiry_delta(),
2553 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2557 for route in payment_params.payee.unblinded_route_hints().iter()
2558 .filter(|route| !route.0.is_empty())
2560 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2561 let first_hop_src_is_reachable =
2562 // Only add the hops in this route to our candidate set if either we are part of
2563 // the first hop, we have a direct channel to the first hop, or the first hop is in
2564 // the regular network graph.
2565 our_node_id == first_hop_src_id ||
2566 first_hop_targets.get(&first_hop_src_id).is_some() ||
2567 network_nodes.get(&first_hop_src_id).is_some();
2568 if first_hop_src_is_reachable {
2569 // We start building the path from reverse, i.e., from payee
2570 // to the first RouteHintHop in the path.
2571 let hop_iter = route.0.iter().rev();
2572 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2573 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2574 let mut hop_used = true;
2575 let mut aggregate_next_hops_fee_msat: u64 = 0;
2576 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2577 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2578 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2579 let mut aggregate_next_hops_path_length: u8 = 0;
2580 let mut aggregate_path_contribution_msat = path_value_msat;
2582 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2583 let target = private_hop_key_cache.get(&prev_hop_id).unwrap();
2585 if let Some(first_channels) = first_hop_targets.get(&target) {
2586 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2587 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2588 hop.short_channel_id);
2593 let candidate = network_channels
2594 .get(&hop.short_channel_id)
2595 .and_then(|channel| channel.as_directed_to(&target))
2596 .map(|(info, _)| CandidateRouteHop::PublicHop(PublicHopCandidate {
2598 short_channel_id: hop.short_channel_id,
2600 .unwrap_or_else(|| CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: hop, target_node_id: target }));
2602 if let Some(hop_used_msat) = add_entry!(&candidate,
2603 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2604 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2605 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2607 aggregate_path_contribution_msat = hop_used_msat;
2609 // If this hop was not used then there is no use checking the preceding
2610 // hops in the RouteHint. We can break by just searching for a direct
2611 // channel between last checked hop and first_hop_targets.
2615 let used_liquidity_msat = used_liquidities
2616 .get(&candidate.id()).copied()
2618 let channel_usage = ChannelUsage {
2619 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2620 inflight_htlc_msat: used_liquidity_msat,
2621 effective_capacity: candidate.effective_capacity(),
2623 let channel_penalty_msat = scorer.channel_penalty_msat(
2624 &candidate, channel_usage, score_params
2626 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2627 .saturating_add(channel_penalty_msat);
2629 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2630 .saturating_add(hop.cltv_expiry_delta as u32);
2632 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2635 // Searching for a direct channel between last checked hop and first_hop_targets
2636 if let Some(first_channels) = first_hop_targets.get_mut(&target) {
2637 sort_first_hop_channels(first_channels, &used_liquidities,
2638 recommended_value_msat, our_node_pubkey);
2639 for details in first_channels {
2640 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2641 details, payer_node_id: &our_node_id,
2643 add_entry!(&first_hop_candidate,
2644 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2645 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2646 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2654 // In the next values of the iterator, the aggregate fees already reflects
2655 // the sum of value sent from payer (final_value_msat) and routing fees
2656 // for the last node in the RouteHint. We need to just add the fees to
2657 // route through the current node so that the preceding node (next iteration)
2659 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2660 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2661 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2663 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2664 // this route hint's source node to forward said min over this channel.
2665 aggregate_next_hops_path_htlc_minimum_msat = {
2666 let curr_htlc_min = cmp::max(
2667 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2669 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2670 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2673 if idx == route.0.len() - 1 {
2674 // The last hop in this iterator is the first hop in
2675 // overall RouteHint.
2676 // If this hop connects to a node with which we have a direct channel,
2677 // ignore the network graph and, if the last hop was added, add our
2678 // direct channel to the candidate set.
2680 // Note that we *must* check if the last hop was added as `add_entry`
2681 // always assumes that the third argument is a node to which we have a
2683 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2684 sort_first_hop_channels(first_channels, &used_liquidities,
2685 recommended_value_msat, our_node_pubkey);
2686 for details in first_channels {
2687 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2688 details, payer_node_id: &our_node_id,
2690 add_entry!(&first_hop_candidate,
2691 aggregate_next_hops_fee_msat,
2692 aggregate_path_contribution_msat,
2693 aggregate_next_hops_path_htlc_minimum_msat,
2694 aggregate_next_hops_path_penalty_msat,
2695 aggregate_next_hops_cltv_delta,
2696 aggregate_next_hops_path_length);
2704 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2706 // At this point, targets are filled with the data from first and
2707 // last hops communicated by the caller, and the payment receiver.
2708 let mut found_new_path = false;
2711 // If this loop terminates due the exhaustion of targets, two situations are possible:
2712 // - not enough outgoing liquidity:
2713 // 0 < already_collected_value_msat < final_value_msat
2714 // - enough outgoing liquidity:
2715 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2716 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2717 // paths_collection will be stopped because found_new_path==false.
2718 // This is not necessarily a routing failure.
2719 'path_construction: while let Some(RouteGraphNode { node_id, total_cltv_delta, mut value_contribution_msat, path_length_to_node, .. }) = targets.pop() {
2721 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2722 // traversing the graph and arrange the path out of what we found.
2723 if node_id == our_node_id {
2724 let mut new_entry = dist.remove(&our_node_id).unwrap();
2725 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2728 let mut features_set = false;
2729 let target = ordered_hops.last().unwrap().0.candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2730 if let Some(first_channels) = first_hop_targets.get(&target) {
2731 for details in first_channels {
2732 if let CandidateRouteHop::FirstHop(FirstHopCandidate { details: last_hop_details, .. })
2733 = ordered_hops.last().unwrap().0.candidate
2735 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2736 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2737 features_set = true;
2744 if let Some(node) = network_nodes.get(&target) {
2745 if let Some(node_info) = node.announcement_info.as_ref() {
2746 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2748 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2751 // We can fill in features for everything except hops which were
2752 // provided via the invoice we're paying. We could guess based on the
2753 // recipient's features but for now we simply avoid guessing at all.
2757 // Means we successfully traversed from the payer to the payee, now
2758 // save this path for the payment route. Also, update the liquidity
2759 // remaining on the used hops, so that we take them into account
2760 // while looking for more paths.
2761 if target == maybe_dummy_payee_node_id {
2765 new_entry = match dist.remove(&target) {
2766 Some(payment_hop) => payment_hop,
2767 // We can't arrive at None because, if we ever add an entry to targets,
2768 // we also fill in the entry in dist (see add_entry!).
2769 None => unreachable!(),
2771 // We "propagate" the fees one hop backward (topologically) here,
2772 // so that fees paid for a HTLC forwarding on the current channel are
2773 // associated with the previous channel (where they will be subtracted).
2774 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2775 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2777 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2778 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2780 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2781 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2783 let mut payment_path = PaymentPath {hops: ordered_hops};
2785 // We could have possibly constructed a slightly inconsistent path: since we reduce
2786 // value being transferred along the way, we could have violated htlc_minimum_msat
2787 // on some channels we already passed (assuming dest->source direction). Here, we
2788 // recompute the fees again, so that if that's the case, we match the currently
2789 // underpaid htlc_minimum_msat with fees.
2790 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2791 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2792 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2794 // Since a path allows to transfer as much value as
2795 // the smallest channel it has ("bottleneck"), we should recompute
2796 // the fees so sender HTLC don't overpay fees when traversing
2797 // larger channels than the bottleneck. This may happen because
2798 // when we were selecting those channels we were not aware how much value
2799 // this path will transfer, and the relative fee for them
2800 // might have been computed considering a larger value.
2801 // Remember that we used these channels so that we don't rely
2802 // on the same liquidity in future paths.
2803 let mut prevented_redundant_path_selection = false;
2804 for (hop, _) in payment_path.hops.iter() {
2805 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2806 let used_liquidity_msat = used_liquidities
2807 .entry(hop.candidate.id())
2808 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2809 .or_insert(spent_on_hop_msat);
2810 let hop_capacity = hop.candidate.effective_capacity();
2811 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2812 if *used_liquidity_msat == hop_max_msat {
2813 // If this path used all of this channel's available liquidity, we know
2814 // this path will not be selected again in the next loop iteration.
2815 prevented_redundant_path_selection = true;
2817 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2819 if !prevented_redundant_path_selection {
2820 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2821 // we'll probably end up picking the same path again on the next iteration.
2822 // Decrease the available liquidity of a hop in the middle of the path.
2823 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2824 let exhausted = u64::max_value();
2826 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2827 LoggedCandidateHop(victim_candidate));
2828 if let Some(scid) = victim_candidate.short_channel_id() {
2829 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2830 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2834 // Track the total amount all our collected paths allow to send so that we know
2835 // when to stop looking for more paths
2836 already_collected_value_msat += value_contribution_msat;
2838 payment_paths.push(payment_path);
2839 found_new_path = true;
2840 break 'path_construction;
2843 // If we found a path back to the payee, we shouldn't try to process it again. This is
2844 // the equivalent of the `elem.was_processed` check in
2845 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2846 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2848 // Otherwise, since the current target node is not us,
2849 // keep "unrolling" the payment graph from payee to payer by
2850 // finding a way to reach the current target from the payer side.
2851 match network_nodes.get(&node_id) {
2854 add_entries_to_cheapest_to_target_node!(node, node_id,
2855 value_contribution_msat,
2856 total_cltv_delta, path_length_to_node);
2862 if !found_new_path && channel_saturation_pow_half != 0 {
2863 channel_saturation_pow_half = 0;
2864 continue 'paths_collection;
2866 // If we don't support MPP, no use trying to gather more value ever.
2867 break 'paths_collection;
2871 // Stop either when the recommended value is reached or if no new path was found in this
2873 // In the latter case, making another path finding attempt won't help,
2874 // because we deterministically terminated the search due to low liquidity.
2875 if !found_new_path && channel_saturation_pow_half != 0 {
2876 channel_saturation_pow_half = 0;
2877 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2878 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
2879 path_value_msat = recommended_value_msat;
2880 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2881 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2882 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2883 break 'paths_collection;
2884 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2885 // Further, if this was our first walk of the graph, and we weren't limited by an
2886 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2887 // limited by an htlc_minimum_msat value, find another path with a higher value,
2888 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2889 // still keeping a lower total fee than this path.
2890 if !hit_minimum_limit {
2891 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2892 break 'paths_collection;
2894 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.");
2895 path_value_msat = recommended_value_msat;
2899 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2900 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
2901 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
2902 num_ignored_total_fee_limit;
2903 if num_ignored_total > 0 {
2905 "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.",
2906 num_ignored_value_contribution, num_ignored_path_length_limit,
2907 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
2908 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
2909 num_ignored_total_fee_limit, num_ignored_total);
2913 if payment_paths.len() == 0 {
2914 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2917 if already_collected_value_msat < final_value_msat {
2918 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2922 let mut selected_route = payment_paths;
2924 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2925 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2927 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2928 // the value they contribute towards the payment amount.
2929 // We sort in descending order as we will remove from the front in `retain`, next.
2930 selected_route.sort_unstable_by(|a, b|
2931 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2932 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2935 // We should make sure that at least 1 path left.
2936 let mut paths_left = selected_route.len();
2937 selected_route.retain(|path| {
2938 if paths_left == 1 {
2941 let path_value_msat = path.get_value_msat();
2942 if path_value_msat <= overpaid_value_msat {
2943 overpaid_value_msat -= path_value_msat;
2949 debug_assert!(selected_route.len() > 0);
2951 if overpaid_value_msat != 0 {
2953 // Now, subtract the remaining overpaid value from the most-expensive path.
2954 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2955 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2956 selected_route.sort_unstable_by(|a, b| {
2957 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2958 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2959 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2961 let expensive_payment_path = selected_route.first_mut().unwrap();
2963 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2964 // can't go negative.
2965 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2966 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2970 // Sort by the path itself and combine redundant paths.
2971 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2972 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2974 selected_route.sort_unstable_by_key(|path| {
2975 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2976 debug_assert!(path.hops.len() <= key.len());
2977 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
2982 for idx in 0..(selected_route.len() - 1) {
2983 if idx + 1 >= selected_route.len() { break; }
2984 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
2985 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
2986 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2987 selected_route[idx].update_value_and_recompute_fees(new_value);
2988 selected_route.remove(idx + 1);
2992 let mut paths = Vec::new();
2993 for payment_path in selected_route {
2994 let mut hops = Vec::with_capacity(payment_path.hops.len());
2995 for (hop, node_features) in payment_path.hops.iter()
2996 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2998 let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
2999 let maybe_announced_channel = if let CandidateRouteHop::PublicHop(_) = hop.candidate {
3000 // If we sourced the hop from the graph we're sure the target node is announced.
3002 } else if let CandidateRouteHop::FirstHop(first_hop) = &hop.candidate {
3003 // If this is a first hop we also know if it's announced.
3004 first_hop.details.is_public
3006 // If we sourced it any other way, we double-check the network graph to see if
3007 // there are announced channels between the endpoints. If so, the hop might be
3008 // referring to any of the announced channels, as its `short_channel_id` might be
3009 // an alias, in which case we don't take any chances here.
3010 network_graph.node(&target).map_or(false, |hop_node|
3011 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
3012 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
3016 hops.push(RouteHop {
3017 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
3018 node_features: node_features.clone(),
3019 short_channel_id: hop.candidate.short_channel_id().unwrap(),
3020 channel_features: hop.candidate.features(),
3021 fee_msat: hop.fee_msat,
3022 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
3023 maybe_announced_channel,
3026 let mut final_cltv_delta = final_cltv_expiry_delta;
3027 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
3028 if let Some(blinded_path) = h.candidate.blinded_path() {
3029 final_cltv_delta = h.candidate.cltv_expiry_delta();
3031 hops: blinded_path.blinded_hops.clone(),
3032 blinding_point: blinded_path.blinding_point,
3033 excess_final_cltv_expiry_delta: 0,
3034 final_value_msat: h.fee_msat,
3038 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
3039 // applicable for the previous hop.
3040 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
3041 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
3044 paths.push(Path { hops, blinded_tail });
3046 // Make sure we would never create a route with more paths than we allow.
3047 debug_assert!(paths.len() <= payment_params.max_path_count.into());
3049 if let Some(node_features) = payment_params.payee.node_features() {
3050 for path in paths.iter_mut() {
3051 path.hops.last_mut().unwrap().node_features = node_features.clone();
3055 let route = Route { paths, route_params: Some(route_params.clone()) };
3057 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
3058 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
3059 if route.get_total_fees() > max_total_routing_fee_msat {
3060 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
3061 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
3065 log_info!(logger, "Got route: {}", log_route!(route));
3069 // When an adversarial intermediary node observes a payment, it may be able to infer its
3070 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
3071 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
3072 // payment path by adding a randomized 'shadow route' offset to the final hop.
3073 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
3074 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
3076 let network_channels = network_graph.channels();
3077 let network_nodes = network_graph.nodes();
3079 for path in route.paths.iter_mut() {
3080 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
3082 // Remember the last three nodes of the random walk and avoid looping back on them.
3083 // Init with the last three nodes from the actual path, if possible.
3084 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
3085 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
3086 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
3088 // Choose the last publicly known node as the starting point for the random walk.
3089 let mut cur_hop: Option<NodeId> = None;
3090 let mut path_nonce = [0u8; 12];
3091 if let Some(starting_hop) = path.hops.iter().rev()
3092 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
3093 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
3094 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
3097 // Init PRNG with the path-dependant nonce, which is static for private paths.
3098 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
3099 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
3101 // Pick a random path length in [1 .. 3]
3102 prng.process_in_place(&mut random_path_bytes);
3103 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
3105 for random_hop in 0..random_walk_length {
3106 // If we don't find a suitable offset in the public network graph, we default to
3107 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3108 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
3110 if let Some(cur_node_id) = cur_hop {
3111 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
3112 // Randomly choose the next unvisited hop.
3113 prng.process_in_place(&mut random_path_bytes);
3114 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
3115 .checked_rem(cur_node.channels.len())
3116 .and_then(|index| cur_node.channels.get(index))
3117 .and_then(|id| network_channels.get(id)) {
3118 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
3119 if !nodes_to_avoid.iter().any(|x| x == next_id) {
3120 nodes_to_avoid[random_hop] = *next_id;
3121 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
3122 cur_hop = Some(*next_id);
3129 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
3130 .checked_add(random_hop_offset)
3131 .unwrap_or(shadow_ctlv_expiry_delta_offset);
3134 // Limit the total offset to reduce the worst-case locked liquidity timevalue
3135 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
3136 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
3138 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
3139 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3140 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
3141 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
3142 max_path_offset = cmp::max(
3143 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
3144 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
3145 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
3147 // Add 'shadow' CLTV offset to the final hop
3148 if let Some(tail) = path.blinded_tail.as_mut() {
3149 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
3150 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
3152 if let Some(last_hop) = path.hops.last_mut() {
3153 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
3154 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
3159 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
3160 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
3162 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
3163 pub fn build_route_from_hops<L: Deref, GL: Deref>(
3164 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3165 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
3166 ) -> Result<Route, LightningError>
3167 where L::Target: Logger, GL::Target: Logger {
3168 let graph_lock = network_graph.read_only();
3169 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
3170 &graph_lock, logger, random_seed_bytes)?;
3171 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
3175 fn build_route_from_hops_internal<L: Deref>(
3176 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3177 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
3178 ) -> Result<Route, LightningError> where L::Target: Logger {
3181 our_node_id: NodeId,
3182 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
3185 impl ScoreLookUp for HopScorer {
3186 type ScoreParams = ();
3187 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
3188 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
3190 let mut cur_id = self.our_node_id;
3191 for i in 0..self.hop_ids.len() {
3192 if let Some(next_id) = self.hop_ids[i] {
3193 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
3205 impl<'a> Writeable for HopScorer {
3207 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
3212 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
3213 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
3216 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
3217 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
3218 for i in 0..hops.len() {
3219 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
3222 let scorer = HopScorer { our_node_id, hop_ids };
3224 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
3229 use crate::blinded_path::{BlindedHop, BlindedPath};
3230 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
3231 use crate::routing::utxo::UtxoResult;
3232 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
3233 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
3234 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop, PublicHopCandidate};
3235 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
3236 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
3237 use crate::chain::transaction::OutPoint;
3238 use crate::sign::EntropySource;
3239 use crate::ln::ChannelId;
3240 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
3241 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
3242 use crate::ln::channelmanager;
3243 use crate::offers::invoice::BlindedPayInfo;
3244 use crate::util::config::UserConfig;
3245 use crate::util::test_utils as ln_test_utils;
3246 use crate::crypto::chacha20::ChaCha20;
3247 use crate::util::ser::{Readable, Writeable};
3249 use crate::util::ser::Writer;
3251 use bitcoin::hashes::Hash;
3252 use bitcoin::network::constants::Network;
3253 use bitcoin::blockdata::constants::ChainHash;
3254 use bitcoin::blockdata::script::Builder;
3255 use bitcoin::blockdata::opcodes;
3256 use bitcoin::blockdata::transaction::TxOut;
3257 use bitcoin::hashes::hex::FromHex;
3258 use bitcoin::secp256k1::{PublicKey,SecretKey};
3259 use bitcoin::secp256k1::Secp256k1;
3261 use crate::io::Cursor;
3262 use crate::prelude::*;
3263 use crate::sync::Arc;
3265 use core::convert::TryInto;
3267 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3268 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
3269 channelmanager::ChannelDetails {
3270 channel_id: ChannelId::new_zero(),
3271 counterparty: channelmanager::ChannelCounterparty {
3274 unspendable_punishment_reserve: 0,
3275 forwarding_info: None,
3276 outbound_htlc_minimum_msat: None,
3277 outbound_htlc_maximum_msat: None,
3279 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3282 outbound_scid_alias: None,
3283 inbound_scid_alias: None,
3284 channel_value_satoshis: 0,
3287 outbound_capacity_msat,
3288 next_outbound_htlc_limit_msat: outbound_capacity_msat,
3289 next_outbound_htlc_minimum_msat: 0,
3290 inbound_capacity_msat: 42,
3291 unspendable_punishment_reserve: None,
3292 confirmations_required: None,
3293 confirmations: None,
3294 force_close_spend_delay: None,
3295 is_outbound: true, is_channel_ready: true,
3296 is_usable: true, is_public: true,
3297 inbound_htlc_minimum_msat: None,
3298 inbound_htlc_maximum_msat: None,
3300 feerate_sat_per_1000_weight: None,
3301 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
3306 fn simple_route_test() {
3307 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3308 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3309 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3310 let scorer = ln_test_utils::TestScorer::new();
3311 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3312 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3314 // Simple route to 2 via 1
3316 let route_params = RouteParameters::from_payment_params_and_value(
3317 payment_params.clone(), 0);
3318 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3319 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3320 &Default::default(), &random_seed_bytes) {
3321 assert_eq!(err, "Cannot send a payment of 0 msat");
3322 } else { panic!(); }
3324 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3325 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3326 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3327 assert_eq!(route.paths[0].hops.len(), 2);
3329 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3330 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3331 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3332 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3333 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3334 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3336 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3337 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3338 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3339 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3340 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3341 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3345 fn invalid_first_hop_test() {
3346 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3347 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3348 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3349 let scorer = ln_test_utils::TestScorer::new();
3350 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3351 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3353 // Simple route to 2 via 1
3355 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3357 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3358 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3359 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3360 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3361 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3362 } else { panic!(); }
3364 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3365 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3366 assert_eq!(route.paths[0].hops.len(), 2);
3370 fn htlc_minimum_test() {
3371 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3372 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3373 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3374 let scorer = ln_test_utils::TestScorer::new();
3375 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3376 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3378 // Simple route to 2 via 1
3380 // Disable other paths
3381 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3382 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3383 short_channel_id: 12,
3385 flags: 2, // to disable
3386 cltv_expiry_delta: 0,
3387 htlc_minimum_msat: 0,
3388 htlc_maximum_msat: MAX_VALUE_MSAT,
3390 fee_proportional_millionths: 0,
3391 excess_data: Vec::new()
3393 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3394 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3395 short_channel_id: 3,
3397 flags: 2, // to disable
3398 cltv_expiry_delta: 0,
3399 htlc_minimum_msat: 0,
3400 htlc_maximum_msat: MAX_VALUE_MSAT,
3402 fee_proportional_millionths: 0,
3403 excess_data: Vec::new()
3405 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3406 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3407 short_channel_id: 13,
3409 flags: 2, // to disable
3410 cltv_expiry_delta: 0,
3411 htlc_minimum_msat: 0,
3412 htlc_maximum_msat: MAX_VALUE_MSAT,
3414 fee_proportional_millionths: 0,
3415 excess_data: Vec::new()
3417 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3418 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3419 short_channel_id: 6,
3421 flags: 2, // to disable
3422 cltv_expiry_delta: 0,
3423 htlc_minimum_msat: 0,
3424 htlc_maximum_msat: MAX_VALUE_MSAT,
3426 fee_proportional_millionths: 0,
3427 excess_data: Vec::new()
3429 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3430 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3431 short_channel_id: 7,
3433 flags: 2, // to disable
3434 cltv_expiry_delta: 0,
3435 htlc_minimum_msat: 0,
3436 htlc_maximum_msat: MAX_VALUE_MSAT,
3438 fee_proportional_millionths: 0,
3439 excess_data: Vec::new()
3442 // Check against amount_to_transfer_over_msat.
3443 // Set minimal HTLC of 200_000_000 msat.
3444 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3445 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3446 short_channel_id: 2,
3449 cltv_expiry_delta: 0,
3450 htlc_minimum_msat: 200_000_000,
3451 htlc_maximum_msat: MAX_VALUE_MSAT,
3453 fee_proportional_millionths: 0,
3454 excess_data: Vec::new()
3457 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3459 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3460 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3461 short_channel_id: 4,
3464 cltv_expiry_delta: 0,
3465 htlc_minimum_msat: 0,
3466 htlc_maximum_msat: 199_999_999,
3468 fee_proportional_millionths: 0,
3469 excess_data: Vec::new()
3472 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3473 let route_params = RouteParameters::from_payment_params_and_value(
3474 payment_params, 199_999_999);
3475 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3476 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3477 &Default::default(), &random_seed_bytes) {
3478 assert_eq!(err, "Failed to find a path to the given destination");
3479 } else { panic!(); }
3481 // Lift the restriction on the first hop.
3482 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3483 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3484 short_channel_id: 2,
3487 cltv_expiry_delta: 0,
3488 htlc_minimum_msat: 0,
3489 htlc_maximum_msat: MAX_VALUE_MSAT,
3491 fee_proportional_millionths: 0,
3492 excess_data: Vec::new()
3495 // A payment above the minimum should pass
3496 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3497 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3498 assert_eq!(route.paths[0].hops.len(), 2);
3502 fn htlc_minimum_overpay_test() {
3503 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3504 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3505 let config = UserConfig::default();
3506 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3507 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3509 let scorer = ln_test_utils::TestScorer::new();
3510 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3511 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3513 // A route to node#2 via two paths.
3514 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3515 // Thus, they can't send 60 without overpaying.
3516 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3517 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3518 short_channel_id: 2,
3521 cltv_expiry_delta: 0,
3522 htlc_minimum_msat: 35_000,
3523 htlc_maximum_msat: 40_000,
3525 fee_proportional_millionths: 0,
3526 excess_data: Vec::new()
3528 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3529 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3530 short_channel_id: 12,
3533 cltv_expiry_delta: 0,
3534 htlc_minimum_msat: 35_000,
3535 htlc_maximum_msat: 40_000,
3537 fee_proportional_millionths: 0,
3538 excess_data: Vec::new()
3542 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3543 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3544 short_channel_id: 13,
3547 cltv_expiry_delta: 0,
3548 htlc_minimum_msat: 0,
3549 htlc_maximum_msat: MAX_VALUE_MSAT,
3551 fee_proportional_millionths: 0,
3552 excess_data: Vec::new()
3554 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3555 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3556 short_channel_id: 4,
3559 cltv_expiry_delta: 0,
3560 htlc_minimum_msat: 0,
3561 htlc_maximum_msat: MAX_VALUE_MSAT,
3563 fee_proportional_millionths: 0,
3564 excess_data: Vec::new()
3567 // Disable other paths
3568 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3569 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3570 short_channel_id: 1,
3572 flags: 2, // to disable
3573 cltv_expiry_delta: 0,
3574 htlc_minimum_msat: 0,
3575 htlc_maximum_msat: MAX_VALUE_MSAT,
3577 fee_proportional_millionths: 0,
3578 excess_data: Vec::new()
3581 let mut route_params = RouteParameters::from_payment_params_and_value(
3582 payment_params.clone(), 60_000);
3583 route_params.max_total_routing_fee_msat = Some(15_000);
3584 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3585 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3586 // Overpay fees to hit htlc_minimum_msat.
3587 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3588 // TODO: this could be better balanced to overpay 10k and not 15k.
3589 assert_eq!(overpaid_fees, 15_000);
3591 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3592 // while taking even more fee to match htlc_minimum_msat.
3593 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3594 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3595 short_channel_id: 12,
3598 cltv_expiry_delta: 0,
3599 htlc_minimum_msat: 65_000,
3600 htlc_maximum_msat: 80_000,
3602 fee_proportional_millionths: 0,
3603 excess_data: Vec::new()
3605 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3606 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3607 short_channel_id: 2,
3610 cltv_expiry_delta: 0,
3611 htlc_minimum_msat: 0,
3612 htlc_maximum_msat: MAX_VALUE_MSAT,
3614 fee_proportional_millionths: 0,
3615 excess_data: Vec::new()
3617 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3618 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3619 short_channel_id: 4,
3622 cltv_expiry_delta: 0,
3623 htlc_minimum_msat: 0,
3624 htlc_maximum_msat: MAX_VALUE_MSAT,
3626 fee_proportional_millionths: 100_000,
3627 excess_data: Vec::new()
3630 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3631 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3632 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3633 assert_eq!(route.paths.len(), 1);
3634 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3635 let fees = route.paths[0].hops[0].fee_msat;
3636 assert_eq!(fees, 5_000);
3638 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3639 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3640 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3641 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3642 // the other channel.
3643 assert_eq!(route.paths.len(), 1);
3644 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3645 let fees = route.paths[0].hops[0].fee_msat;
3646 assert_eq!(fees, 5_000);
3650 fn htlc_minimum_recipient_overpay_test() {
3651 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3652 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3653 let config = UserConfig::default();
3654 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3655 let scorer = ln_test_utils::TestScorer::new();
3656 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3657 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3659 // Route to node2 over a single path which requires overpaying the recipient themselves.
3661 // First disable all paths except the us -> node1 -> node2 path
3662 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3663 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3664 short_channel_id: 13,
3667 cltv_expiry_delta: 0,
3668 htlc_minimum_msat: 0,
3669 htlc_maximum_msat: 0,
3671 fee_proportional_millionths: 0,
3672 excess_data: Vec::new()
3675 // Set channel 4 to free but with a high htlc_minimum_msat
3676 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3677 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3678 short_channel_id: 4,
3681 cltv_expiry_delta: 0,
3682 htlc_minimum_msat: 15_000,
3683 htlc_maximum_msat: MAX_VALUE_MSAT,
3685 fee_proportional_millionths: 0,
3686 excess_data: Vec::new()
3689 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3690 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3691 // what we try to find a route for, so this test only just happens to work out to exactly
3693 let mut route_params = RouteParameters::from_payment_params_and_value(
3694 payment_params.clone(), 5_000);
3695 route_params.max_total_routing_fee_msat = Some(9_999);
3696 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3697 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3698 &Default::default(), &random_seed_bytes) {
3699 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3700 } else { panic!(); }
3702 let mut route_params = RouteParameters::from_payment_params_and_value(
3703 payment_params.clone(), 5_000);
3704 route_params.max_total_routing_fee_msat = Some(10_000);
3705 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3706 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3707 assert_eq!(route.get_total_fees(), 10_000);
3711 fn disable_channels_test() {
3712 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3713 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3714 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3715 let scorer = ln_test_utils::TestScorer::new();
3716 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3717 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3719 // // Disable channels 4 and 12 by flags=2
3720 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3721 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3722 short_channel_id: 4,
3724 flags: 2, // to disable
3725 cltv_expiry_delta: 0,
3726 htlc_minimum_msat: 0,
3727 htlc_maximum_msat: MAX_VALUE_MSAT,
3729 fee_proportional_millionths: 0,
3730 excess_data: Vec::new()
3732 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3733 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3734 short_channel_id: 12,
3736 flags: 2, // to disable
3737 cltv_expiry_delta: 0,
3738 htlc_minimum_msat: 0,
3739 htlc_maximum_msat: MAX_VALUE_MSAT,
3741 fee_proportional_millionths: 0,
3742 excess_data: Vec::new()
3745 // If all the channels require some features we don't understand, route should fail
3746 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3747 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3748 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3749 &Default::default(), &random_seed_bytes) {
3750 assert_eq!(err, "Failed to find a path to the given destination");
3751 } else { panic!(); }
3753 // If we specify a channel to node7, that overrides our local channel view and that gets used
3754 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3755 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3756 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3757 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3758 &Default::default(), &random_seed_bytes).unwrap();
3759 assert_eq!(route.paths[0].hops.len(), 2);
3761 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3762 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3763 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3764 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3765 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3766 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3768 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3769 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3770 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3771 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3772 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3773 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3777 fn disable_node_test() {
3778 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3779 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3780 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3781 let scorer = ln_test_utils::TestScorer::new();
3782 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3783 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3785 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3786 let mut unknown_features = NodeFeatures::empty();
3787 unknown_features.set_unknown_feature_required();
3788 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3789 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3790 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3792 // If all nodes require some features we don't understand, route should fail
3793 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3794 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3795 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3796 &Default::default(), &random_seed_bytes) {
3797 assert_eq!(err, "Failed to find a path to the given destination");
3798 } else { panic!(); }
3800 // If we specify a channel to node7, that overrides our local channel view and that gets used
3801 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3802 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3803 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3804 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3805 &Default::default(), &random_seed_bytes).unwrap();
3806 assert_eq!(route.paths[0].hops.len(), 2);
3808 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3809 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3810 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3811 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3812 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3813 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3815 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3816 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3817 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3818 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3819 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3820 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3822 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3823 // naively) assume that the user checked the feature bits on the invoice, which override
3824 // the node_announcement.
3828 fn our_chans_test() {
3829 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3830 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3831 let scorer = ln_test_utils::TestScorer::new();
3832 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3833 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3835 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3836 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3837 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3838 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3839 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3840 assert_eq!(route.paths[0].hops.len(), 3);
3842 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3843 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3844 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3845 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3846 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3847 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3849 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3850 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3851 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3852 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3853 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3854 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3856 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3857 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3858 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3859 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3860 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3861 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3863 // If we specify a channel to node7, that overrides our local channel view and that gets used
3864 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3865 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3866 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3867 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3868 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3869 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3870 &Default::default(), &random_seed_bytes).unwrap();
3871 assert_eq!(route.paths[0].hops.len(), 2);
3873 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3874 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3875 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3876 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3877 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3878 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3880 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3881 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3882 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3883 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3884 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3885 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3888 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3889 let zero_fees = RoutingFees {
3891 proportional_millionths: 0,
3893 vec![RouteHint(vec![RouteHintHop {
3894 src_node_id: nodes[3],
3895 short_channel_id: 8,
3897 cltv_expiry_delta: (8 << 4) | 1,
3898 htlc_minimum_msat: None,
3899 htlc_maximum_msat: None,
3901 ]), RouteHint(vec![RouteHintHop {
3902 src_node_id: nodes[4],
3903 short_channel_id: 9,
3906 proportional_millionths: 0,
3908 cltv_expiry_delta: (9 << 4) | 1,
3909 htlc_minimum_msat: None,
3910 htlc_maximum_msat: None,
3911 }]), RouteHint(vec![RouteHintHop {
3912 src_node_id: nodes[5],
3913 short_channel_id: 10,
3915 cltv_expiry_delta: (10 << 4) | 1,
3916 htlc_minimum_msat: None,
3917 htlc_maximum_msat: None,
3921 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3922 let zero_fees = RoutingFees {
3924 proportional_millionths: 0,
3926 vec![RouteHint(vec![RouteHintHop {
3927 src_node_id: nodes[2],
3928 short_channel_id: 5,
3931 proportional_millionths: 0,
3933 cltv_expiry_delta: (5 << 4) | 1,
3934 htlc_minimum_msat: None,
3935 htlc_maximum_msat: None,
3937 src_node_id: nodes[3],
3938 short_channel_id: 8,
3940 cltv_expiry_delta: (8 << 4) | 1,
3941 htlc_minimum_msat: None,
3942 htlc_maximum_msat: None,
3944 ]), RouteHint(vec![RouteHintHop {
3945 src_node_id: nodes[4],
3946 short_channel_id: 9,
3949 proportional_millionths: 0,
3951 cltv_expiry_delta: (9 << 4) | 1,
3952 htlc_minimum_msat: None,
3953 htlc_maximum_msat: None,
3954 }]), RouteHint(vec![RouteHintHop {
3955 src_node_id: nodes[5],
3956 short_channel_id: 10,
3958 cltv_expiry_delta: (10 << 4) | 1,
3959 htlc_minimum_msat: None,
3960 htlc_maximum_msat: None,
3965 fn partial_route_hint_test() {
3966 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3967 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3968 let scorer = ln_test_utils::TestScorer::new();
3969 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3970 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3972 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3973 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3974 // RouteHint may be partially used by the algo to build the best path.
3976 // First check that last hop can't have its source as the payee.
3977 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3978 src_node_id: nodes[6],
3979 short_channel_id: 8,
3982 proportional_millionths: 0,
3984 cltv_expiry_delta: (8 << 4) | 1,
3985 htlc_minimum_msat: None,
3986 htlc_maximum_msat: None,
3989 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3990 invalid_last_hops.push(invalid_last_hop);
3992 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3993 .with_route_hints(invalid_last_hops).unwrap();
3994 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3995 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3996 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3997 &Default::default(), &random_seed_bytes) {
3998 assert_eq!(err, "Route hint cannot have the payee as the source.");
3999 } else { panic!(); }
4002 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4003 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
4004 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4005 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4006 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4007 assert_eq!(route.paths[0].hops.len(), 5);
4009 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4010 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4011 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4012 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4013 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4014 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4016 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4017 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4018 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4019 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4020 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4021 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4023 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4024 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4025 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4026 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4027 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4028 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4030 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4031 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4032 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4033 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4034 // If we have a peer in the node map, we'll use their features here since we don't have
4035 // a way of figuring out their features from the invoice:
4036 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4037 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4039 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4040 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4041 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4042 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4043 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4044 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4047 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4048 let zero_fees = RoutingFees {
4050 proportional_millionths: 0,
4052 vec![RouteHint(vec![RouteHintHop {
4053 src_node_id: nodes[3],
4054 short_channel_id: 8,
4056 cltv_expiry_delta: (8 << 4) | 1,
4057 htlc_minimum_msat: None,
4058 htlc_maximum_msat: None,
4059 }]), RouteHint(vec![
4061 ]), RouteHint(vec![RouteHintHop {
4062 src_node_id: nodes[5],
4063 short_channel_id: 10,
4065 cltv_expiry_delta: (10 << 4) | 1,
4066 htlc_minimum_msat: None,
4067 htlc_maximum_msat: None,
4072 fn ignores_empty_last_hops_test() {
4073 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4074 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4075 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
4076 let scorer = ln_test_utils::TestScorer::new();
4077 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4078 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4080 // Test handling of an empty RouteHint passed in Invoice.
4081 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4082 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4083 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4084 assert_eq!(route.paths[0].hops.len(), 5);
4086 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4087 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4088 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4089 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4090 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4091 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4093 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4094 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4095 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4096 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4097 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4098 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4100 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4101 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4102 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4103 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4104 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4105 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4107 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4108 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4109 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4110 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4111 // If we have a peer in the node map, we'll use their features here since we don't have
4112 // a way of figuring out their features from the invoice:
4113 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4114 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4116 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4117 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4118 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4119 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4120 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4121 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4124 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
4126 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
4127 let zero_fees = RoutingFees {
4129 proportional_millionths: 0,
4131 vec![RouteHint(vec![RouteHintHop {
4132 src_node_id: hint_hops[0],
4133 short_channel_id: 0xff00,
4136 proportional_millionths: 0,
4138 cltv_expiry_delta: (5 << 4) | 1,
4139 htlc_minimum_msat: None,
4140 htlc_maximum_msat: None,
4142 src_node_id: hint_hops[1],
4143 short_channel_id: 0xff01,
4145 cltv_expiry_delta: (8 << 4) | 1,
4146 htlc_minimum_msat: None,
4147 htlc_maximum_msat: None,
4152 fn multi_hint_last_hops_test() {
4153 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4154 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4155 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
4156 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4157 let scorer = ln_test_utils::TestScorer::new();
4158 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4159 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4160 // Test through channels 2, 3, 0xff00, 0xff01.
4161 // Test shows that multiple hop hints are considered.
4163 // Disabling channels 6 & 7 by flags=2
4164 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4165 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4166 short_channel_id: 6,
4168 flags: 2, // to disable
4169 cltv_expiry_delta: 0,
4170 htlc_minimum_msat: 0,
4171 htlc_maximum_msat: MAX_VALUE_MSAT,
4173 fee_proportional_millionths: 0,
4174 excess_data: Vec::new()
4176 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4177 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4178 short_channel_id: 7,
4180 flags: 2, // to disable
4181 cltv_expiry_delta: 0,
4182 htlc_minimum_msat: 0,
4183 htlc_maximum_msat: MAX_VALUE_MSAT,
4185 fee_proportional_millionths: 0,
4186 excess_data: Vec::new()
4189 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4190 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4191 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4192 assert_eq!(route.paths[0].hops.len(), 4);
4194 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4195 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4196 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4197 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4198 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4199 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4201 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4202 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4203 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4204 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4205 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4206 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4208 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4209 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4210 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4211 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4212 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4213 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4215 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4216 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4217 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4218 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4219 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4220 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4224 fn private_multi_hint_last_hops_test() {
4225 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4226 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4228 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4229 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4231 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4232 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4233 let scorer = ln_test_utils::TestScorer::new();
4234 // Test through channels 2, 3, 0xff00, 0xff01.
4235 // Test shows that multiple hop hints are considered.
4237 // Disabling channels 6 & 7 by flags=2
4238 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4239 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4240 short_channel_id: 6,
4242 flags: 2, // to disable
4243 cltv_expiry_delta: 0,
4244 htlc_minimum_msat: 0,
4245 htlc_maximum_msat: MAX_VALUE_MSAT,
4247 fee_proportional_millionths: 0,
4248 excess_data: Vec::new()
4250 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4251 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4252 short_channel_id: 7,
4254 flags: 2, // to disable
4255 cltv_expiry_delta: 0,
4256 htlc_minimum_msat: 0,
4257 htlc_maximum_msat: MAX_VALUE_MSAT,
4259 fee_proportional_millionths: 0,
4260 excess_data: Vec::new()
4263 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4264 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4265 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4266 assert_eq!(route.paths[0].hops.len(), 4);
4268 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4269 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4270 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4271 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4272 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4273 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4275 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4276 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4277 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4278 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4279 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4280 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4282 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4283 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4284 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4285 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4286 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4287 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4289 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4290 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4291 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4292 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4293 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4294 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4297 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4298 let zero_fees = RoutingFees {
4300 proportional_millionths: 0,
4302 vec![RouteHint(vec![RouteHintHop {
4303 src_node_id: nodes[4],
4304 short_channel_id: 11,
4306 cltv_expiry_delta: (11 << 4) | 1,
4307 htlc_minimum_msat: None,
4308 htlc_maximum_msat: None,
4310 src_node_id: nodes[3],
4311 short_channel_id: 8,
4313 cltv_expiry_delta: (8 << 4) | 1,
4314 htlc_minimum_msat: None,
4315 htlc_maximum_msat: None,
4316 }]), RouteHint(vec![RouteHintHop {
4317 src_node_id: nodes[4],
4318 short_channel_id: 9,
4321 proportional_millionths: 0,
4323 cltv_expiry_delta: (9 << 4) | 1,
4324 htlc_minimum_msat: None,
4325 htlc_maximum_msat: None,
4326 }]), RouteHint(vec![RouteHintHop {
4327 src_node_id: nodes[5],
4328 short_channel_id: 10,
4330 cltv_expiry_delta: (10 << 4) | 1,
4331 htlc_minimum_msat: None,
4332 htlc_maximum_msat: None,
4337 fn last_hops_with_public_channel_test() {
4338 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4339 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4340 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4341 let scorer = ln_test_utils::TestScorer::new();
4342 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4343 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4344 // This test shows that public routes can be present in the invoice
4345 // which would be handled in the same manner.
4347 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4348 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4349 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4350 assert_eq!(route.paths[0].hops.len(), 5);
4352 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4353 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4354 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4355 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4356 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4357 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4359 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4360 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4361 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4362 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4363 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4364 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4366 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4367 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4368 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4369 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4370 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4371 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4373 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4374 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4375 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4376 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4377 // If we have a peer in the node map, we'll use their features here since we don't have
4378 // a way of figuring out their features from the invoice:
4379 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4380 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4382 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4383 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4384 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4385 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4386 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4387 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4391 fn our_chans_last_hop_connect_test() {
4392 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4393 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4394 let scorer = ln_test_utils::TestScorer::new();
4395 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4396 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4398 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4399 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4400 let mut last_hops = last_hops(&nodes);
4401 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4402 .with_route_hints(last_hops.clone()).unwrap();
4403 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4404 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4405 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4406 &Default::default(), &random_seed_bytes).unwrap();
4407 assert_eq!(route.paths[0].hops.len(), 2);
4409 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4410 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4411 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4412 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4413 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4414 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4416 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4417 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4418 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4419 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4420 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4421 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4423 last_hops[0].0[0].fees.base_msat = 1000;
4425 // Revert to via 6 as the fee on 8 goes up
4426 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4427 .with_route_hints(last_hops).unwrap();
4428 let route_params = RouteParameters::from_payment_params_and_value(
4429 payment_params.clone(), 100);
4430 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4431 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4432 assert_eq!(route.paths[0].hops.len(), 4);
4434 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4435 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4436 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4437 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4438 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4439 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4441 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4442 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4443 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4444 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4445 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4446 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4448 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4449 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4450 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4451 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4452 // If we have a peer in the node map, we'll use their features here since we don't have
4453 // a way of figuring out their features from the invoice:
4454 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4455 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4457 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4458 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4459 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4460 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4461 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4462 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4464 // ...but still use 8 for larger payments as 6 has a variable feerate
4465 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4466 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4467 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4468 assert_eq!(route.paths[0].hops.len(), 5);
4470 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4471 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4472 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4473 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4474 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4475 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4477 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4478 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4479 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4480 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4481 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4482 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4484 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4485 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4486 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4487 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4488 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4489 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4491 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4492 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4493 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4494 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4495 // If we have a peer in the node map, we'll use their features here since we don't have
4496 // a way of figuring out their features from the invoice:
4497 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4498 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4500 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4501 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4502 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4503 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4504 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4505 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4508 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> {
4509 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4510 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4511 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4513 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4514 let last_hops = RouteHint(vec![RouteHintHop {
4515 src_node_id: middle_node_id,
4516 short_channel_id: 8,
4519 proportional_millionths: last_hop_fee_prop,
4521 cltv_expiry_delta: (8 << 4) | 1,
4522 htlc_minimum_msat: None,
4523 htlc_maximum_msat: last_hop_htlc_max,
4525 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4526 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4527 let scorer = ln_test_utils::TestScorer::new();
4528 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4529 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4530 let logger = ln_test_utils::TestLogger::new();
4531 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4532 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4533 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4534 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4535 &random_seed_bytes);
4540 fn unannounced_path_test() {
4541 // We should be able to send a payment to a destination without any help of a routing graph
4542 // if we have a channel with a common counterparty that appears in the first and last hop
4544 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4546 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4547 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4548 assert_eq!(route.paths[0].hops.len(), 2);
4550 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4551 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4552 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4553 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4554 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4555 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4557 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4558 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4559 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4560 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4561 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4562 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4566 fn overflow_unannounced_path_test_liquidity_underflow() {
4567 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4568 // the last-hop had a fee which overflowed a u64, we'd panic.
4569 // This was due to us adding the first-hop from us unconditionally, causing us to think
4570 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4571 // In this test, we previously hit a subtraction underflow due to having less available
4572 // liquidity at the last hop than 0.
4573 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());
4577 fn overflow_unannounced_path_test_feerate_overflow() {
4578 // This tests for the same case as above, except instead of hitting a subtraction
4579 // underflow, we hit a case where the fee charged at a hop overflowed.
4580 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());
4584 fn available_amount_while_routing_test() {
4585 // Tests whether we choose the correct available channel amount while routing.
4587 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4588 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4589 let scorer = ln_test_utils::TestScorer::new();
4590 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4591 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4592 let config = UserConfig::default();
4593 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4594 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4597 // We will use a simple single-path route from
4598 // our node to node2 via node0: channels {1, 3}.
4600 // First disable all other paths.
4601 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4602 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4603 short_channel_id: 2,
4606 cltv_expiry_delta: 0,
4607 htlc_minimum_msat: 0,
4608 htlc_maximum_msat: 100_000,
4610 fee_proportional_millionths: 0,
4611 excess_data: Vec::new()
4613 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4614 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4615 short_channel_id: 12,
4618 cltv_expiry_delta: 0,
4619 htlc_minimum_msat: 0,
4620 htlc_maximum_msat: 100_000,
4622 fee_proportional_millionths: 0,
4623 excess_data: Vec::new()
4626 // Make the first channel (#1) very permissive,
4627 // and we will be testing all limits on the second channel.
4628 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4629 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4630 short_channel_id: 1,
4633 cltv_expiry_delta: 0,
4634 htlc_minimum_msat: 0,
4635 htlc_maximum_msat: 1_000_000_000,
4637 fee_proportional_millionths: 0,
4638 excess_data: Vec::new()
4641 // First, let's see if routing works if we have absolutely no idea about the available amount.
4642 // In this case, it should be set to 250_000 sats.
4643 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4644 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4645 short_channel_id: 3,
4648 cltv_expiry_delta: 0,
4649 htlc_minimum_msat: 0,
4650 htlc_maximum_msat: 250_000_000,
4652 fee_proportional_millionths: 0,
4653 excess_data: Vec::new()
4657 // Attempt to route more than available results in a failure.
4658 let route_params = RouteParameters::from_payment_params_and_value(
4659 payment_params.clone(), 250_000_001);
4660 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4661 &our_id, &route_params, &network_graph.read_only(), None,
4662 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4663 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4664 } else { panic!(); }
4668 // Now, attempt to route an exact amount we have should be fine.
4669 let route_params = RouteParameters::from_payment_params_and_value(
4670 payment_params.clone(), 250_000_000);
4671 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4672 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4673 assert_eq!(route.paths.len(), 1);
4674 let path = route.paths.last().unwrap();
4675 assert_eq!(path.hops.len(), 2);
4676 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4677 assert_eq!(path.final_value_msat(), 250_000_000);
4680 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4681 // Disable channel #1 and use another first hop.
4682 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4683 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4684 short_channel_id: 1,
4687 cltv_expiry_delta: 0,
4688 htlc_minimum_msat: 0,
4689 htlc_maximum_msat: 1_000_000_000,
4691 fee_proportional_millionths: 0,
4692 excess_data: Vec::new()
4695 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4696 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4699 // Attempt to route more than available results in a failure.
4700 let route_params = RouteParameters::from_payment_params_and_value(
4701 payment_params.clone(), 200_000_001);
4702 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4703 &our_id, &route_params, &network_graph.read_only(),
4704 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4705 &Default::default(), &random_seed_bytes) {
4706 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4707 } else { panic!(); }
4711 // Now, attempt to route an exact amount we have should be fine.
4712 let route_params = RouteParameters::from_payment_params_and_value(
4713 payment_params.clone(), 200_000_000);
4714 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4715 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4716 &Default::default(), &random_seed_bytes).unwrap();
4717 assert_eq!(route.paths.len(), 1);
4718 let path = route.paths.last().unwrap();
4719 assert_eq!(path.hops.len(), 2);
4720 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4721 assert_eq!(path.final_value_msat(), 200_000_000);
4724 // Enable channel #1 back.
4725 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4726 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4727 short_channel_id: 1,
4730 cltv_expiry_delta: 0,
4731 htlc_minimum_msat: 0,
4732 htlc_maximum_msat: 1_000_000_000,
4734 fee_proportional_millionths: 0,
4735 excess_data: Vec::new()
4739 // Now let's see if routing works if we know only htlc_maximum_msat.
4740 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4741 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4742 short_channel_id: 3,
4745 cltv_expiry_delta: 0,
4746 htlc_minimum_msat: 0,
4747 htlc_maximum_msat: 15_000,
4749 fee_proportional_millionths: 0,
4750 excess_data: Vec::new()
4754 // Attempt to route more than available results in a failure.
4755 let route_params = RouteParameters::from_payment_params_and_value(
4756 payment_params.clone(), 15_001);
4757 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4758 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4759 &scorer, &Default::default(), &random_seed_bytes) {
4760 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4761 } else { panic!(); }
4765 // Now, attempt to route an exact amount we have should be fine.
4766 let route_params = RouteParameters::from_payment_params_and_value(
4767 payment_params.clone(), 15_000);
4768 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4769 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4770 assert_eq!(route.paths.len(), 1);
4771 let path = route.paths.last().unwrap();
4772 assert_eq!(path.hops.len(), 2);
4773 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4774 assert_eq!(path.final_value_msat(), 15_000);
4777 // Now let's see if routing works if we know only capacity from the UTXO.
4779 // We can't change UTXO capacity on the fly, so we'll disable
4780 // the existing channel and add another one with the capacity we need.
4781 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4782 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4783 short_channel_id: 3,
4786 cltv_expiry_delta: 0,
4787 htlc_minimum_msat: 0,
4788 htlc_maximum_msat: MAX_VALUE_MSAT,
4790 fee_proportional_millionths: 0,
4791 excess_data: Vec::new()
4794 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4795 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4796 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4797 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4798 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4800 *chain_monitor.utxo_ret.lock().unwrap() =
4801 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4802 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4804 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4805 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4806 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4807 short_channel_id: 333,
4810 cltv_expiry_delta: (3 << 4) | 1,
4811 htlc_minimum_msat: 0,
4812 htlc_maximum_msat: 15_000,
4814 fee_proportional_millionths: 0,
4815 excess_data: Vec::new()
4817 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4818 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4819 short_channel_id: 333,
4822 cltv_expiry_delta: (3 << 4) | 2,
4823 htlc_minimum_msat: 0,
4824 htlc_maximum_msat: 15_000,
4826 fee_proportional_millionths: 0,
4827 excess_data: Vec::new()
4831 // Attempt to route more than available results in a failure.
4832 let route_params = RouteParameters::from_payment_params_and_value(
4833 payment_params.clone(), 15_001);
4834 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4835 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4836 &scorer, &Default::default(), &random_seed_bytes) {
4837 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4838 } else { panic!(); }
4842 // Now, attempt to route an exact amount we have should be fine.
4843 let route_params = RouteParameters::from_payment_params_and_value(
4844 payment_params.clone(), 15_000);
4845 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4846 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4847 assert_eq!(route.paths.len(), 1);
4848 let path = route.paths.last().unwrap();
4849 assert_eq!(path.hops.len(), 2);
4850 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4851 assert_eq!(path.final_value_msat(), 15_000);
4854 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4855 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4856 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4857 short_channel_id: 333,
4860 cltv_expiry_delta: 0,
4861 htlc_minimum_msat: 0,
4862 htlc_maximum_msat: 10_000,
4864 fee_proportional_millionths: 0,
4865 excess_data: Vec::new()
4869 // Attempt to route more than available results in a failure.
4870 let route_params = RouteParameters::from_payment_params_and_value(
4871 payment_params.clone(), 10_001);
4872 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4873 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4874 &scorer, &Default::default(), &random_seed_bytes) {
4875 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4876 } else { panic!(); }
4880 // Now, attempt to route an exact amount we have should be fine.
4881 let route_params = RouteParameters::from_payment_params_and_value(
4882 payment_params.clone(), 10_000);
4883 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4884 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4885 assert_eq!(route.paths.len(), 1);
4886 let path = route.paths.last().unwrap();
4887 assert_eq!(path.hops.len(), 2);
4888 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4889 assert_eq!(path.final_value_msat(), 10_000);
4894 fn available_liquidity_last_hop_test() {
4895 // Check that available liquidity properly limits the path even when only
4896 // one of the latter hops is limited.
4897 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4898 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4899 let scorer = ln_test_utils::TestScorer::new();
4900 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4901 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4902 let config = UserConfig::default();
4903 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4904 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4907 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4908 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4909 // Total capacity: 50 sats.
4911 // Disable other potential paths.
4912 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4913 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4914 short_channel_id: 2,
4917 cltv_expiry_delta: 0,
4918 htlc_minimum_msat: 0,
4919 htlc_maximum_msat: 100_000,
4921 fee_proportional_millionths: 0,
4922 excess_data: Vec::new()
4924 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4925 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4926 short_channel_id: 7,
4929 cltv_expiry_delta: 0,
4930 htlc_minimum_msat: 0,
4931 htlc_maximum_msat: 100_000,
4933 fee_proportional_millionths: 0,
4934 excess_data: Vec::new()
4939 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4940 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4941 short_channel_id: 12,
4944 cltv_expiry_delta: 0,
4945 htlc_minimum_msat: 0,
4946 htlc_maximum_msat: 100_000,
4948 fee_proportional_millionths: 0,
4949 excess_data: Vec::new()
4951 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4952 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4953 short_channel_id: 13,
4956 cltv_expiry_delta: 0,
4957 htlc_minimum_msat: 0,
4958 htlc_maximum_msat: 100_000,
4960 fee_proportional_millionths: 0,
4961 excess_data: Vec::new()
4964 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4965 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4966 short_channel_id: 6,
4969 cltv_expiry_delta: 0,
4970 htlc_minimum_msat: 0,
4971 htlc_maximum_msat: 50_000,
4973 fee_proportional_millionths: 0,
4974 excess_data: Vec::new()
4976 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4977 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4978 short_channel_id: 11,
4981 cltv_expiry_delta: 0,
4982 htlc_minimum_msat: 0,
4983 htlc_maximum_msat: 100_000,
4985 fee_proportional_millionths: 0,
4986 excess_data: Vec::new()
4989 // Attempt to route more than available results in a failure.
4990 let route_params = RouteParameters::from_payment_params_and_value(
4991 payment_params.clone(), 60_000);
4992 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4993 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4994 &scorer, &Default::default(), &random_seed_bytes) {
4995 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4996 } else { panic!(); }
5000 // Now, attempt to route 49 sats (just a bit below the capacity).
5001 let route_params = RouteParameters::from_payment_params_and_value(
5002 payment_params.clone(), 49_000);
5003 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5004 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5005 assert_eq!(route.paths.len(), 1);
5006 let mut total_amount_paid_msat = 0;
5007 for path in &route.paths {
5008 assert_eq!(path.hops.len(), 4);
5009 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5010 total_amount_paid_msat += path.final_value_msat();
5012 assert_eq!(total_amount_paid_msat, 49_000);
5016 // Attempt to route an exact amount is also fine
5017 let route_params = RouteParameters::from_payment_params_and_value(
5018 payment_params, 50_000);
5019 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5020 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5021 assert_eq!(route.paths.len(), 1);
5022 let mut total_amount_paid_msat = 0;
5023 for path in &route.paths {
5024 assert_eq!(path.hops.len(), 4);
5025 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5026 total_amount_paid_msat += path.final_value_msat();
5028 assert_eq!(total_amount_paid_msat, 50_000);
5033 fn ignore_fee_first_hop_test() {
5034 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5035 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5036 let scorer = ln_test_utils::TestScorer::new();
5037 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5038 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5039 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5041 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5042 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5043 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5044 short_channel_id: 1,
5047 cltv_expiry_delta: 0,
5048 htlc_minimum_msat: 0,
5049 htlc_maximum_msat: 100_000,
5050 fee_base_msat: 1_000_000,
5051 fee_proportional_millionths: 0,
5052 excess_data: Vec::new()
5054 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5055 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5056 short_channel_id: 3,
5059 cltv_expiry_delta: 0,
5060 htlc_minimum_msat: 0,
5061 htlc_maximum_msat: 50_000,
5063 fee_proportional_millionths: 0,
5064 excess_data: Vec::new()
5068 let route_params = RouteParameters::from_payment_params_and_value(
5069 payment_params, 50_000);
5070 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5071 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5072 assert_eq!(route.paths.len(), 1);
5073 let mut total_amount_paid_msat = 0;
5074 for path in &route.paths {
5075 assert_eq!(path.hops.len(), 2);
5076 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5077 total_amount_paid_msat += path.final_value_msat();
5079 assert_eq!(total_amount_paid_msat, 50_000);
5084 fn simple_mpp_route_test() {
5085 let (secp_ctx, _, _, _, _) = build_graph();
5086 let (_, _, _, nodes) = get_nodes(&secp_ctx);
5087 let config = UserConfig::default();
5088 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5089 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5091 do_simple_mpp_route_test(clear_payment_params);
5093 // MPP to a 1-hop blinded path for nodes[2]
5094 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
5095 let blinded_path = BlindedPath {
5096 introduction_node_id: nodes[2],
5097 blinding_point: ln_test_utils::pubkey(42),
5098 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
5100 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
5102 fee_proportional_millionths: 0,
5103 htlc_minimum_msat: 0,
5104 htlc_maximum_msat: 0,
5105 cltv_expiry_delta: 0,
5106 features: BlindedHopFeatures::empty(),
5108 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
5109 .with_bolt12_features(bolt12_features.clone()).unwrap();
5110 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
5112 // MPP to 3 2-hop blinded paths
5113 let mut blinded_path_node_0 = blinded_path.clone();
5114 blinded_path_node_0.introduction_node_id = nodes[0];
5115 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
5116 let mut node_0_payinfo = blinded_payinfo.clone();
5117 node_0_payinfo.htlc_maximum_msat = 50_000;
5119 let mut blinded_path_node_7 = blinded_path_node_0.clone();
5120 blinded_path_node_7.introduction_node_id = nodes[7];
5121 let mut node_7_payinfo = blinded_payinfo.clone();
5122 node_7_payinfo.htlc_maximum_msat = 60_000;
5124 let mut blinded_path_node_1 = blinded_path_node_0.clone();
5125 blinded_path_node_1.introduction_node_id = nodes[1];
5126 let mut node_1_payinfo = blinded_payinfo.clone();
5127 node_1_payinfo.htlc_maximum_msat = 180_000;
5129 let two_hop_blinded_payment_params = PaymentParameters::blinded(
5131 (node_0_payinfo, blinded_path_node_0),
5132 (node_7_payinfo, blinded_path_node_7),
5133 (node_1_payinfo, blinded_path_node_1)
5135 .with_bolt12_features(bolt12_features).unwrap();
5136 do_simple_mpp_route_test(two_hop_blinded_payment_params);
5140 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
5141 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5142 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5143 let scorer = ln_test_utils::TestScorer::new();
5144 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5145 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5147 // We need a route consisting of 3 paths:
5148 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5149 // To achieve this, the amount being transferred should be around
5150 // the total capacity of these 3 paths.
5152 // First, we set limits on these (previously unlimited) channels.
5153 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
5155 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5156 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5157 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5158 short_channel_id: 1,
5161 cltv_expiry_delta: 0,
5162 htlc_minimum_msat: 0,
5163 htlc_maximum_msat: 100_000,
5165 fee_proportional_millionths: 0,
5166 excess_data: Vec::new()
5168 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5169 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5170 short_channel_id: 3,
5173 cltv_expiry_delta: 0,
5174 htlc_minimum_msat: 0,
5175 htlc_maximum_msat: 50_000,
5177 fee_proportional_millionths: 0,
5178 excess_data: Vec::new()
5181 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
5182 // (total limit 60).
5183 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5184 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5185 short_channel_id: 12,
5188 cltv_expiry_delta: 0,
5189 htlc_minimum_msat: 0,
5190 htlc_maximum_msat: 60_000,
5192 fee_proportional_millionths: 0,
5193 excess_data: Vec::new()
5195 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5196 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5197 short_channel_id: 13,
5200 cltv_expiry_delta: 0,
5201 htlc_minimum_msat: 0,
5202 htlc_maximum_msat: 60_000,
5204 fee_proportional_millionths: 0,
5205 excess_data: Vec::new()
5208 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5209 // (total capacity 180 sats).
5210 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5211 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5212 short_channel_id: 2,
5215 cltv_expiry_delta: 0,
5216 htlc_minimum_msat: 0,
5217 htlc_maximum_msat: 200_000,
5219 fee_proportional_millionths: 0,
5220 excess_data: Vec::new()
5222 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5223 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5224 short_channel_id: 4,
5227 cltv_expiry_delta: 0,
5228 htlc_minimum_msat: 0,
5229 htlc_maximum_msat: 180_000,
5231 fee_proportional_millionths: 0,
5232 excess_data: Vec::new()
5236 // Attempt to route more than available results in a failure.
5237 let route_params = RouteParameters::from_payment_params_and_value(
5238 payment_params.clone(), 300_000);
5239 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5240 &our_id, &route_params, &network_graph.read_only(), None,
5241 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5242 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5243 } else { panic!(); }
5247 // Attempt to route while setting max_path_count to 0 results in a failure.
5248 let zero_payment_params = payment_params.clone().with_max_path_count(0);
5249 let route_params = RouteParameters::from_payment_params_and_value(
5250 zero_payment_params, 100);
5251 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5252 &our_id, &route_params, &network_graph.read_only(), None,
5253 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5254 assert_eq!(err, "Can't find a route with no paths allowed.");
5255 } else { panic!(); }
5259 // Attempt to route while setting max_path_count to 3 results in a failure.
5260 // This is the case because the minimal_value_contribution_msat would require each path
5261 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5262 let fail_payment_params = payment_params.clone().with_max_path_count(3);
5263 let route_params = RouteParameters::from_payment_params_and_value(
5264 fail_payment_params, 250_000);
5265 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5266 &our_id, &route_params, &network_graph.read_only(), None,
5267 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5268 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5269 } else { panic!(); }
5273 // Now, attempt to route 250 sats (just a bit below the capacity).
5274 // Our algorithm should provide us with these 3 paths.
5275 let route_params = RouteParameters::from_payment_params_and_value(
5276 payment_params.clone(), 250_000);
5277 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5278 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5279 assert_eq!(route.paths.len(), 3);
5280 let mut total_amount_paid_msat = 0;
5281 for path in &route.paths {
5282 if let Some(bt) = &path.blinded_tail {
5283 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5285 assert_eq!(path.hops.len(), 2);
5286 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5288 total_amount_paid_msat += path.final_value_msat();
5290 assert_eq!(total_amount_paid_msat, 250_000);
5294 // Attempt to route an exact amount is also fine
5295 let route_params = RouteParameters::from_payment_params_and_value(
5296 payment_params.clone(), 290_000);
5297 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5298 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5299 assert_eq!(route.paths.len(), 3);
5300 let mut total_amount_paid_msat = 0;
5301 for path in &route.paths {
5302 if payment_params.payee.blinded_route_hints().len() != 0 {
5303 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5304 if let Some(bt) = &path.blinded_tail {
5305 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5306 if bt.hops.len() > 1 {
5307 assert_eq!(path.hops.last().unwrap().pubkey,
5308 payment_params.payee.blinded_route_hints().iter()
5309 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5310 .map(|(_, p)| p.introduction_node_id).unwrap());
5312 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5315 assert_eq!(path.hops.len(), 2);
5316 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5318 total_amount_paid_msat += path.final_value_msat();
5320 assert_eq!(total_amount_paid_msat, 290_000);
5325 fn long_mpp_route_test() {
5326 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5327 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5328 let scorer = ln_test_utils::TestScorer::new();
5329 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5330 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5331 let config = UserConfig::default();
5332 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5333 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5336 // We need a route consisting of 3 paths:
5337 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5338 // Note that these paths overlap (channels 5, 12, 13).
5339 // We will route 300 sats.
5340 // Each path will have 100 sats capacity, those channels which
5341 // are used twice will have 200 sats capacity.
5343 // Disable other potential paths.
5344 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5345 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5346 short_channel_id: 2,
5349 cltv_expiry_delta: 0,
5350 htlc_minimum_msat: 0,
5351 htlc_maximum_msat: 100_000,
5353 fee_proportional_millionths: 0,
5354 excess_data: Vec::new()
5356 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5357 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5358 short_channel_id: 7,
5361 cltv_expiry_delta: 0,
5362 htlc_minimum_msat: 0,
5363 htlc_maximum_msat: 100_000,
5365 fee_proportional_millionths: 0,
5366 excess_data: Vec::new()
5369 // Path via {node0, node2} is channels {1, 3, 5}.
5370 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5371 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5372 short_channel_id: 1,
5375 cltv_expiry_delta: 0,
5376 htlc_minimum_msat: 0,
5377 htlc_maximum_msat: 100_000,
5379 fee_proportional_millionths: 0,
5380 excess_data: Vec::new()
5382 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5383 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5384 short_channel_id: 3,
5387 cltv_expiry_delta: 0,
5388 htlc_minimum_msat: 0,
5389 htlc_maximum_msat: 100_000,
5391 fee_proportional_millionths: 0,
5392 excess_data: Vec::new()
5395 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5396 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5397 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5398 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5399 short_channel_id: 5,
5402 cltv_expiry_delta: 0,
5403 htlc_minimum_msat: 0,
5404 htlc_maximum_msat: 200_000,
5406 fee_proportional_millionths: 0,
5407 excess_data: Vec::new()
5410 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5411 // Add 100 sats to the capacities of {12, 13}, because these channels
5412 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5413 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5414 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5415 short_channel_id: 12,
5418 cltv_expiry_delta: 0,
5419 htlc_minimum_msat: 0,
5420 htlc_maximum_msat: 200_000,
5422 fee_proportional_millionths: 0,
5423 excess_data: Vec::new()
5425 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5426 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5427 short_channel_id: 13,
5430 cltv_expiry_delta: 0,
5431 htlc_minimum_msat: 0,
5432 htlc_maximum_msat: 200_000,
5434 fee_proportional_millionths: 0,
5435 excess_data: Vec::new()
5438 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5439 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5440 short_channel_id: 6,
5443 cltv_expiry_delta: 0,
5444 htlc_minimum_msat: 0,
5445 htlc_maximum_msat: 100_000,
5447 fee_proportional_millionths: 0,
5448 excess_data: Vec::new()
5450 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5451 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5452 short_channel_id: 11,
5455 cltv_expiry_delta: 0,
5456 htlc_minimum_msat: 0,
5457 htlc_maximum_msat: 100_000,
5459 fee_proportional_millionths: 0,
5460 excess_data: Vec::new()
5463 // Path via {node7, node2} is channels {12, 13, 5}.
5464 // We already limited them to 200 sats (they are used twice for 100 sats).
5465 // Nothing to do here.
5468 // Attempt to route more than available results in a failure.
5469 let route_params = RouteParameters::from_payment_params_and_value(
5470 payment_params.clone(), 350_000);
5471 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5472 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5473 &scorer, &Default::default(), &random_seed_bytes) {
5474 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5475 } else { panic!(); }
5479 // Now, attempt to route 300 sats (exact amount we can route).
5480 // Our algorithm should provide us with these 3 paths, 100 sats each.
5481 let route_params = RouteParameters::from_payment_params_and_value(
5482 payment_params, 300_000);
5483 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5484 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5485 assert_eq!(route.paths.len(), 3);
5487 let mut total_amount_paid_msat = 0;
5488 for path in &route.paths {
5489 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5490 total_amount_paid_msat += path.final_value_msat();
5492 assert_eq!(total_amount_paid_msat, 300_000);
5498 fn mpp_cheaper_route_test() {
5499 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5500 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5501 let scorer = ln_test_utils::TestScorer::new();
5502 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5503 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5504 let config = UserConfig::default();
5505 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5506 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5509 // This test checks that if we have two cheaper paths and one more expensive path,
5510 // so that liquidity-wise any 2 of 3 combination is sufficient,
5511 // two cheaper paths will be taken.
5512 // These paths have equal available liquidity.
5514 // We need a combination of 3 paths:
5515 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5516 // Note that these paths overlap (channels 5, 12, 13).
5517 // Each path will have 100 sats capacity, those channels which
5518 // are used twice will have 200 sats capacity.
5520 // Disable other potential paths.
5521 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5522 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5523 short_channel_id: 2,
5526 cltv_expiry_delta: 0,
5527 htlc_minimum_msat: 0,
5528 htlc_maximum_msat: 100_000,
5530 fee_proportional_millionths: 0,
5531 excess_data: Vec::new()
5533 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5534 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5535 short_channel_id: 7,
5538 cltv_expiry_delta: 0,
5539 htlc_minimum_msat: 0,
5540 htlc_maximum_msat: 100_000,
5542 fee_proportional_millionths: 0,
5543 excess_data: Vec::new()
5546 // Path via {node0, node2} is channels {1, 3, 5}.
5547 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5548 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5549 short_channel_id: 1,
5552 cltv_expiry_delta: 0,
5553 htlc_minimum_msat: 0,
5554 htlc_maximum_msat: 100_000,
5556 fee_proportional_millionths: 0,
5557 excess_data: Vec::new()
5559 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5560 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5561 short_channel_id: 3,
5564 cltv_expiry_delta: 0,
5565 htlc_minimum_msat: 0,
5566 htlc_maximum_msat: 100_000,
5568 fee_proportional_millionths: 0,
5569 excess_data: Vec::new()
5572 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5573 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5574 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5575 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5576 short_channel_id: 5,
5579 cltv_expiry_delta: 0,
5580 htlc_minimum_msat: 0,
5581 htlc_maximum_msat: 200_000,
5583 fee_proportional_millionths: 0,
5584 excess_data: Vec::new()
5587 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5588 // Add 100 sats to the capacities of {12, 13}, because these channels
5589 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5590 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5591 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5592 short_channel_id: 12,
5595 cltv_expiry_delta: 0,
5596 htlc_minimum_msat: 0,
5597 htlc_maximum_msat: 200_000,
5599 fee_proportional_millionths: 0,
5600 excess_data: Vec::new()
5602 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5603 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5604 short_channel_id: 13,
5607 cltv_expiry_delta: 0,
5608 htlc_minimum_msat: 0,
5609 htlc_maximum_msat: 200_000,
5611 fee_proportional_millionths: 0,
5612 excess_data: Vec::new()
5615 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5616 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5617 short_channel_id: 6,
5620 cltv_expiry_delta: 0,
5621 htlc_minimum_msat: 0,
5622 htlc_maximum_msat: 100_000,
5623 fee_base_msat: 1_000,
5624 fee_proportional_millionths: 0,
5625 excess_data: Vec::new()
5627 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5628 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5629 short_channel_id: 11,
5632 cltv_expiry_delta: 0,
5633 htlc_minimum_msat: 0,
5634 htlc_maximum_msat: 100_000,
5636 fee_proportional_millionths: 0,
5637 excess_data: Vec::new()
5640 // Path via {node7, node2} is channels {12, 13, 5}.
5641 // We already limited them to 200 sats (they are used twice for 100 sats).
5642 // Nothing to do here.
5645 // Now, attempt to route 180 sats.
5646 // Our algorithm should provide us with these 2 paths.
5647 let route_params = RouteParameters::from_payment_params_and_value(
5648 payment_params, 180_000);
5649 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5650 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5651 assert_eq!(route.paths.len(), 2);
5653 let mut total_value_transferred_msat = 0;
5654 let mut total_paid_msat = 0;
5655 for path in &route.paths {
5656 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5657 total_value_transferred_msat += path.final_value_msat();
5658 for hop in &path.hops {
5659 total_paid_msat += hop.fee_msat;
5662 // If we paid fee, this would be higher.
5663 assert_eq!(total_value_transferred_msat, 180_000);
5664 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5665 assert_eq!(total_fees_paid, 0);
5670 fn fees_on_mpp_route_test() {
5671 // This test makes sure that MPP algorithm properly takes into account
5672 // fees charged on the channels, by making the fees impactful:
5673 // if the fee is not properly accounted for, the behavior is different.
5674 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5675 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5676 let scorer = ln_test_utils::TestScorer::new();
5677 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5678 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5679 let config = UserConfig::default();
5680 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5681 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5684 // We need a route consisting of 2 paths:
5685 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5686 // We will route 200 sats, Each path will have 100 sats capacity.
5688 // This test is not particularly stable: e.g.,
5689 // there's a way to route via {node0, node2, node4}.
5690 // It works while pathfinding is deterministic, but can be broken otherwise.
5691 // It's fine to ignore this concern for now.
5693 // Disable other potential paths.
5694 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5695 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5696 short_channel_id: 2,
5699 cltv_expiry_delta: 0,
5700 htlc_minimum_msat: 0,
5701 htlc_maximum_msat: 100_000,
5703 fee_proportional_millionths: 0,
5704 excess_data: Vec::new()
5707 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5708 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5709 short_channel_id: 7,
5712 cltv_expiry_delta: 0,
5713 htlc_minimum_msat: 0,
5714 htlc_maximum_msat: 100_000,
5716 fee_proportional_millionths: 0,
5717 excess_data: Vec::new()
5720 // Path via {node0, node2} is channels {1, 3, 5}.
5721 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5722 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5723 short_channel_id: 1,
5726 cltv_expiry_delta: 0,
5727 htlc_minimum_msat: 0,
5728 htlc_maximum_msat: 100_000,
5730 fee_proportional_millionths: 0,
5731 excess_data: Vec::new()
5733 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5734 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5735 short_channel_id: 3,
5738 cltv_expiry_delta: 0,
5739 htlc_minimum_msat: 0,
5740 htlc_maximum_msat: 100_000,
5742 fee_proportional_millionths: 0,
5743 excess_data: Vec::new()
5746 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5747 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5748 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5749 short_channel_id: 5,
5752 cltv_expiry_delta: 0,
5753 htlc_minimum_msat: 0,
5754 htlc_maximum_msat: 100_000,
5756 fee_proportional_millionths: 0,
5757 excess_data: Vec::new()
5760 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5761 // All channels should be 100 sats capacity. But for the fee experiment,
5762 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5763 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5764 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5765 // so no matter how large are other channels,
5766 // the whole path will be limited by 100 sats with just these 2 conditions:
5767 // - channel 12 capacity is 250 sats
5768 // - fee for channel 6 is 150 sats
5769 // Let's test this by enforcing these 2 conditions and removing other limits.
5770 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5771 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5772 short_channel_id: 12,
5775 cltv_expiry_delta: 0,
5776 htlc_minimum_msat: 0,
5777 htlc_maximum_msat: 250_000,
5779 fee_proportional_millionths: 0,
5780 excess_data: Vec::new()
5782 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5783 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5784 short_channel_id: 13,
5787 cltv_expiry_delta: 0,
5788 htlc_minimum_msat: 0,
5789 htlc_maximum_msat: MAX_VALUE_MSAT,
5791 fee_proportional_millionths: 0,
5792 excess_data: Vec::new()
5795 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5796 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5797 short_channel_id: 6,
5800 cltv_expiry_delta: 0,
5801 htlc_minimum_msat: 0,
5802 htlc_maximum_msat: MAX_VALUE_MSAT,
5803 fee_base_msat: 150_000,
5804 fee_proportional_millionths: 0,
5805 excess_data: Vec::new()
5807 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5808 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5809 short_channel_id: 11,
5812 cltv_expiry_delta: 0,
5813 htlc_minimum_msat: 0,
5814 htlc_maximum_msat: MAX_VALUE_MSAT,
5816 fee_proportional_millionths: 0,
5817 excess_data: Vec::new()
5821 // Attempt to route more than available results in a failure.
5822 let route_params = RouteParameters::from_payment_params_and_value(
5823 payment_params.clone(), 210_000);
5824 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5825 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5826 &scorer, &Default::default(), &random_seed_bytes) {
5827 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5828 } else { panic!(); }
5832 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5833 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5834 max_total_routing_fee_msat: Some(149_999) };
5835 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5836 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5837 &scorer, &Default::default(), &random_seed_bytes) {
5838 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5839 } else { panic!(); }
5843 // Now, attempt to route 200 sats (exact amount we can route).
5844 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5845 max_total_routing_fee_msat: Some(150_000) };
5846 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5847 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5848 assert_eq!(route.paths.len(), 2);
5850 let mut total_amount_paid_msat = 0;
5851 for path in &route.paths {
5852 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5853 total_amount_paid_msat += path.final_value_msat();
5855 assert_eq!(total_amount_paid_msat, 200_000);
5856 assert_eq!(route.get_total_fees(), 150_000);
5861 fn mpp_with_last_hops() {
5862 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5863 // via a single last-hop route hint, we'd fail to route if we first collected routes
5864 // totaling close but not quite enough to fund the full payment.
5866 // This was because we considered last-hop hints to have exactly the sought payment amount
5867 // instead of the amount we were trying to collect, needlessly limiting our path searching
5868 // at the very first hop.
5870 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5871 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5872 // to only have the remaining to-collect amount in available liquidity.
5874 // This bug appeared in production in some specific channel configurations.
5875 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5876 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5877 let scorer = ln_test_utils::TestScorer::new();
5878 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5879 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5880 let config = UserConfig::default();
5881 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
5882 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
5883 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5884 src_node_id: nodes[2],
5885 short_channel_id: 42,
5886 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5887 cltv_expiry_delta: 42,
5888 htlc_minimum_msat: None,
5889 htlc_maximum_msat: None,
5890 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5892 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5893 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5894 // would first use the no-fee route and then fail to find a path along the second route as
5895 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5896 // under 5% of our payment amount.
5897 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5898 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5899 short_channel_id: 1,
5902 cltv_expiry_delta: (5 << 4) | 5,
5903 htlc_minimum_msat: 0,
5904 htlc_maximum_msat: 99_000,
5905 fee_base_msat: u32::max_value(),
5906 fee_proportional_millionths: u32::max_value(),
5907 excess_data: Vec::new()
5909 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5910 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5911 short_channel_id: 2,
5914 cltv_expiry_delta: (5 << 4) | 3,
5915 htlc_minimum_msat: 0,
5916 htlc_maximum_msat: 99_000,
5917 fee_base_msat: u32::max_value(),
5918 fee_proportional_millionths: u32::max_value(),
5919 excess_data: Vec::new()
5921 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5922 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5923 short_channel_id: 4,
5926 cltv_expiry_delta: (4 << 4) | 1,
5927 htlc_minimum_msat: 0,
5928 htlc_maximum_msat: MAX_VALUE_MSAT,
5930 fee_proportional_millionths: 0,
5931 excess_data: Vec::new()
5933 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5934 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5935 short_channel_id: 13,
5937 flags: 0|2, // Channel disabled
5938 cltv_expiry_delta: (13 << 4) | 1,
5939 htlc_minimum_msat: 0,
5940 htlc_maximum_msat: MAX_VALUE_MSAT,
5942 fee_proportional_millionths: 2000000,
5943 excess_data: Vec::new()
5946 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5948 let route_params = RouteParameters::from_payment_params_and_value(
5949 payment_params, 100_000);
5950 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5951 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5952 assert_eq!(route.paths.len(), 2);
5953 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5954 // Paths are manually ordered ordered by SCID, so:
5955 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5956 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5957 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5958 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5959 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5960 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5961 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5962 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5963 assert_eq!(route.get_total_fees(), 1);
5964 assert_eq!(route.get_total_amount(), 100_000);
5968 fn drop_lowest_channel_mpp_route_test() {
5969 // This test checks that low-capacity channel is dropped when after
5970 // path finding we realize that we found more capacity than we need.
5971 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5972 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5973 let scorer = ln_test_utils::TestScorer::new();
5974 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5975 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5976 let config = UserConfig::default();
5977 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5978 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5980 .with_max_channel_saturation_power_of_half(0);
5982 // We need a route consisting of 3 paths:
5983 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5985 // The first and the second paths should be sufficient, but the third should be
5986 // cheaper, so that we select it but drop later.
5988 // First, we set limits on these (previously unlimited) channels.
5989 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5991 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5992 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5993 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5994 short_channel_id: 1,
5997 cltv_expiry_delta: 0,
5998 htlc_minimum_msat: 0,
5999 htlc_maximum_msat: 100_000,
6001 fee_proportional_millionths: 0,
6002 excess_data: Vec::new()
6004 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6005 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6006 short_channel_id: 3,
6009 cltv_expiry_delta: 0,
6010 htlc_minimum_msat: 0,
6011 htlc_maximum_msat: 50_000,
6013 fee_proportional_millionths: 0,
6014 excess_data: Vec::new()
6017 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
6018 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6019 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6020 short_channel_id: 12,
6023 cltv_expiry_delta: 0,
6024 htlc_minimum_msat: 0,
6025 htlc_maximum_msat: 60_000,
6027 fee_proportional_millionths: 0,
6028 excess_data: Vec::new()
6030 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6031 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6032 short_channel_id: 13,
6035 cltv_expiry_delta: 0,
6036 htlc_minimum_msat: 0,
6037 htlc_maximum_msat: 60_000,
6039 fee_proportional_millionths: 0,
6040 excess_data: Vec::new()
6043 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
6044 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6045 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6046 short_channel_id: 2,
6049 cltv_expiry_delta: 0,
6050 htlc_minimum_msat: 0,
6051 htlc_maximum_msat: 20_000,
6053 fee_proportional_millionths: 0,
6054 excess_data: Vec::new()
6056 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6057 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6058 short_channel_id: 4,
6061 cltv_expiry_delta: 0,
6062 htlc_minimum_msat: 0,
6063 htlc_maximum_msat: 20_000,
6065 fee_proportional_millionths: 0,
6066 excess_data: Vec::new()
6070 // Attempt to route more than available results in a failure.
6071 let route_params = RouteParameters::from_payment_params_and_value(
6072 payment_params.clone(), 150_000);
6073 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6074 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6075 &scorer, &Default::default(), &random_seed_bytes) {
6076 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6077 } else { panic!(); }
6081 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
6082 // Our algorithm should provide us with these 3 paths.
6083 let route_params = RouteParameters::from_payment_params_and_value(
6084 payment_params.clone(), 125_000);
6085 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6086 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6087 assert_eq!(route.paths.len(), 3);
6088 let mut total_amount_paid_msat = 0;
6089 for path in &route.paths {
6090 assert_eq!(path.hops.len(), 2);
6091 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6092 total_amount_paid_msat += path.final_value_msat();
6094 assert_eq!(total_amount_paid_msat, 125_000);
6098 // Attempt to route without the last small cheap channel
6099 let route_params = RouteParameters::from_payment_params_and_value(
6100 payment_params, 90_000);
6101 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6102 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6103 assert_eq!(route.paths.len(), 2);
6104 let mut total_amount_paid_msat = 0;
6105 for path in &route.paths {
6106 assert_eq!(path.hops.len(), 2);
6107 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6108 total_amount_paid_msat += path.final_value_msat();
6110 assert_eq!(total_amount_paid_msat, 90_000);
6115 fn min_criteria_consistency() {
6116 // Test that we don't use an inconsistent metric between updating and walking nodes during
6117 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
6118 // was updated with a different criterion from the heap sorting, resulting in loops in
6119 // calculated paths. We test for that specific case here.
6121 // We construct a network that looks like this:
6123 // node2 -1(3)2- node3
6127 // node1 -1(5)2- node4 -1(1)2- node6
6133 // We create a loop on the side of our real path - our destination is node 6, with a
6134 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
6135 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
6136 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
6137 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
6138 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
6139 // "previous hop" being set to node 3, creating a loop in the path.
6140 let secp_ctx = Secp256k1::new();
6141 let logger = Arc::new(ln_test_utils::TestLogger::new());
6142 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6143 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
6144 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6145 let scorer = ln_test_utils::TestScorer::new();
6146 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6147 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6148 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
6150 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
6151 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6152 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6153 short_channel_id: 6,
6156 cltv_expiry_delta: (6 << 4) | 0,
6157 htlc_minimum_msat: 0,
6158 htlc_maximum_msat: MAX_VALUE_MSAT,
6160 fee_proportional_millionths: 0,
6161 excess_data: Vec::new()
6163 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
6165 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6166 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6167 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6168 short_channel_id: 5,
6171 cltv_expiry_delta: (5 << 4) | 0,
6172 htlc_minimum_msat: 0,
6173 htlc_maximum_msat: MAX_VALUE_MSAT,
6175 fee_proportional_millionths: 0,
6176 excess_data: Vec::new()
6178 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
6180 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
6181 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6182 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6183 short_channel_id: 4,
6186 cltv_expiry_delta: (4 << 4) | 0,
6187 htlc_minimum_msat: 0,
6188 htlc_maximum_msat: MAX_VALUE_MSAT,
6190 fee_proportional_millionths: 0,
6191 excess_data: Vec::new()
6193 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6195 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6196 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
6197 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6198 short_channel_id: 3,
6201 cltv_expiry_delta: (3 << 4) | 0,
6202 htlc_minimum_msat: 0,
6203 htlc_maximum_msat: MAX_VALUE_MSAT,
6205 fee_proportional_millionths: 0,
6206 excess_data: Vec::new()
6208 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6210 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6211 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
6212 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6213 short_channel_id: 2,
6216 cltv_expiry_delta: (2 << 4) | 0,
6217 htlc_minimum_msat: 0,
6218 htlc_maximum_msat: MAX_VALUE_MSAT,
6220 fee_proportional_millionths: 0,
6221 excess_data: Vec::new()
6224 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6225 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6226 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6227 short_channel_id: 1,
6230 cltv_expiry_delta: (1 << 4) | 0,
6231 htlc_minimum_msat: 100,
6232 htlc_maximum_msat: MAX_VALUE_MSAT,
6234 fee_proportional_millionths: 0,
6235 excess_data: Vec::new()
6237 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6240 // Now ensure the route flows simply over nodes 1 and 4 to 6.
6241 let route_params = RouteParameters::from_payment_params_and_value(
6242 payment_params, 10_000);
6243 let route = get_route(&our_id, &route_params, &network.read_only(), None,
6244 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6245 assert_eq!(route.paths.len(), 1);
6246 assert_eq!(route.paths[0].hops.len(), 3);
6248 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6249 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6250 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6251 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6252 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6253 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6255 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6256 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6257 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6258 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6259 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6260 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6262 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6263 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6264 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6265 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6266 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6267 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6273 fn exact_fee_liquidity_limit() {
6274 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6275 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6276 // we calculated fees on a higher value, resulting in us ignoring such paths.
6277 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6278 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6279 let scorer = ln_test_utils::TestScorer::new();
6280 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6281 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6282 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6284 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6286 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6287 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6288 short_channel_id: 2,
6291 cltv_expiry_delta: 0,
6292 htlc_minimum_msat: 0,
6293 htlc_maximum_msat: 85_000,
6295 fee_proportional_millionths: 0,
6296 excess_data: Vec::new()
6299 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6300 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6301 short_channel_id: 12,
6304 cltv_expiry_delta: (4 << 4) | 1,
6305 htlc_minimum_msat: 0,
6306 htlc_maximum_msat: 270_000,
6308 fee_proportional_millionths: 1000000,
6309 excess_data: Vec::new()
6313 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6314 // 200% fee charged channel 13 in the 1-to-2 direction.
6315 let mut route_params = RouteParameters::from_payment_params_and_value(
6316 payment_params, 90_000);
6317 route_params.max_total_routing_fee_msat = Some(90_000*2);
6318 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6319 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6320 assert_eq!(route.paths.len(), 1);
6321 assert_eq!(route.paths[0].hops.len(), 2);
6323 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6324 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6325 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6326 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6327 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6328 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6330 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6331 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6332 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6333 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6334 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6335 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6340 fn htlc_max_reduction_below_min() {
6341 // Test that if, while walking the graph, we reduce the value being sent to meet an
6342 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6343 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6344 // resulting in us thinking there is no possible path, even if other paths exist.
6345 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6346 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6347 let scorer = ln_test_utils::TestScorer::new();
6348 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6349 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6350 let config = UserConfig::default();
6351 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6352 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6355 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6356 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6357 // then try to send 90_000.
6358 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6359 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6360 short_channel_id: 2,
6363 cltv_expiry_delta: 0,
6364 htlc_minimum_msat: 0,
6365 htlc_maximum_msat: 80_000,
6367 fee_proportional_millionths: 0,
6368 excess_data: Vec::new()
6370 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6371 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6372 short_channel_id: 4,
6375 cltv_expiry_delta: (4 << 4) | 1,
6376 htlc_minimum_msat: 90_000,
6377 htlc_maximum_msat: MAX_VALUE_MSAT,
6379 fee_proportional_millionths: 0,
6380 excess_data: Vec::new()
6384 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6385 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6386 // expensive) channels 12-13 path.
6387 let mut route_params = RouteParameters::from_payment_params_and_value(
6388 payment_params, 90_000);
6389 route_params.max_total_routing_fee_msat = Some(90_000*2);
6390 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6391 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6392 assert_eq!(route.paths.len(), 1);
6393 assert_eq!(route.paths[0].hops.len(), 2);
6395 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6396 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6397 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6398 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6399 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6400 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6402 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6403 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6404 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6405 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6406 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6407 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6412 fn multiple_direct_first_hops() {
6413 // Previously we'd only ever considered one first hop path per counterparty.
6414 // However, as we don't restrict users to one channel per peer, we really need to support
6415 // looking at all first hop paths.
6416 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6417 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6418 // route over multiple channels with the same first hop.
6419 let secp_ctx = Secp256k1::new();
6420 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6421 let logger = Arc::new(ln_test_utils::TestLogger::new());
6422 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6423 let scorer = ln_test_utils::TestScorer::new();
6424 let config = UserConfig::default();
6425 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6426 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6428 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6429 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6432 let route_params = RouteParameters::from_payment_params_and_value(
6433 payment_params.clone(), 100_000);
6434 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6435 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6436 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6437 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6438 assert_eq!(route.paths.len(), 1);
6439 assert_eq!(route.paths[0].hops.len(), 1);
6441 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6442 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6443 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6446 let route_params = RouteParameters::from_payment_params_and_value(
6447 payment_params.clone(), 100_000);
6448 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6449 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6450 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6451 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6452 assert_eq!(route.paths.len(), 2);
6453 assert_eq!(route.paths[0].hops.len(), 1);
6454 assert_eq!(route.paths[1].hops.len(), 1);
6456 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6457 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6459 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6460 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6462 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6463 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6467 // If we have a bunch of outbound channels to the same node, where most are not
6468 // sufficient to pay the full payment, but one is, we should default to just using the
6469 // one single channel that has sufficient balance, avoiding MPP.
6471 // If we have several options above the 3xpayment value threshold, we should pick the
6472 // smallest of them, avoiding further fragmenting our available outbound balance to
6474 let route_params = RouteParameters::from_payment_params_and_value(
6475 payment_params, 100_000);
6476 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6477 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6478 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6479 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6480 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6481 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6482 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6483 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6484 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6485 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6486 assert_eq!(route.paths.len(), 1);
6487 assert_eq!(route.paths[0].hops.len(), 1);
6489 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6490 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6491 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6496 fn prefers_shorter_route_with_higher_fees() {
6497 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6498 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6499 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6501 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6502 let scorer = ln_test_utils::TestScorer::new();
6503 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6504 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6505 let route_params = RouteParameters::from_payment_params_and_value(
6506 payment_params.clone(), 100);
6507 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6508 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6509 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6511 assert_eq!(route.get_total_fees(), 100);
6512 assert_eq!(route.get_total_amount(), 100);
6513 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6515 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6516 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6517 let scorer = FixedPenaltyScorer::with_penalty(100);
6518 let route_params = RouteParameters::from_payment_params_and_value(
6519 payment_params, 100);
6520 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6521 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6522 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6524 assert_eq!(route.get_total_fees(), 300);
6525 assert_eq!(route.get_total_amount(), 100);
6526 assert_eq!(path, vec![2, 4, 7, 10]);
6529 struct BadChannelScorer {
6530 short_channel_id: u64,
6534 impl Writeable for BadChannelScorer {
6535 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6537 impl ScoreLookUp for BadChannelScorer {
6538 type ScoreParams = ();
6539 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6540 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6544 struct BadNodeScorer {
6549 impl Writeable for BadNodeScorer {
6550 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6553 impl ScoreLookUp for BadNodeScorer {
6554 type ScoreParams = ();
6555 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6556 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6561 fn avoids_routing_through_bad_channels_and_nodes() {
6562 let (secp_ctx, network, _, _, logger) = build_graph();
6563 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6564 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6565 let network_graph = network.read_only();
6567 // A path to nodes[6] exists when no penalties are applied to any channel.
6568 let scorer = ln_test_utils::TestScorer::new();
6569 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6570 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6571 let route_params = RouteParameters::from_payment_params_and_value(
6572 payment_params, 100);
6573 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6574 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6575 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6577 assert_eq!(route.get_total_fees(), 100);
6578 assert_eq!(route.get_total_amount(), 100);
6579 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6581 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6582 let scorer = BadChannelScorer { short_channel_id: 6 };
6583 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6584 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6585 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6587 assert_eq!(route.get_total_fees(), 300);
6588 assert_eq!(route.get_total_amount(), 100);
6589 assert_eq!(path, vec![2, 4, 7, 10]);
6591 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6592 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6593 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6594 &scorer, &Default::default(), &random_seed_bytes) {
6595 Err(LightningError { err, .. } ) => {
6596 assert_eq!(err, "Failed to find a path to the given destination");
6598 Ok(_) => panic!("Expected error"),
6603 fn total_fees_single_path() {
6605 paths: vec![Path { hops: vec![
6607 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6608 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6609 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6612 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6613 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6614 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6617 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6618 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6619 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6621 ], blinded_tail: None }],
6625 assert_eq!(route.get_total_fees(), 250);
6626 assert_eq!(route.get_total_amount(), 225);
6630 fn total_fees_multi_path() {
6632 paths: vec![Path { hops: vec![
6634 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6635 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6636 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6639 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6640 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6641 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6643 ], blinded_tail: None }, Path { hops: vec![
6645 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6646 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6647 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6650 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6651 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6652 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6654 ], blinded_tail: None }],
6658 assert_eq!(route.get_total_fees(), 200);
6659 assert_eq!(route.get_total_amount(), 300);
6663 fn total_empty_route_no_panic() {
6664 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6665 // would both panic if the route was completely empty. We test to ensure they return 0
6666 // here, even though its somewhat nonsensical as a route.
6667 let route = Route { paths: Vec::new(), route_params: None };
6669 assert_eq!(route.get_total_fees(), 0);
6670 assert_eq!(route.get_total_amount(), 0);
6674 fn limits_total_cltv_delta() {
6675 let (secp_ctx, network, _, _, logger) = build_graph();
6676 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6677 let network_graph = network.read_only();
6679 let scorer = ln_test_utils::TestScorer::new();
6681 // Make sure that generally there is at least one route available
6682 let feasible_max_total_cltv_delta = 1008;
6683 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6684 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6685 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6686 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6687 let route_params = RouteParameters::from_payment_params_and_value(
6688 feasible_payment_params, 100);
6689 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6690 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6691 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6692 assert_ne!(path.len(), 0);
6694 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6695 let fail_max_total_cltv_delta = 23;
6696 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6697 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6698 let route_params = RouteParameters::from_payment_params_and_value(
6699 fail_payment_params, 100);
6700 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6701 &Default::default(), &random_seed_bytes)
6703 Err(LightningError { err, .. } ) => {
6704 assert_eq!(err, "Failed to find a path to the given destination");
6706 Ok(_) => panic!("Expected error"),
6711 fn avoids_recently_failed_paths() {
6712 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6713 // randomly inserting channels into it until we can't find a route anymore.
6714 let (secp_ctx, network, _, _, logger) = build_graph();
6715 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6716 let network_graph = network.read_only();
6718 let scorer = ln_test_utils::TestScorer::new();
6719 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6720 .with_max_path_count(1);
6721 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6722 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6724 // We should be able to find a route initially, and then after we fail a few random
6725 // channels eventually we won't be able to any longer.
6726 let route_params = RouteParameters::from_payment_params_and_value(
6727 payment_params.clone(), 100);
6728 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6729 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6731 let route_params = RouteParameters::from_payment_params_and_value(
6732 payment_params.clone(), 100);
6733 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6734 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6736 for chan in route.paths[0].hops.iter() {
6737 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6739 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6740 % route.paths[0].hops.len();
6741 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6747 fn limits_path_length() {
6748 let (secp_ctx, network, _, _, logger) = build_line_graph();
6749 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6750 let network_graph = network.read_only();
6752 let scorer = ln_test_utils::TestScorer::new();
6753 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6754 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6756 // First check we can actually create a long route on this graph.
6757 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6758 let route_params = RouteParameters::from_payment_params_and_value(
6759 feasible_payment_params, 100);
6760 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6761 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6762 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6763 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6765 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6766 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6767 let route_params = RouteParameters::from_payment_params_and_value(
6768 fail_payment_params, 100);
6769 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6770 &Default::default(), &random_seed_bytes)
6772 Err(LightningError { err, .. } ) => {
6773 assert_eq!(err, "Failed to find a path to the given destination");
6775 Ok(_) => panic!("Expected error"),
6780 fn adds_and_limits_cltv_offset() {
6781 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6782 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6784 let scorer = ln_test_utils::TestScorer::new();
6786 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6787 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6788 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6789 let route_params = RouteParameters::from_payment_params_and_value(
6790 payment_params.clone(), 100);
6791 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6792 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6793 assert_eq!(route.paths.len(), 1);
6795 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6797 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6798 let mut route_default = route.clone();
6799 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6800 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6801 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6802 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6803 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6805 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6806 let mut route_limited = route.clone();
6807 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6808 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6809 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6810 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6811 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6815 fn adds_plausible_cltv_offset() {
6816 let (secp_ctx, network, _, _, logger) = build_graph();
6817 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6818 let network_graph = network.read_only();
6819 let network_nodes = network_graph.nodes();
6820 let network_channels = network_graph.channels();
6821 let scorer = ln_test_utils::TestScorer::new();
6822 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6823 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6824 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6826 let route_params = RouteParameters::from_payment_params_and_value(
6827 payment_params.clone(), 100);
6828 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6829 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6830 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6832 let mut path_plausibility = vec![];
6834 for p in route.paths {
6835 // 1. Select random observation point
6836 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6837 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6839 prng.process_in_place(&mut random_bytes);
6840 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6841 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6843 // 2. Calculate what CLTV expiry delta we would observe there
6844 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6846 // 3. Starting from the observation point, find candidate paths
6847 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6848 candidates.push_back((observation_point, vec![]));
6850 let mut found_plausible_candidate = false;
6852 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6853 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6854 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6855 found_plausible_candidate = true;
6856 break 'candidate_loop;
6860 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6861 for channel_id in &cur_node.channels {
6862 if let Some(channel_info) = network_channels.get(&channel_id) {
6863 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6864 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6865 if cur_path_cltv_deltas.iter().sum::<u32>()
6866 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6867 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6868 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6869 candidates.push_back((*next_id, new_path_cltv_deltas));
6877 path_plausibility.push(found_plausible_candidate);
6879 assert!(path_plausibility.iter().all(|x| *x));
6883 fn builds_correct_path_from_hops() {
6884 let (secp_ctx, network, _, _, logger) = build_graph();
6885 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6886 let network_graph = network.read_only();
6888 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6889 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6891 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6892 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6893 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6894 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6895 Arc::clone(&logger), &random_seed_bytes).unwrap();
6896 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6897 assert_eq!(hops.len(), route.paths[0].hops.len());
6898 for (idx, hop_pubkey) in hops.iter().enumerate() {
6899 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6904 fn avoids_saturating_channels() {
6905 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6906 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6907 let decay_params = ProbabilisticScoringDecayParameters::default();
6908 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6910 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6911 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6912 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6913 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6914 short_channel_id: 4,
6917 cltv_expiry_delta: (4 << 4) | 1,
6918 htlc_minimum_msat: 0,
6919 htlc_maximum_msat: 250_000_000,
6921 fee_proportional_millionths: 0,
6922 excess_data: Vec::new()
6924 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6925 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6926 short_channel_id: 13,
6929 cltv_expiry_delta: (13 << 4) | 1,
6930 htlc_minimum_msat: 0,
6931 htlc_maximum_msat: 250_000_000,
6933 fee_proportional_millionths: 0,
6934 excess_data: Vec::new()
6937 let config = UserConfig::default();
6938 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6939 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6941 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6942 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6943 // 100,000 sats is less than the available liquidity on each channel, set above.
6944 let route_params = RouteParameters::from_payment_params_and_value(
6945 payment_params, 100_000_000);
6946 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6947 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6948 assert_eq!(route.paths.len(), 2);
6949 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6950 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6953 #[cfg(not(feature = "no-std"))]
6954 pub(super) fn random_init_seed() -> u64 {
6955 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6956 use core::hash::{BuildHasher, Hasher};
6957 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6958 println!("Using seed of {}", seed);
6963 #[cfg(not(feature = "no-std"))]
6964 fn generate_routes() {
6965 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6967 let logger = ln_test_utils::TestLogger::new();
6968 let graph = match super::bench_utils::read_network_graph(&logger) {
6976 let params = ProbabilisticScoringFeeParameters::default();
6977 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6978 let features = super::Bolt11InvoiceFeatures::empty();
6980 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6984 #[cfg(not(feature = "no-std"))]
6985 fn generate_routes_mpp() {
6986 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6988 let logger = ln_test_utils::TestLogger::new();
6989 let graph = match super::bench_utils::read_network_graph(&logger) {
6997 let params = ProbabilisticScoringFeeParameters::default();
6998 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6999 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7001 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7005 #[cfg(not(feature = "no-std"))]
7006 fn generate_large_mpp_routes() {
7007 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
7009 let logger = ln_test_utils::TestLogger::new();
7010 let graph = match super::bench_utils::read_network_graph(&logger) {
7018 let params = ProbabilisticScoringFeeParameters::default();
7019 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
7020 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7022 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
7026 fn honors_manual_penalties() {
7027 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
7028 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7030 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7031 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7033 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
7034 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
7036 // First check set manual penalties are returned by the scorer.
7037 let usage = ChannelUsage {
7039 inflight_htlc_msat: 0,
7040 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
7042 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
7043 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
7044 let network_graph = network_graph.read_only();
7045 let channels = network_graph.channels();
7046 let channel = channels.get(&5).unwrap();
7047 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
7048 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop(PublicHopCandidate {
7050 short_channel_id: 5,
7052 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
7054 // Then check we can get a normal route
7055 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
7056 let route_params = RouteParameters::from_payment_params_and_value(
7057 payment_params, 100);
7058 let route = get_route(&our_id, &route_params, &network_graph, None,
7059 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
7060 assert!(route.is_ok());
7062 // Then check that we can't get a route if we ban an intermediate node.
7063 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
7064 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7065 assert!(route.is_err());
7067 // Finally make sure we can route again, when we remove the ban.
7068 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
7069 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7070 assert!(route.is_ok());
7074 fn abide_by_route_hint_max_htlc() {
7075 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
7076 // params in the final route.
7077 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7078 let netgraph = network_graph.read_only();
7079 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7080 let scorer = ln_test_utils::TestScorer::new();
7081 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7082 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7083 let config = UserConfig::default();
7085 let max_htlc_msat = 50_000;
7086 let route_hint_1 = RouteHint(vec![RouteHintHop {
7087 src_node_id: nodes[2],
7088 short_channel_id: 42,
7091 proportional_millionths: 0,
7093 cltv_expiry_delta: 10,
7094 htlc_minimum_msat: None,
7095 htlc_maximum_msat: Some(max_htlc_msat),
7097 let dest_node_id = ln_test_utils::pubkey(42);
7098 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7099 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
7100 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7103 // Make sure we'll error if our route hints don't have enough liquidity according to their
7104 // htlc_maximum_msat.
7105 let mut route_params = RouteParameters::from_payment_params_and_value(
7106 payment_params, max_htlc_msat + 1);
7107 route_params.max_total_routing_fee_msat = None;
7108 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
7109 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
7112 assert_eq!(err, "Failed to find a sufficient route to the given destination");
7113 } else { panic!(); }
7115 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
7116 let mut route_hint_2 = route_hint_1.clone();
7117 route_hint_2.0[0].short_channel_id = 43;
7118 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7119 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7120 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7122 let mut route_params = RouteParameters::from_payment_params_and_value(
7123 payment_params, max_htlc_msat + 1);
7124 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
7125 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
7126 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7127 assert_eq!(route.paths.len(), 2);
7128 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7129 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7133 fn direct_channel_to_hints_with_max_htlc() {
7134 // Check that if we have a first hop channel peer that's connected to multiple provided route
7135 // hints, that we properly split the payment between the route hints if needed.
7136 let logger = Arc::new(ln_test_utils::TestLogger::new());
7137 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7138 let scorer = ln_test_utils::TestScorer::new();
7139 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7140 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7141 let config = UserConfig::default();
7143 let our_node_id = ln_test_utils::pubkey(42);
7144 let intermed_node_id = ln_test_utils::pubkey(43);
7145 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7147 let amt_msat = 900_000;
7148 let max_htlc_msat = 500_000;
7149 let route_hint_1 = RouteHint(vec![RouteHintHop {
7150 src_node_id: intermed_node_id,
7151 short_channel_id: 44,
7154 proportional_millionths: 0,
7156 cltv_expiry_delta: 10,
7157 htlc_minimum_msat: None,
7158 htlc_maximum_msat: Some(max_htlc_msat),
7160 src_node_id: intermed_node_id,
7161 short_channel_id: 45,
7164 proportional_millionths: 0,
7166 cltv_expiry_delta: 10,
7167 htlc_minimum_msat: None,
7168 // Check that later route hint max htlcs don't override earlier ones
7169 htlc_maximum_msat: Some(max_htlc_msat - 50),
7171 let mut route_hint_2 = route_hint_1.clone();
7172 route_hint_2.0[0].short_channel_id = 46;
7173 route_hint_2.0[1].short_channel_id = 47;
7174 let dest_node_id = ln_test_utils::pubkey(44);
7175 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7176 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7177 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7180 let route_params = RouteParameters::from_payment_params_and_value(
7181 payment_params, amt_msat);
7182 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7183 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7184 &Default::default(), &random_seed_bytes).unwrap();
7185 assert_eq!(route.paths.len(), 2);
7186 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7187 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7188 assert_eq!(route.get_total_amount(), amt_msat);
7190 // Re-run but with two first hop channels connected to the same route hint peers that must be
7192 let first_hops = vec![
7193 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7194 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7196 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7197 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7198 &Default::default(), &random_seed_bytes).unwrap();
7199 assert_eq!(route.paths.len(), 2);
7200 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7201 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7202 assert_eq!(route.get_total_amount(), amt_msat);
7204 // Make sure this works for blinded route hints.
7205 let blinded_path = BlindedPath {
7206 introduction_node_id: intermed_node_id,
7207 blinding_point: ln_test_utils::pubkey(42),
7209 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
7210 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
7213 let blinded_payinfo = BlindedPayInfo {
7215 fee_proportional_millionths: 0,
7216 htlc_minimum_msat: 1,
7217 htlc_maximum_msat: max_htlc_msat,
7218 cltv_expiry_delta: 10,
7219 features: BlindedHopFeatures::empty(),
7221 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7222 let payment_params = PaymentParameters::blinded(vec![
7223 (blinded_payinfo.clone(), blinded_path.clone()),
7224 (blinded_payinfo.clone(), blinded_path.clone())])
7225 .with_bolt12_features(bolt12_features).unwrap();
7226 let route_params = RouteParameters::from_payment_params_and_value(
7227 payment_params, amt_msat);
7228 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7229 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7230 &Default::default(), &random_seed_bytes).unwrap();
7231 assert_eq!(route.paths.len(), 2);
7232 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7233 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7234 assert_eq!(route.get_total_amount(), amt_msat);
7238 fn blinded_route_ser() {
7239 let blinded_path_1 = BlindedPath {
7240 introduction_node_id: ln_test_utils::pubkey(42),
7241 blinding_point: ln_test_utils::pubkey(43),
7243 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7244 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7247 let blinded_path_2 = BlindedPath {
7248 introduction_node_id: ln_test_utils::pubkey(46),
7249 blinding_point: ln_test_utils::pubkey(47),
7251 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7252 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7255 // (De)serialize a Route with 1 blinded path out of two total paths.
7256 let mut route = Route { paths: vec![Path {
7257 hops: vec![RouteHop {
7258 pubkey: ln_test_utils::pubkey(50),
7259 node_features: NodeFeatures::empty(),
7260 short_channel_id: 42,
7261 channel_features: ChannelFeatures::empty(),
7263 cltv_expiry_delta: 0,
7264 maybe_announced_channel: true,
7266 blinded_tail: Some(BlindedTail {
7267 hops: blinded_path_1.blinded_hops,
7268 blinding_point: blinded_path_1.blinding_point,
7269 excess_final_cltv_expiry_delta: 40,
7270 final_value_msat: 100,
7272 hops: vec![RouteHop {
7273 pubkey: ln_test_utils::pubkey(51),
7274 node_features: NodeFeatures::empty(),
7275 short_channel_id: 43,
7276 channel_features: ChannelFeatures::empty(),
7278 cltv_expiry_delta: 0,
7279 maybe_announced_channel: true,
7280 }], blinded_tail: None }],
7283 let encoded_route = route.encode();
7284 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7285 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7286 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7288 // (De)serialize a Route with two paths, each containing a blinded tail.
7289 route.paths[1].blinded_tail = Some(BlindedTail {
7290 hops: blinded_path_2.blinded_hops,
7291 blinding_point: blinded_path_2.blinding_point,
7292 excess_final_cltv_expiry_delta: 41,
7293 final_value_msat: 101,
7295 let encoded_route = route.encode();
7296 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7297 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7298 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7302 fn blinded_path_inflight_processing() {
7303 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7304 // account for the blinded tail's final amount_msat.
7305 let mut inflight_htlcs = InFlightHtlcs::new();
7306 let blinded_path = BlindedPath {
7307 introduction_node_id: ln_test_utils::pubkey(43),
7308 blinding_point: ln_test_utils::pubkey(48),
7309 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7312 hops: vec![RouteHop {
7313 pubkey: ln_test_utils::pubkey(42),
7314 node_features: NodeFeatures::empty(),
7315 short_channel_id: 42,
7316 channel_features: ChannelFeatures::empty(),
7318 cltv_expiry_delta: 0,
7319 maybe_announced_channel: false,
7322 pubkey: blinded_path.introduction_node_id,
7323 node_features: NodeFeatures::empty(),
7324 short_channel_id: 43,
7325 channel_features: ChannelFeatures::empty(),
7327 cltv_expiry_delta: 0,
7328 maybe_announced_channel: false,
7330 blinded_tail: Some(BlindedTail {
7331 hops: blinded_path.blinded_hops,
7332 blinding_point: blinded_path.blinding_point,
7333 excess_final_cltv_expiry_delta: 0,
7334 final_value_msat: 200,
7337 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7338 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7339 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7343 fn blinded_path_cltv_shadow_offset() {
7344 // Make sure we add a shadow offset when sending to blinded paths.
7345 let blinded_path = BlindedPath {
7346 introduction_node_id: ln_test_utils::pubkey(43),
7347 blinding_point: ln_test_utils::pubkey(44),
7349 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7350 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7353 let mut route = Route { paths: vec![Path {
7354 hops: vec![RouteHop {
7355 pubkey: ln_test_utils::pubkey(42),
7356 node_features: NodeFeatures::empty(),
7357 short_channel_id: 42,
7358 channel_features: ChannelFeatures::empty(),
7360 cltv_expiry_delta: 0,
7361 maybe_announced_channel: false,
7364 pubkey: blinded_path.introduction_node_id,
7365 node_features: NodeFeatures::empty(),
7366 short_channel_id: 43,
7367 channel_features: ChannelFeatures::empty(),
7369 cltv_expiry_delta: 0,
7370 maybe_announced_channel: false,
7373 blinded_tail: Some(BlindedTail {
7374 hops: blinded_path.blinded_hops,
7375 blinding_point: blinded_path.blinding_point,
7376 excess_final_cltv_expiry_delta: 0,
7377 final_value_msat: 200,
7379 }], route_params: None};
7381 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7382 let (_, network_graph, _, _, _) = build_line_graph();
7383 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7384 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7385 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7389 fn simple_blinded_route_hints() {
7390 do_simple_blinded_route_hints(1);
7391 do_simple_blinded_route_hints(2);
7392 do_simple_blinded_route_hints(3);
7395 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7396 // Check that we can generate a route to a blinded path with the expected hops.
7397 let (secp_ctx, network, _, _, logger) = build_graph();
7398 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7399 let network_graph = network.read_only();
7401 let scorer = ln_test_utils::TestScorer::new();
7402 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7403 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7405 let mut blinded_path = BlindedPath {
7406 introduction_node_id: nodes[2],
7407 blinding_point: ln_test_utils::pubkey(42),
7408 blinded_hops: Vec::with_capacity(num_blinded_hops),
7410 for i in 0..num_blinded_hops {
7411 blinded_path.blinded_hops.push(
7412 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7415 let blinded_payinfo = BlindedPayInfo {
7417 fee_proportional_millionths: 500,
7418 htlc_minimum_msat: 1000,
7419 htlc_maximum_msat: 100_000_000,
7420 cltv_expiry_delta: 15,
7421 features: BlindedHopFeatures::empty(),
7424 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7425 let route_params = RouteParameters::from_payment_params_and_value(
7426 payment_params, 1001);
7427 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7428 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7429 assert_eq!(route.paths.len(), 1);
7430 assert_eq!(route.paths[0].hops.len(), 2);
7432 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7433 assert_eq!(tail.hops, blinded_path.blinded_hops);
7434 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7435 assert_eq!(tail.final_value_msat, 1001);
7437 let final_hop = route.paths[0].hops.last().unwrap();
7438 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
7439 if tail.hops.len() > 1 {
7440 assert_eq!(final_hop.fee_msat,
7441 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7442 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7444 assert_eq!(final_hop.fee_msat, 0);
7445 assert_eq!(final_hop.cltv_expiry_delta, 0);
7450 fn blinded_path_routing_errors() {
7451 // Check that we can generate a route to a blinded path with the expected hops.
7452 let (secp_ctx, network, _, _, logger) = build_graph();
7453 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7454 let network_graph = network.read_only();
7456 let scorer = ln_test_utils::TestScorer::new();
7457 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7458 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7460 let mut invalid_blinded_path = BlindedPath {
7461 introduction_node_id: nodes[2],
7462 blinding_point: ln_test_utils::pubkey(42),
7464 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7467 let blinded_payinfo = BlindedPayInfo {
7469 fee_proportional_millionths: 500,
7470 htlc_minimum_msat: 1000,
7471 htlc_maximum_msat: 100_000_000,
7472 cltv_expiry_delta: 15,
7473 features: BlindedHopFeatures::empty(),
7476 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7477 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
7478 let payment_params = PaymentParameters::blinded(vec![
7479 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7480 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7481 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7482 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7483 &scorer, &Default::default(), &random_seed_bytes)
7485 Err(LightningError { err, .. }) => {
7486 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7488 _ => panic!("Expected error")
7491 invalid_blinded_path.introduction_node_id = our_id;
7492 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7493 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7494 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7495 &Default::default(), &random_seed_bytes)
7497 Err(LightningError { err, .. }) => {
7498 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7500 _ => panic!("Expected error")
7503 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
7504 invalid_blinded_path.blinded_hops.clear();
7505 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7506 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7507 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7508 &Default::default(), &random_seed_bytes)
7510 Err(LightningError { err, .. }) => {
7511 assert_eq!(err, "0-hop blinded path provided");
7513 _ => panic!("Expected error")
7518 fn matching_intro_node_paths_provided() {
7519 // Check that if multiple blinded paths with the same intro node are provided in payment
7520 // parameters, we'll return the correct paths in the resulting MPP route.
7521 let (secp_ctx, network, _, _, logger) = build_graph();
7522 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7523 let network_graph = network.read_only();
7525 let scorer = ln_test_utils::TestScorer::new();
7526 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7527 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7528 let config = UserConfig::default();
7530 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7531 let blinded_path_1 = BlindedPath {
7532 introduction_node_id: nodes[2],
7533 blinding_point: ln_test_utils::pubkey(42),
7535 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7536 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7539 let blinded_payinfo_1 = BlindedPayInfo {
7541 fee_proportional_millionths: 0,
7542 htlc_minimum_msat: 0,
7543 htlc_maximum_msat: 30_000,
7544 cltv_expiry_delta: 0,
7545 features: BlindedHopFeatures::empty(),
7548 let mut blinded_path_2 = blinded_path_1.clone();
7549 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7550 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7551 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7553 let blinded_hints = vec![
7554 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7555 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7557 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7558 .with_bolt12_features(bolt12_features).unwrap();
7560 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7561 route_params.max_total_routing_fee_msat = Some(100_000);
7562 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7563 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7564 assert_eq!(route.paths.len(), 2);
7565 let mut total_amount_paid_msat = 0;
7566 for path in route.paths.into_iter() {
7567 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7568 if let Some(bt) = &path.blinded_tail {
7569 assert_eq!(bt.blinding_point,
7570 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7571 .map(|(_, bp)| bp.blinding_point).unwrap());
7572 } else { panic!(); }
7573 total_amount_paid_msat += path.final_value_msat();
7575 assert_eq!(total_amount_paid_msat, 100_000);
7579 fn direct_to_intro_node() {
7580 // This previously caused a debug panic in the router when asserting
7581 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7582 // direct channels we failed to account for the fee charged for use of the blinded path.
7585 // node0 -1(1)2 - node1
7586 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7587 // doesn't account for the blinded path fee.
7589 let secp_ctx = Secp256k1::new();
7590 let logger = Arc::new(ln_test_utils::TestLogger::new());
7591 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7592 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
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();
7597 let amt_msat = 10_000_000;
7598 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7599 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7600 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7601 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7602 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7603 short_channel_id: 1,
7606 cltv_expiry_delta: 42,
7607 htlc_minimum_msat: 1_000,
7608 htlc_maximum_msat: 10_000_000,
7610 fee_proportional_millionths: 0,
7611 excess_data: Vec::new()
7613 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7614 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7615 short_channel_id: 1,
7618 cltv_expiry_delta: 42,
7619 htlc_minimum_msat: 1_000,
7620 htlc_maximum_msat: 10_000_000,
7622 fee_proportional_millionths: 0,
7623 excess_data: Vec::new()
7625 let first_hops = vec![
7626 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7628 let blinded_path = BlindedPath {
7629 introduction_node_id: nodes[1],
7630 blinding_point: ln_test_utils::pubkey(42),
7632 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7633 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7636 let blinded_payinfo = BlindedPayInfo {
7637 fee_base_msat: 1000,
7638 fee_proportional_millionths: 0,
7639 htlc_minimum_msat: 1000,
7640 htlc_maximum_msat: MAX_VALUE_MSAT,
7641 cltv_expiry_delta: 0,
7642 features: BlindedHopFeatures::empty(),
7644 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7646 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7648 let netgraph = network_graph.read_only();
7649 let route_params = RouteParameters::from_payment_params_and_value(
7650 payment_params.clone(), amt_msat);
7651 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7652 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7653 &Default::default(), &random_seed_bytes) {
7654 assert_eq!(err, "Failed to find a path to the given destination");
7655 } else { panic!("Expected error") }
7657 // Sending an exact amount accounting for the blinded path fee works.
7658 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7659 let route_params = RouteParameters::from_payment_params_and_value(
7660 payment_params, amt_minus_blinded_path_fee);
7661 let route = get_route(&nodes[0], &route_params, &netgraph,
7662 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7663 &Default::default(), &random_seed_bytes).unwrap();
7664 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7665 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7669 fn direct_to_matching_intro_nodes() {
7670 // This previously caused us to enter `unreachable` code in the following situation:
7671 // 1. We add a route candidate for intro_node contributing a high amount
7672 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7673 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7674 // amount, and update our route candidate for intro_node for the lower amount
7675 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7676 // lower contribution amount, but fail (this was previously caused by failure to account for
7677 // blinded path fees when adding first_hop<>intro_node candidates)
7678 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7679 // candidate still thinks its path is contributing the original higher amount. This caused us
7680 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7682 let secp_ctx = Secp256k1::new();
7683 let logger = Arc::new(ln_test_utils::TestLogger::new());
7684 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7685 let scorer = ln_test_utils::TestScorer::new();
7686 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7687 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7688 let config = UserConfig::default();
7690 // Values are taken from the fuzz input that uncovered this panic.
7691 let amt_msat = 21_7020_5185_1403_2640;
7692 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7693 let first_hops = vec![
7694 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7695 18446744073709551615)];
7697 let blinded_path = BlindedPath {
7698 introduction_node_id: nodes[1],
7699 blinding_point: ln_test_utils::pubkey(42),
7701 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7702 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7705 let blinded_payinfo = BlindedPayInfo {
7706 fee_base_msat: 5046_2720,
7707 fee_proportional_millionths: 0,
7708 htlc_minimum_msat: 4503_5996_2737_0496,
7709 htlc_maximum_msat: 45_0359_9627_3704_9600,
7710 cltv_expiry_delta: 0,
7711 features: BlindedHopFeatures::empty(),
7713 let mut blinded_hints = vec![
7714 (blinded_payinfo.clone(), blinded_path.clone()),
7715 (blinded_payinfo.clone(), blinded_path.clone()),
7717 blinded_hints[1].0.fee_base_msat = 419_4304;
7718 blinded_hints[1].0.fee_proportional_millionths = 257;
7719 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7720 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7721 blinded_hints[1].0.cltv_expiry_delta = 0;
7723 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7724 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7725 .with_bolt12_features(bolt12_features).unwrap();
7727 let netgraph = network_graph.read_only();
7728 let route_params = RouteParameters::from_payment_params_and_value(
7729 payment_params, amt_msat);
7730 let route = get_route(&nodes[0], &route_params, &netgraph,
7731 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7732 &Default::default(), &random_seed_bytes).unwrap();
7733 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7734 assert_eq!(route.get_total_amount(), amt_msat);
7738 fn we_are_intro_node_candidate_hops() {
7739 // This previously led to a panic in the router because we'd generate a Path with only a
7740 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7741 // where the origin node is the intro node. We now fully disallow considering candidate hops
7742 // where the origin node is the intro node.
7743 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7744 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7745 let scorer = ln_test_utils::TestScorer::new();
7746 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7747 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7748 let config = UserConfig::default();
7750 // Values are taken from the fuzz input that uncovered this panic.
7751 let amt_msat = 21_7020_5185_1423_0019;
7753 let blinded_path = BlindedPath {
7754 introduction_node_id: our_id,
7755 blinding_point: ln_test_utils::pubkey(42),
7757 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7758 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7761 let blinded_payinfo = BlindedPayInfo {
7762 fee_base_msat: 5052_9027,
7763 fee_proportional_millionths: 0,
7764 htlc_minimum_msat: 21_7020_5185_1423_0019,
7765 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7766 cltv_expiry_delta: 0,
7767 features: BlindedHopFeatures::empty(),
7769 let mut blinded_hints = vec![
7770 (blinded_payinfo.clone(), blinded_path.clone()),
7771 (blinded_payinfo.clone(), blinded_path.clone()),
7773 blinded_hints[1].1.introduction_node_id = nodes[6];
7775 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7776 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7777 .with_bolt12_features(bolt12_features.clone()).unwrap();
7779 let netgraph = network_graph.read_only();
7780 let route_params = RouteParameters::from_payment_params_and_value(
7781 payment_params, amt_msat);
7782 if let Err(LightningError { err, .. }) = get_route(
7783 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7785 assert_eq!(err, "Failed to find a path to the given destination");
7790 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7791 // This previously led to a debug panic in the router because we'd find an invalid Path with
7792 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7793 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7794 // the payment, when it was intended to only include the final value of the payment.
7795 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7796 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7797 let scorer = ln_test_utils::TestScorer::new();
7798 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7799 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7800 let config = UserConfig::default();
7802 // Values are taken from the fuzz input that uncovered this panic.
7803 let amt_msat = 21_7020_5185_1423_0019;
7805 let blinded_path = BlindedPath {
7806 introduction_node_id: our_id,
7807 blinding_point: ln_test_utils::pubkey(42),
7809 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7810 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7813 let blinded_payinfo = BlindedPayInfo {
7814 fee_base_msat: 10_4425_1395,
7815 fee_proportional_millionths: 0,
7816 htlc_minimum_msat: 21_7301_9934_9094_0931,
7817 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7818 cltv_expiry_delta: 0,
7819 features: BlindedHopFeatures::empty(),
7821 let mut blinded_hints = vec![
7822 (blinded_payinfo.clone(), blinded_path.clone()),
7823 (blinded_payinfo.clone(), blinded_path.clone()),
7824 (blinded_payinfo.clone(), blinded_path.clone()),
7826 blinded_hints[1].0.fee_base_msat = 5052_9027;
7827 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7828 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7830 blinded_hints[2].1.introduction_node_id = nodes[6];
7832 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7833 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7834 .with_bolt12_features(bolt12_features.clone()).unwrap();
7836 let netgraph = network_graph.read_only();
7837 let route_params = RouteParameters::from_payment_params_and_value(
7838 payment_params, amt_msat);
7839 if let Err(LightningError { err, .. }) = get_route(
7840 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7842 assert_eq!(err, "Failed to find a path to the given destination");
7847 fn min_htlc_overpay_violates_max_htlc() {
7848 do_min_htlc_overpay_violates_max_htlc(true);
7849 do_min_htlc_overpay_violates_max_htlc(false);
7851 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7852 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7853 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7854 // to `targets` and build an invalid path with it, and subsequently hit a debug panic asserting
7855 // that the used liquidity for a hop was less than its available liquidity limit.
7856 let secp_ctx = Secp256k1::new();
7857 let logger = Arc::new(ln_test_utils::TestLogger::new());
7858 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7859 let scorer = ln_test_utils::TestScorer::new();
7860 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7861 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7862 let config = UserConfig::default();
7864 // Values are taken from the fuzz input that uncovered this panic.
7865 let amt_msat = 7_4009_8048;
7866 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7867 let first_hop_outbound_capacity = 2_7345_2000;
7868 let first_hops = vec![get_channel_details(
7869 Some(200), nodes[0], channelmanager::provided_init_features(&config),
7870 first_hop_outbound_capacity
7873 let base_fee = 1_6778_3453;
7874 let htlc_min = 2_5165_8240;
7875 let payment_params = if blinded_payee {
7876 let blinded_path = BlindedPath {
7877 introduction_node_id: nodes[0],
7878 blinding_point: ln_test_utils::pubkey(42),
7880 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7881 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7884 let blinded_payinfo = BlindedPayInfo {
7885 fee_base_msat: base_fee,
7886 fee_proportional_millionths: 0,
7887 htlc_minimum_msat: htlc_min,
7888 htlc_maximum_msat: htlc_min * 1000,
7889 cltv_expiry_delta: 0,
7890 features: BlindedHopFeatures::empty(),
7892 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7893 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
7894 .with_bolt12_features(bolt12_features.clone()).unwrap()
7896 let route_hint = RouteHint(vec![RouteHintHop {
7897 src_node_id: nodes[0],
7898 short_channel_id: 42,
7900 base_msat: base_fee,
7901 proportional_millionths: 0,
7903 cltv_expiry_delta: 10,
7904 htlc_minimum_msat: Some(htlc_min),
7905 htlc_maximum_msat: None,
7908 PaymentParameters::from_node_id(nodes[1], 42)
7909 .with_route_hints(vec![route_hint]).unwrap()
7910 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7913 let netgraph = network_graph.read_only();
7914 let route_params = RouteParameters::from_payment_params_and_value(
7915 payment_params, amt_msat);
7916 if let Err(LightningError { err, .. }) = get_route(
7917 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7918 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7920 assert_eq!(err, "Failed to find a path to the given destination");
7925 fn previously_used_liquidity_violates_max_htlc() {
7926 do_previously_used_liquidity_violates_max_htlc(true);
7927 do_previously_used_liquidity_violates_max_htlc(false);
7930 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
7931 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
7932 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
7933 // candidate. In this case, the candidate does not have enough due to a previous path taking up
7934 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
7935 // asserting that the used liquidity for a hop was less than its available liquidity limit.
7936 let secp_ctx = Secp256k1::new();
7937 let logger = Arc::new(ln_test_utils::TestLogger::new());
7938 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7939 let scorer = ln_test_utils::TestScorer::new();
7940 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7941 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7942 let config = UserConfig::default();
7944 // Values are taken from the fuzz input that uncovered this panic.
7945 let amt_msat = 52_4288;
7946 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7947 let first_hops = vec![get_channel_details(
7948 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
7949 ), get_channel_details(
7950 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
7953 let base_fees = [0, 425_9840, 0, 0];
7954 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
7955 let payment_params = if blinded_payee {
7956 let blinded_path = BlindedPath {
7957 introduction_node_id: nodes[0],
7958 blinding_point: ln_test_utils::pubkey(42),
7960 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7961 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7964 let mut blinded_hints = Vec::new();
7965 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
7966 blinded_hints.push((BlindedPayInfo {
7967 fee_base_msat: *base_fee,
7968 fee_proportional_millionths: 0,
7969 htlc_minimum_msat: *htlc_min,
7970 htlc_maximum_msat: htlc_min * 100,
7971 cltv_expiry_delta: 10,
7972 features: BlindedHopFeatures::empty(),
7973 }, blinded_path.clone()));
7975 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7976 PaymentParameters::blinded(blinded_hints.clone())
7977 .with_bolt12_features(bolt12_features.clone()).unwrap()
7979 let mut route_hints = Vec::new();
7980 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
7981 route_hints.push(RouteHint(vec![RouteHintHop {
7982 src_node_id: nodes[0],
7983 short_channel_id: 42 + idx as u64,
7985 base_msat: *base_fee,
7986 proportional_millionths: 0,
7988 cltv_expiry_delta: 10,
7989 htlc_minimum_msat: Some(*htlc_min),
7990 htlc_maximum_msat: Some(htlc_min * 100),
7993 PaymentParameters::from_node_id(nodes[1], 42)
7994 .with_route_hints(route_hints).unwrap()
7995 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7998 let netgraph = network_graph.read_only();
7999 let route_params = RouteParameters::from_payment_params_and_value(
8000 payment_params, amt_msat);
8002 let route = get_route(
8003 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8004 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8006 assert_eq!(route.paths.len(), 1);
8007 assert_eq!(route.get_total_amount(), amt_msat);
8011 fn candidate_path_min() {
8012 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
8013 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
8014 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
8015 // would add a connecting first_hop node that did not have enough contribution amount, leading
8016 // to a debug panic upon invalid path construction.
8017 let secp_ctx = Secp256k1::new();
8018 let logger = Arc::new(ln_test_utils::TestLogger::new());
8019 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8020 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
8021 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8022 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8023 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8024 let config = UserConfig::default();
8026 // Values are taken from the fuzz input that uncovered this panic.
8027 let amt_msat = 7_4009_8048;
8028 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
8029 let first_hops = vec![get_channel_details(
8030 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
8033 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
8034 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8035 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8036 short_channel_id: 6,
8039 cltv_expiry_delta: (6 << 4) | 0,
8040 htlc_minimum_msat: 0,
8041 htlc_maximum_msat: MAX_VALUE_MSAT,
8043 fee_proportional_millionths: 0,
8044 excess_data: Vec::new()
8046 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
8048 let htlc_min = 2_5165_8240;
8049 let blinded_hints = vec![
8051 fee_base_msat: 1_6778_3453,
8052 fee_proportional_millionths: 0,
8053 htlc_minimum_msat: htlc_min,
8054 htlc_maximum_msat: htlc_min * 100,
8055 cltv_expiry_delta: 10,
8056 features: BlindedHopFeatures::empty(),
8058 introduction_node_id: nodes[0],
8059 blinding_point: ln_test_utils::pubkey(42),
8061 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8062 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8066 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8067 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8068 .with_bolt12_features(bolt12_features.clone()).unwrap();
8069 let route_params = RouteParameters::from_payment_params_and_value(
8070 payment_params, amt_msat);
8071 let netgraph = network_graph.read_only();
8073 if let Err(LightningError { err, .. }) = get_route(
8074 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8075 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8078 assert_eq!(err, "Failed to find a path to the given destination");
8083 fn path_contribution_includes_min_htlc_overpay() {
8084 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
8085 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
8086 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
8087 // selection, both tested here.
8088 let secp_ctx = Secp256k1::new();
8089 let logger = Arc::new(ln_test_utils::TestLogger::new());
8090 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8091 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8092 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8093 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8094 let config = UserConfig::default();
8096 // Values are taken from the fuzz input that uncovered this panic.
8097 let amt_msat = 562_0000;
8098 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8099 let first_hops = vec![
8100 get_channel_details(
8101 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
8105 let htlc_mins = [49_0000, 1125_0000];
8106 let payment_params = {
8107 let blinded_path = BlindedPath {
8108 introduction_node_id: nodes[0],
8109 blinding_point: ln_test_utils::pubkey(42),
8111 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8112 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8115 let mut blinded_hints = Vec::new();
8116 for htlc_min in htlc_mins.iter() {
8117 blinded_hints.push((BlindedPayInfo {
8119 fee_proportional_millionths: 0,
8120 htlc_minimum_msat: *htlc_min,
8121 htlc_maximum_msat: *htlc_min * 100,
8122 cltv_expiry_delta: 10,
8123 features: BlindedHopFeatures::empty(),
8124 }, blinded_path.clone()));
8126 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8127 PaymentParameters::blinded(blinded_hints.clone())
8128 .with_bolt12_features(bolt12_features.clone()).unwrap()
8131 let netgraph = network_graph.read_only();
8132 let route_params = RouteParameters::from_payment_params_and_value(
8133 payment_params, amt_msat);
8134 let route = get_route(
8135 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8136 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8139 assert_eq!(route.paths.len(), 1);
8140 assert_eq!(route.get_total_amount(), amt_msat);
8144 fn first_hop_preferred_over_hint() {
8145 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
8146 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
8147 let secp_ctx = Secp256k1::new();
8148 let logger = Arc::new(ln_test_utils::TestLogger::new());
8149 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8150 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
8151 let scorer = ln_test_utils::TestScorer::new();
8152 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8153 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8154 let config = UserConfig::default();
8156 let amt_msat = 1_000_000;
8157 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
8159 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
8160 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
8161 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8162 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8163 short_channel_id: 1,
8166 cltv_expiry_delta: 42,
8167 htlc_minimum_msat: 1_000,
8168 htlc_maximum_msat: 10_000_000,
8170 fee_proportional_millionths: 0,
8171 excess_data: Vec::new()
8173 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8174 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8175 short_channel_id: 1,
8178 cltv_expiry_delta: 42,
8179 htlc_minimum_msat: 1_000,
8180 htlc_maximum_msat: 10_000_000,
8182 fee_proportional_millionths: 0,
8183 excess_data: Vec::new()
8186 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
8187 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
8188 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8189 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8190 short_channel_id: 2,
8193 cltv_expiry_delta: 42,
8194 htlc_minimum_msat: 1_000,
8195 htlc_maximum_msat: 10_000_000,
8197 fee_proportional_millionths: 0,
8198 excess_data: Vec::new()
8200 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8201 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8202 short_channel_id: 2,
8205 cltv_expiry_delta: 42,
8206 htlc_minimum_msat: 1_000,
8207 htlc_maximum_msat: 10_000_000,
8209 fee_proportional_millionths: 0,
8210 excess_data: Vec::new()
8213 let dest_node_id = nodes[2];
8215 let route_hint = RouteHint(vec![RouteHintHop {
8216 src_node_id: our_node_id,
8217 short_channel_id: 44,
8220 proportional_millionths: 0,
8222 cltv_expiry_delta: 10,
8223 htlc_minimum_msat: None,
8224 htlc_maximum_msat: Some(5_000_000),
8227 src_node_id: nodes[0],
8228 short_channel_id: 45,
8231 proportional_millionths: 0,
8233 cltv_expiry_delta: 10,
8234 htlc_minimum_msat: None,
8235 htlc_maximum_msat: None,
8238 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8239 .with_route_hints(vec![route_hint]).unwrap()
8240 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8241 let route_params = RouteParameters::from_payment_params_and_value(
8242 payment_params, amt_msat);
8244 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8246 let first_hop = get_channel_details(Some(1), nodes[0],
8247 channelmanager::provided_init_features(&config), 999_999);
8248 let first_hops = vec![first_hop];
8250 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8251 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8252 &Default::default(), &random_seed_bytes).unwrap();
8253 assert_eq!(route.paths.len(), 1);
8254 assert_eq!(route.get_total_amount(), amt_msat);
8255 assert_eq!(route.paths[0].hops.len(), 2);
8256 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8257 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8258 assert_eq!(route.get_total_fees(), 123);
8260 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8261 // for a first hop channel.
8262 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8263 first_hop.outbound_scid_alias = Some(44);
8264 let first_hops = vec![first_hop];
8266 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8267 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8268 &Default::default(), &random_seed_bytes);
8269 assert!(route_res.is_err());
8271 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8272 // use the cheaper second hop of the route hint.
8273 let mut first_hop = get_channel_details(Some(1), nodes[0],
8274 channelmanager::provided_init_features(&config), 10_000_000);
8275 first_hop.outbound_scid_alias = Some(44);
8276 let first_hops = vec![first_hop];
8278 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8279 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8280 &Default::default(), &random_seed_bytes).unwrap();
8281 assert_eq!(route.paths.len(), 1);
8282 assert_eq!(route.get_total_amount(), amt_msat);
8283 assert_eq!(route.paths[0].hops.len(), 2);
8284 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8285 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8286 assert_eq!(route.get_total_fees(), 123);
8290 fn allow_us_being_first_hint() {
8291 // Check that we consider a route hint even if we are the src of the first hop.
8292 let secp_ctx = Secp256k1::new();
8293 let logger = Arc::new(ln_test_utils::TestLogger::new());
8294 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8295 let scorer = ln_test_utils::TestScorer::new();
8296 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8297 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8298 let config = UserConfig::default();
8300 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8302 let amt_msat = 1_000_000;
8303 let dest_node_id = nodes[1];
8305 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8306 let first_hops = vec![first_hop];
8308 let route_hint = RouteHint(vec![RouteHintHop {
8309 src_node_id: our_node_id,
8310 short_channel_id: 44,
8313 proportional_millionths: 0,
8315 cltv_expiry_delta: 10,
8316 htlc_minimum_msat: None,
8317 htlc_maximum_msat: None,
8320 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8321 .with_route_hints(vec![route_hint]).unwrap()
8322 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8324 let route_params = RouteParameters::from_payment_params_and_value(
8325 payment_params, amt_msat);
8328 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8329 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8330 &Default::default(), &random_seed_bytes).unwrap();
8332 assert_eq!(route.paths.len(), 1);
8333 assert_eq!(route.get_total_amount(), amt_msat);
8334 assert_eq!(route.get_total_fees(), 0);
8335 assert_eq!(route.paths[0].hops.len(), 1);
8337 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8341 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
8342 pub(crate) mod bench_utils {
8345 use std::time::Duration;
8347 use bitcoin::hashes::Hash;
8348 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
8350 use crate::chain::transaction::OutPoint;
8351 use crate::routing::scoring::ScoreUpdate;
8352 use crate::sign::{EntropySource, KeysManager};
8353 use crate::ln::ChannelId;
8354 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
8355 use crate::ln::features::Bolt11InvoiceFeatures;
8356 use crate::routing::gossip::NetworkGraph;
8357 use crate::util::config::UserConfig;
8358 use crate::util::ser::ReadableArgs;
8359 use crate::util::test_utils::TestLogger;
8361 /// Tries to open a network graph file, or panics with a URL to fetch it.
8362 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
8363 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
8364 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
8365 .or_else(|_| { // Fall back to guessing based on the binary location
8366 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8367 let mut path = std::env::current_exe().unwrap();
8368 path.pop(); // lightning-...
8370 path.pop(); // debug
8371 path.pop(); // target
8372 path.push("lightning");
8373 path.push("net_graph-2023-01-18.bin");
8376 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8377 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8378 let mut path = std::env::current_exe().unwrap();
8379 path.pop(); // bench...
8381 path.pop(); // debug
8382 path.pop(); // target
8383 path.pop(); // bench
8384 path.push("lightning");
8385 path.push("net_graph-2023-01-18.bin");
8388 .map_err(|_| "Please fetch https://bitcoin.ninja/ldk-net_graph-v0.0.113-2023-01-18.bin and place it at lightning/net_graph-2023-01-18.bin");
8389 #[cfg(require_route_graph_test)]
8390 return Ok(res.unwrap());
8391 #[cfg(not(require_route_graph_test))]
8395 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
8396 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
8399 pub(crate) fn payer_pubkey() -> PublicKey {
8400 let secp_ctx = Secp256k1::new();
8401 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8405 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8407 channel_id: ChannelId::new_zero(),
8408 counterparty: ChannelCounterparty {
8409 features: channelmanager::provided_init_features(&UserConfig::default()),
8411 unspendable_punishment_reserve: 0,
8412 forwarding_info: None,
8413 outbound_htlc_minimum_msat: None,
8414 outbound_htlc_maximum_msat: None,
8416 funding_txo: Some(OutPoint {
8417 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8420 short_channel_id: Some(1),
8421 inbound_scid_alias: None,
8422 outbound_scid_alias: None,
8423 channel_value_satoshis: 10_000_000_000,
8425 balance_msat: 10_000_000_000,
8426 outbound_capacity_msat: 10_000_000_000,
8427 next_outbound_htlc_minimum_msat: 0,
8428 next_outbound_htlc_limit_msat: 10_000_000_000,
8429 inbound_capacity_msat: 0,
8430 unspendable_punishment_reserve: None,
8431 confirmations_required: None,
8432 confirmations: None,
8433 force_close_spend_delay: None,
8435 is_channel_ready: true,
8438 inbound_htlc_minimum_msat: None,
8439 inbound_htlc_maximum_msat: None,
8441 feerate_sat_per_1000_weight: None,
8442 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
8446 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8447 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8448 starting_amount: u64, route_count: usize,
8449 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8450 let payer = payer_pubkey();
8451 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8452 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8454 let nodes = graph.read_only().nodes().clone();
8455 let mut route_endpoints = Vec::new();
8456 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
8457 // with some routes we picked being un-routable.
8458 for _ in 0..route_count * 3 / 2 {
8460 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8461 let src = PublicKey::from_slice(nodes.unordered_keys()
8462 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8463 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8464 let dst = PublicKey::from_slice(nodes.unordered_keys()
8465 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8466 let params = PaymentParameters::from_node_id(dst, 42)
8467 .with_bolt11_features(features.clone()).unwrap();
8468 let first_hop = first_hop(src);
8469 let amt_msat = starting_amount + seed % 1_000_000;
8470 let route_params = RouteParameters::from_payment_params_and_value(
8471 params.clone(), amt_msat);
8473 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8474 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8476 // ...and seed the scorer with success and failure data...
8477 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8478 let mut score_amt = seed % 1_000_000_000;
8480 // Generate fail/success paths for a wider range of potential amounts with
8481 // MPP enabled to give us a chance to apply penalties for more potential
8483 let mpp_features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
8484 let params = PaymentParameters::from_node_id(dst, 42)
8485 .with_bolt11_features(mpp_features).unwrap();
8486 let route_params = RouteParameters::from_payment_params_and_value(
8487 params.clone(), score_amt);
8488 let route_res = get_route(&payer, &route_params, &graph.read_only(),
8489 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
8490 &random_seed_bytes);
8491 if let Ok(route) = route_res {
8492 for path in route.paths {
8493 if seed & 0x80 == 0 {
8494 scorer.payment_path_successful(&path, Duration::ZERO);
8496 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
8497 scorer.payment_path_failed(&path, short_channel_id, Duration::ZERO);
8499 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8503 // If we couldn't find a path with a higher amount, reduce and try again.
8507 route_endpoints.push((first_hop, params, amt_msat));
8513 // Because we've changed channel scores, it's possible we'll take different routes to the
8514 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
8515 // requires a too-high CLTV delta.
8516 route_endpoints.retain(|(first_hop, params, amt_msat)| {
8517 let route_params = RouteParameters::from_payment_params_and_value(
8518 params.clone(), *amt_msat);
8519 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8520 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
8522 route_endpoints.truncate(route_count);
8523 assert_eq!(route_endpoints.len(), route_count);
8531 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8532 use crate::sign::{EntropySource, KeysManager};
8533 use crate::ln::channelmanager;
8534 use crate::ln::features::Bolt11InvoiceFeatures;
8535 use crate::routing::gossip::NetworkGraph;
8536 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
8537 use crate::util::config::UserConfig;
8538 use crate::util::logger::{Logger, Record};
8539 use crate::util::test_utils::TestLogger;
8541 use criterion::Criterion;
8543 struct DummyLogger {}
8544 impl Logger for DummyLogger {
8545 fn log(&self, _record: Record) {}
8548 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8549 let logger = TestLogger::new();
8550 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8551 let scorer = FixedPenaltyScorer::with_penalty(0);
8552 generate_routes(bench, &network_graph, scorer, &Default::default(),
8553 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8556 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8557 let logger = TestLogger::new();
8558 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8559 let scorer = FixedPenaltyScorer::with_penalty(0);
8560 generate_routes(bench, &network_graph, scorer, &Default::default(),
8561 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8562 "generate_mpp_routes_with_zero_penalty_scorer");
8565 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8566 let logger = TestLogger::new();
8567 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8568 let params = ProbabilisticScoringFeeParameters::default();
8569 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8570 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8571 "generate_routes_with_probabilistic_scorer");
8574 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8575 let logger = TestLogger::new();
8576 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8577 let params = ProbabilisticScoringFeeParameters::default();
8578 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8579 generate_routes(bench, &network_graph, scorer, ¶ms,
8580 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8581 "generate_mpp_routes_with_probabilistic_scorer");
8584 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8585 let logger = TestLogger::new();
8586 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8587 let params = ProbabilisticScoringFeeParameters::default();
8588 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8589 generate_routes(bench, &network_graph, scorer, ¶ms,
8590 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8591 "generate_large_mpp_routes_with_probabilistic_scorer");
8594 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8595 let logger = TestLogger::new();
8596 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8597 let mut params = ProbabilisticScoringFeeParameters::default();
8598 params.linear_success_probability = false;
8599 let scorer = ProbabilisticScorer::new(
8600 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8601 generate_routes(bench, &network_graph, scorer, ¶ms,
8602 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8603 "generate_routes_with_nonlinear_probabilistic_scorer");
8606 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8607 let logger = TestLogger::new();
8608 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8609 let mut params = ProbabilisticScoringFeeParameters::default();
8610 params.linear_success_probability = false;
8611 let scorer = ProbabilisticScorer::new(
8612 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8613 generate_routes(bench, &network_graph, scorer, ¶ms,
8614 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8615 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8618 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8619 let logger = TestLogger::new();
8620 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8621 let mut params = ProbabilisticScoringFeeParameters::default();
8622 params.linear_success_probability = false;
8623 let scorer = ProbabilisticScorer::new(
8624 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8625 generate_routes(bench, &network_graph, scorer, ¶ms,
8626 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8627 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8630 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8631 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8632 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8633 bench_name: &'static str,
8635 let payer = bench_utils::payer_pubkey();
8636 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8637 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8639 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8640 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8642 // ...then benchmark finding paths between the nodes we learned.
8644 bench.bench_function(bench_name, |b| b.iter(|| {
8645 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8646 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8647 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8648 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());