1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The router finds paths within a [`NetworkGraph`] for a payment.
12 use bitcoin::secp256k1::{PublicKey, Secp256k1, self};
13 use bitcoin::hashes::Hash;
14 use bitcoin::hashes::sha256::Hash as Sha256;
16 use crate::blinded_path::{BlindedHop, BlindedPath};
17 use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, PaymentConstraints, PaymentRelay, ReceiveTlvs};
18 use crate::ln::PaymentHash;
19 use crate::ln::channelmanager::{ChannelDetails, PaymentId};
20 use crate::ln::features::{BlindedHopFeatures, Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
21 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
22 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice};
23 use crate::onion_message::{DefaultMessageRouter, Destination, MessageRouter, OnionMessagePath};
24 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
25 use crate::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp};
26 use crate::sign::EntropySource;
27 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
28 use crate::util::logger::{Level, Logger};
29 use crate::util::chacha20::ChaCha20;
32 use crate::prelude::*;
33 use crate::sync::Mutex;
34 use alloc::collections::BinaryHeap;
38 /// A [`Router`] implemented using [`find_route`].
39 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> where
41 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
45 random_seed_bytes: Mutex<[u8; 32]>,
48 message_router: DefaultMessageRouter<G, L>,
51 impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> DefaultRouter<G, L, S, SP, Sc> where
53 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
55 /// Creates a new router.
56 pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32], scorer: S, score_params: SP) -> Self {
57 let random_seed_bytes = Mutex::new(random_seed_bytes);
58 let message_router = DefaultMessageRouter::new(network_graph.clone());
59 Self { network_graph, logger, random_seed_bytes, scorer, score_params, message_router }
63 impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> Router for DefaultRouter<G, L, S, SP, Sc> where
65 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
70 params: &RouteParameters,
71 first_hops: Option<&[&ChannelDetails]>,
72 inflight_htlcs: InFlightHtlcs
73 ) -> Result<Route, LightningError> {
74 let random_seed_bytes = {
75 let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
76 *locked_random_seed_bytes = Sha256::hash(&*locked_random_seed_bytes).to_byte_array();
77 *locked_random_seed_bytes
80 payer, params, &self.network_graph, first_hops, &*self.logger,
81 &ScorerAccountingForInFlightHtlcs::new(self.scorer.read_lock(), &inflight_htlcs),
87 fn create_blinded_payment_paths<
88 ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
90 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
91 amount_msats: u64, entropy_source: &ES, secp_ctx: &Secp256k1<T>
92 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
93 // Limit the number of blinded paths that are computed.
94 const MAX_PAYMENT_PATHS: usize = 3;
96 // Ensure peers have at least three channels so that it is more difficult to infer the
97 // recipient's node_id.
98 const MIN_PEER_CHANNELS: usize = 3;
100 let network_graph = self.network_graph.deref().read_only();
101 let paths = first_hops.into_iter()
102 .filter(|details| details.counterparty.features.supports_route_blinding())
103 .filter(|details| amount_msats <= details.inbound_capacity_msat)
104 .filter(|details| amount_msats >= details.inbound_htlc_minimum_msat.unwrap_or(0))
105 .filter(|details| amount_msats <= details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX))
106 .filter(|details| network_graph
107 .node(&NodeId::from_pubkey(&details.counterparty.node_id))
108 .map(|node_info| node_info.channels.len() >= MIN_PEER_CHANNELS)
111 .filter_map(|details| {
112 let short_channel_id = match details.get_inbound_payment_scid() {
113 Some(short_channel_id) => short_channel_id,
116 let payment_relay: PaymentRelay = match details.counterparty.forwarding_info {
117 Some(forwarding_info) => forwarding_info.into(),
121 // Avoid exposing esoteric CLTV expiry deltas
122 let cltv_expiry_delta = match payment_relay.cltv_expiry_delta {
130 let payment_constraints = PaymentConstraints {
131 max_cltv_expiry: tlvs.payment_constraints.max_cltv_expiry + cltv_expiry_delta,
132 htlc_minimum_msat: details.inbound_htlc_minimum_msat.unwrap_or(0),
139 features: BlindedHopFeatures::empty(),
141 node_id: details.counterparty.node_id,
142 htlc_maximum_msat: details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX),
145 .map(|forward_node| {
146 BlindedPath::new_for_payment(
147 &[forward_node], recipient, tlvs.clone(), u64::MAX, entropy_source, secp_ctx
150 .take(MAX_PAYMENT_PATHS)
151 .collect::<Result<Vec<_>, _>>();
154 Ok(paths) if !paths.is_empty() => Ok(paths),
156 if network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient)) {
157 BlindedPath::one_hop_for_payment(recipient, tlvs, entropy_source, secp_ctx)
158 .map(|path| vec![path])
167 impl< G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> MessageRouter for DefaultRouter<G, L, S, SP, Sc> where
169 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
172 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
173 ) -> Result<OnionMessagePath, ()> {
174 self.message_router.find_path(sender, peers, destination)
177 fn create_blinded_paths<
178 ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
180 &self, recipient: PublicKey, peers: Vec<PublicKey>, entropy_source: &ES,
181 secp_ctx: &Secp256k1<T>
182 ) -> Result<Vec<BlindedPath>, ()> {
183 self.message_router.create_blinded_paths(recipient, peers, entropy_source, secp_ctx)
187 /// A trait defining behavior for routing a payment.
188 pub trait Router: MessageRouter {
189 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
191 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
192 /// and [`RouteParameters::final_value_msat`], respectively.
194 &self, payer: &PublicKey, route_params: &RouteParameters,
195 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
196 ) -> Result<Route, LightningError>;
198 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
200 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
201 /// and [`RouteParameters::final_value_msat`], respectively.
203 /// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
205 fn find_route_with_id(
206 &self, payer: &PublicKey, route_params: &RouteParameters,
207 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
208 _payment_hash: PaymentHash, _payment_id: PaymentId
209 ) -> Result<Route, LightningError> {
210 self.find_route(payer, route_params, first_hops, inflight_htlcs)
213 /// Creates [`BlindedPath`]s for payment to the `recipient` node. The channels in `first_hops`
214 /// are assumed to be with the `recipient`'s peers. The payment secret and any constraints are
216 fn create_blinded_payment_paths<
217 ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
219 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
220 amount_msats: u64, entropy_source: &ES, secp_ctx: &Secp256k1<T>
221 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()>;
224 /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
226 /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
229 /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
230 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> where S::Target: ScoreLookUp {
232 // Maps a channel's short channel id and its direction to the liquidity used up.
233 inflight_htlcs: &'a InFlightHtlcs,
235 impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
236 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
237 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
238 ScorerAccountingForInFlightHtlcs {
245 impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
246 type ScoreParams = <S::Target as ScoreLookUp>::ScoreParams;
247 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
248 let target = match candidate.target() {
249 Some(target) => target,
250 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
252 let short_channel_id = match candidate.short_channel_id() {
253 Some(short_channel_id) => short_channel_id,
254 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
256 let source = candidate.source();
257 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
258 &source, &target, short_channel_id
260 let usage = ChannelUsage {
261 inflight_htlc_msat: usage.inflight_htlc_msat.saturating_add(used_liquidity),
265 self.scorer.channel_penalty_msat(candidate, usage, score_params)
267 self.scorer.channel_penalty_msat(candidate, usage, score_params)
272 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
273 /// in-use channel liquidity.
275 pub struct InFlightHtlcs(
276 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
277 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
278 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
280 HashMap<(u64, bool), u64>
284 /// Constructs an empty `InFlightHtlcs`.
285 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
287 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
288 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
289 if path.hops.is_empty() { return };
291 let mut cumulative_msat = 0;
292 if let Some(tail) = &path.blinded_tail {
293 cumulative_msat += tail.final_value_msat;
296 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
297 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
298 // the router excludes the payer node. In the following lines, the payer's information is
299 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
300 // in our sliding window of two.
301 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
302 .map(|hop| hop.pubkey)
303 .chain(core::iter::once(payer_node_id));
305 // Taking the reversed vector from above, we zip it with just the reversed hops list to
306 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
307 // the total amount sent.
308 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
309 cumulative_msat += next_hop.fee_msat;
311 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
312 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
313 .or_insert(cumulative_msat);
317 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
319 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
321 .entry((channel_scid, source < target))
322 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
323 .or_insert(used_msat);
326 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
328 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
329 self.0.get(&(channel_scid, source < target)).map(|v| *v)
333 impl Writeable for InFlightHtlcs {
334 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
337 impl Readable for InFlightHtlcs {
338 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
339 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
340 Ok(Self(infight_map))
344 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
345 /// that leads to it.
346 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
347 pub struct RouteHop {
348 /// The node_id of the node at this hop.
349 pub pubkey: PublicKey,
350 /// The node_announcement features of the node at this hop. For the last hop, these may be
351 /// amended to match the features present in the invoice this node generated.
352 pub node_features: NodeFeatures,
353 /// The channel that should be used from the previous hop to reach this node.
354 pub short_channel_id: u64,
355 /// The channel_announcement features of the channel that should be used from the previous hop
356 /// to reach this node.
357 pub channel_features: ChannelFeatures,
358 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
359 /// If this is the last hop in [`Path::hops`]:
360 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
361 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
363 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
365 /// The CLTV delta added for this hop.
366 /// If this is the last hop in [`Path::hops`]:
367 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
368 /// * otherwise, this is the CLTV delta expected at the destination
370 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
371 pub cltv_expiry_delta: u32,
372 /// Indicates whether this hop is possibly announced in the public network graph.
374 /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
375 /// either know for sure it's announced in the public graph, or if any public channels exist
376 /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
377 /// the channel to be unannounced.
379 /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
380 pub maybe_announced_channel: bool,
383 impl_writeable_tlv_based!(RouteHop, {
384 (0, pubkey, required),
385 (1, maybe_announced_channel, (default_value, true)),
386 (2, node_features, required),
387 (4, short_channel_id, required),
388 (6, channel_features, required),
389 (8, fee_msat, required),
390 (10, cltv_expiry_delta, required),
393 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
394 /// their [`Bolt12Invoice`].
396 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
397 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
398 pub struct BlindedTail {
399 /// The hops of the [`BlindedPath`] provided by the recipient.
401 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
402 pub hops: Vec<BlindedHop>,
403 /// The blinding point of the [`BlindedPath`] provided by the recipient.
405 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
406 pub blinding_point: PublicKey,
407 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
408 /// inferring the destination. May be 0.
409 pub excess_final_cltv_expiry_delta: u32,
410 /// The total amount paid on this [`Path`], excluding the fees.
411 pub final_value_msat: u64,
414 impl_writeable_tlv_based!(BlindedTail, {
415 (0, hops, required_vec),
416 (2, blinding_point, required),
417 (4, excess_final_cltv_expiry_delta, required),
418 (6, final_value_msat, required),
421 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
422 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
423 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
425 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
426 pub hops: Vec<RouteHop>,
427 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
428 pub blinded_tail: Option<BlindedTail>,
432 /// Gets the fees for a given path, excluding any excess paid to the recipient.
433 pub fn fee_msat(&self) -> u64 {
434 match &self.blinded_tail {
435 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
437 // Do not count last hop of each path since that's the full value of the payment
438 self.hops.split_last().map_or(0,
439 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
444 /// Gets the total amount paid on this [`Path`], excluding the fees.
445 pub fn final_value_msat(&self) -> u64 {
446 match &self.blinded_tail {
447 Some(blinded_tail) => blinded_tail.final_value_msat,
448 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
452 /// Gets the final hop's CLTV expiry delta.
453 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
454 match &self.blinded_tail {
456 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
461 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
462 /// it can take multiple paths. Each path is composed of one or more hops through the network.
463 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
465 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
466 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
468 pub paths: Vec<Path>,
469 /// The `route_params` parameter passed to [`find_route`].
471 /// This is used by `ChannelManager` to track information which may be required for retries.
473 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
474 pub route_params: Option<RouteParameters>,
478 /// Returns the total amount of fees paid on this [`Route`].
480 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
481 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
482 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
484 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
485 pub fn get_total_fees(&self) -> u64 {
486 let overpaid_value_msat = self.route_params.as_ref()
487 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
488 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
491 /// Returns the total amount paid on this [`Route`], excluding the fees.
493 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
494 /// we had to reach the [`htlc_minimum_msat`] limits.
496 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
497 pub fn get_total_amount(&self) -> u64 {
498 self.paths.iter().map(|path| path.final_value_msat()).sum()
502 impl fmt::Display for Route {
503 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
504 log_route!(self).fmt(f)
508 const SERIALIZATION_VERSION: u8 = 1;
509 const MIN_SERIALIZATION_VERSION: u8 = 1;
511 impl Writeable for Route {
512 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
513 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
514 (self.paths.len() as u64).write(writer)?;
515 let mut blinded_tails = Vec::new();
516 for path in self.paths.iter() {
517 (path.hops.len() as u8).write(writer)?;
518 for (idx, hop) in path.hops.iter().enumerate() {
520 if let Some(blinded_tail) = &path.blinded_tail {
521 if blinded_tails.is_empty() {
522 blinded_tails = Vec::with_capacity(path.hops.len());
524 blinded_tails.push(None);
527 blinded_tails.push(Some(blinded_tail));
528 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
531 write_tlv_fields!(writer, {
532 // For compatibility with LDK versions prior to 0.0.117, we take the individual
533 // RouteParameters' fields and reconstruct them on read.
534 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
535 (2, blinded_tails, optional_vec),
536 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
537 (5, self.route_params.as_ref().map(|p| p.max_total_routing_fee_msat), option),
543 impl Readable for Route {
544 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
545 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
546 let path_count: u64 = Readable::read(reader)?;
547 if path_count == 0 { return Err(DecodeError::InvalidValue); }
548 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
549 let mut min_final_cltv_expiry_delta = u32::max_value();
550 for _ in 0..path_count {
551 let hop_count: u8 = Readable::read(reader)?;
552 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
553 for _ in 0..hop_count {
554 hops.push(Readable::read(reader)?);
556 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
557 min_final_cltv_expiry_delta =
558 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
559 paths.push(Path { hops, blinded_tail: None });
561 _init_and_read_len_prefixed_tlv_fields!(reader, {
562 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
563 (2, blinded_tails, optional_vec),
564 (3, final_value_msat, option),
565 (5, max_total_routing_fee_msat, option)
567 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
568 if blinded_tails.len() != 0 {
569 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
570 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
571 path.blinded_tail = blinded_tail_opt;
575 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
576 let route_params = match (payment_params, final_value_msat) {
577 (Some(payment_params), Some(final_value_msat)) => {
578 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
583 Ok(Route { paths, route_params })
587 /// Parameters needed to find a [`Route`].
589 /// Passed to [`find_route`] and [`build_route_from_hops`].
590 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
591 pub struct RouteParameters {
592 /// The parameters of the failed payment path.
593 pub payment_params: PaymentParameters,
595 /// The amount in msats sent on the failed payment path.
596 pub final_value_msat: u64,
598 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
600 /// This limit also applies to the total fees that may arise while retrying failed payment
603 /// Note that values below a few sats may result in some paths being spuriously ignored.
604 pub max_total_routing_fee_msat: Option<u64>,
607 impl RouteParameters {
608 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
610 /// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
611 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
612 Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
616 impl Writeable for RouteParameters {
617 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
618 write_tlv_fields!(writer, {
619 (0, self.payment_params, required),
620 (1, self.max_total_routing_fee_msat, option),
621 (2, self.final_value_msat, required),
622 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
623 // `RouteParameters` directly. For compatibility, we write it here.
624 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
630 impl Readable for RouteParameters {
631 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
632 _init_and_read_len_prefixed_tlv_fields!(reader, {
633 (0, payment_params, (required: ReadableArgs, 0)),
634 (1, max_total_routing_fee_msat, option),
635 (2, final_value_msat, required),
636 (4, final_cltv_delta, option),
638 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
639 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
640 if final_cltv_expiry_delta == &0 {
641 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
646 final_value_msat: final_value_msat.0.unwrap(),
647 max_total_routing_fee_msat,
652 /// Maximum total CTLV difference we allow for a full payment path.
653 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
655 /// Maximum number of paths we allow an (MPP) payment to have.
656 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
657 // limits, but for now more than 10 paths likely carries too much one-path failure.
658 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
660 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
662 // The median hop CLTV expiry delta currently seen in the network.
663 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
665 // During routing, we only consider paths shorter than our maximum length estimate.
666 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
667 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
668 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
670 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
671 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
672 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
673 // (payment_secret and total_msat) = 93 bytes for the final hop.
674 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
675 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
676 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
678 /// Information used to route a payment.
679 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
680 pub struct PaymentParameters {
681 /// Information about the payee, such as their features and route hints for their channels.
684 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
685 pub expiry_time: Option<u64>,
687 /// The maximum total CLTV delta we accept for the route.
688 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
689 pub max_total_cltv_expiry_delta: u32,
691 /// The maximum number of paths that may be used by (MPP) payments.
692 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
693 pub max_path_count: u8,
695 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
696 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
697 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
698 /// increasing failure probability for those paths.
700 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
701 /// restriction have been found. While paths which meet this criteria will be searched for, it
702 /// is ultimately up to the scorer to select them over other paths.
704 /// A value of 0 will allow payments up to and including a channel's total announced usable
705 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
708 pub max_channel_saturation_power_of_half: u8,
710 /// A list of SCIDs which this payment was previously attempted over and which caused the
711 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
713 pub previously_failed_channels: Vec<u64>,
715 /// A list of indices corresponding to blinded paths in [`Payee::Blinded::route_hints`] which this
716 /// payment was previously attempted over and which caused the payment to fail. Future attempts
717 /// for the same payment shouldn't be relayed through any of these blinded paths.
718 pub previously_failed_blinded_path_idxs: Vec<u64>,
721 impl Writeable for PaymentParameters {
722 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
723 let mut clear_hints = &vec![];
724 let mut blinded_hints = &vec![];
726 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
727 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
729 write_tlv_fields!(writer, {
730 (0, self.payee.node_id(), option),
731 (1, self.max_total_cltv_expiry_delta, required),
732 (2, self.payee.features(), option),
733 (3, self.max_path_count, required),
734 (4, *clear_hints, required_vec),
735 (5, self.max_channel_saturation_power_of_half, required),
736 (6, self.expiry_time, option),
737 (7, self.previously_failed_channels, required_vec),
738 (8, *blinded_hints, optional_vec),
739 (9, self.payee.final_cltv_expiry_delta(), option),
740 (11, self.previously_failed_blinded_path_idxs, required_vec),
746 impl ReadableArgs<u32> for PaymentParameters {
747 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
748 _init_and_read_len_prefixed_tlv_fields!(reader, {
749 (0, payee_pubkey, option),
750 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
751 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
752 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
753 (4, clear_route_hints, required_vec),
754 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
755 (6, expiry_time, option),
756 (7, previously_failed_channels, optional_vec),
757 (8, blinded_route_hints, optional_vec),
758 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
759 (11, previously_failed_blinded_path_idxs, optional_vec),
761 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
762 let payee = if blinded_route_hints.len() != 0 {
763 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
765 route_hints: blinded_route_hints,
766 features: features.and_then(|f: Features| f.bolt12()),
770 route_hints: clear_route_hints,
771 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
772 features: features.and_then(|f| f.bolt11()),
773 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
777 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
778 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
780 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
782 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
783 previously_failed_blinded_path_idxs: previously_failed_blinded_path_idxs.unwrap_or(Vec::new()),
789 impl PaymentParameters {
790 /// Creates a payee with the node id of the given `pubkey`.
792 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
794 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
796 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
798 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
799 max_path_count: DEFAULT_MAX_PATH_COUNT,
800 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
801 previously_failed_channels: Vec::new(),
802 previously_failed_blinded_path_idxs: Vec::new(),
806 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
808 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
811 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
812 /// whether your router will be allowed to find a multi-part route for this payment. If you
813 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
814 /// [`RecipientOnionFields::secret_only`].
816 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
817 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
818 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
819 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
820 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
823 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
824 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
825 /// [`PaymentParameters::expiry_time`].
826 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
827 Self::blinded(invoice.payment_paths().to_vec())
828 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
829 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
832 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
833 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
835 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
837 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
838 max_path_count: DEFAULT_MAX_PATH_COUNT,
839 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
840 previously_failed_channels: Vec::new(),
841 previously_failed_blinded_path_idxs: Vec::new(),
845 /// Includes the payee's features. Errors if the parameters were not initialized with
846 /// [`PaymentParameters::from_bolt12_invoice`].
848 /// This is not exported to bindings users since bindings don't support move semantics
849 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
851 Payee::Clear { .. } => Err(()),
852 Payee::Blinded { route_hints, .. } =>
853 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
857 /// Includes the payee's features. Errors if the parameters were initialized with
858 /// [`PaymentParameters::from_bolt12_invoice`].
860 /// This is not exported to bindings users since bindings don't support move semantics
861 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
863 Payee::Blinded { .. } => Err(()),
864 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
866 payee: Payee::Clear {
867 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
873 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
874 /// [`PaymentParameters::from_bolt12_invoice`].
876 /// This is not exported to bindings users since bindings don't support move semantics
877 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
879 Payee::Blinded { .. } => Err(()),
880 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
882 payee: Payee::Clear {
883 route_hints, node_id, features, final_cltv_expiry_delta,
889 /// Includes a payment expiration in seconds relative to the UNIX epoch.
891 /// This is not exported to bindings users since bindings don't support move semantics
892 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
893 Self { expiry_time: Some(expiry_time), ..self }
896 /// Includes a limit for the total CLTV expiry delta which is considered during routing
898 /// This is not exported to bindings users since bindings don't support move semantics
899 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
900 Self { max_total_cltv_expiry_delta, ..self }
903 /// Includes a limit for the maximum number of payment paths that may be used.
905 /// This is not exported to bindings users since bindings don't support move semantics
906 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
907 Self { max_path_count, ..self }
910 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
911 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
913 /// This is not exported to bindings users since bindings don't support move semantics
914 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
915 Self { max_channel_saturation_power_of_half, ..self }
918 pub(crate) fn insert_previously_failed_blinded_path(&mut self, failed_blinded_tail: &BlindedTail) {
919 let mut found_blinded_tail = false;
920 for (idx, (_, path)) in self.payee.blinded_route_hints().iter().enumerate() {
921 if failed_blinded_tail.hops == path.blinded_hops &&
922 failed_blinded_tail.blinding_point == path.blinding_point
924 self.previously_failed_blinded_path_idxs.push(idx as u64);
925 found_blinded_tail = true;
928 debug_assert!(found_blinded_tail);
932 /// The recipient of a payment, differing based on whether they've hidden their identity with route
934 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
936 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
937 /// will be included in the final [`Route`].
939 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
941 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
942 /// Features supported by the payee.
944 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
946 features: Option<Bolt12InvoiceFeatures>,
948 /// The recipient included these route hints in their BOLT11 invoice.
950 /// The node id of the payee.
952 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
953 route_hints: Vec<RouteHint>,
954 /// Features supported by the payee.
956 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
957 /// does not contain any features.
959 /// [`for_keysend`]: PaymentParameters::for_keysend
960 features: Option<Bolt11InvoiceFeatures>,
961 /// The minimum CLTV delta at the end of the route. This value must not be zero.
962 final_cltv_expiry_delta: u32,
967 fn node_id(&self) -> Option<PublicKey> {
969 Self::Clear { node_id, .. } => Some(*node_id),
973 fn node_features(&self) -> Option<NodeFeatures> {
975 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
976 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
979 fn supports_basic_mpp(&self) -> bool {
981 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
982 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
985 fn features(&self) -> Option<FeaturesRef> {
987 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
988 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
991 fn final_cltv_expiry_delta(&self) -> Option<u32> {
993 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
997 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
999 Self::Blinded { route_hints, .. } => &route_hints[..],
1000 Self::Clear { .. } => &[]
1004 fn unblinded_route_hints(&self) -> &[RouteHint] {
1006 Self::Blinded { .. } => &[],
1007 Self::Clear { route_hints, .. } => &route_hints[..]
1012 enum FeaturesRef<'a> {
1013 Bolt11(&'a Bolt11InvoiceFeatures),
1014 Bolt12(&'a Bolt12InvoiceFeatures),
1017 Bolt11(Bolt11InvoiceFeatures),
1018 Bolt12(Bolt12InvoiceFeatures),
1022 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
1024 Self::Bolt12(f) => Some(f),
1028 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
1030 Self::Bolt11(f) => Some(f),
1036 impl<'a> Writeable for FeaturesRef<'a> {
1037 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1039 Self::Bolt11(f) => Ok(f.write(w)?),
1040 Self::Bolt12(f) => Ok(f.write(w)?),
1045 impl ReadableArgs<bool> for Features {
1046 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
1047 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
1048 Ok(Self::Bolt12(Readable::read(reader)?))
1052 /// A list of hops along a payment path terminating with a channel to the recipient.
1053 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1054 pub struct RouteHint(pub Vec<RouteHintHop>);
1056 impl Writeable for RouteHint {
1057 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1058 (self.0.len() as u64).write(writer)?;
1059 for hop in self.0.iter() {
1066 impl Readable for RouteHint {
1067 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1068 let hop_count: u64 = Readable::read(reader)?;
1069 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
1070 for _ in 0..hop_count {
1071 hops.push(Readable::read(reader)?);
1077 /// A channel descriptor for a hop along a payment path.
1079 /// While this generally comes from BOLT 11's `r` field, this struct includes more fields than are
1080 /// available in BOLT 11. Thus, encoding and decoding this via `lightning-invoice` is lossy, as
1081 /// fields not supported in BOLT 11 will be stripped.
1082 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1083 pub struct RouteHintHop {
1084 /// The node_id of the non-target end of the route
1085 pub src_node_id: PublicKey,
1086 /// The short_channel_id of this channel
1087 pub short_channel_id: u64,
1088 /// The fees which must be paid to use this channel
1089 pub fees: RoutingFees,
1090 /// The difference in CLTV values between this node and the next node.
1091 pub cltv_expiry_delta: u16,
1092 /// The minimum value, in msat, which must be relayed to the next hop.
1093 pub htlc_minimum_msat: Option<u64>,
1094 /// The maximum value in msat available for routing with a single HTLC.
1095 pub htlc_maximum_msat: Option<u64>,
1098 impl_writeable_tlv_based!(RouteHintHop, {
1099 (0, src_node_id, required),
1100 (1, htlc_minimum_msat, option),
1101 (2, short_channel_id, required),
1102 (3, htlc_maximum_msat, option),
1103 (4, fees, required),
1104 (6, cltv_expiry_delta, required),
1107 #[derive(Eq, PartialEq)]
1108 #[repr(align(64))] // Force the size to 64 bytes
1109 struct RouteGraphNode {
1112 // The maximum value a yet-to-be-constructed payment path might flow through this node.
1113 // This value is upper-bounded by us by:
1114 // - how much is needed for a path being constructed
1115 // - how much value can channels following this node (up to the destination) can contribute,
1116 // considering their capacity and fees
1117 value_contribution_msat: u64,
1118 total_cltv_delta: u32,
1119 /// The number of hops walked up to this node.
1120 path_length_to_node: u8,
1123 impl cmp::Ord for RouteGraphNode {
1124 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
1125 other.score.cmp(&self.score).then_with(|| other.node_id.cmp(&self.node_id))
1129 impl cmp::PartialOrd for RouteGraphNode {
1130 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
1131 Some(self.cmp(other))
1135 // While RouteGraphNode can be laid out with fewer bytes, performance appears to be improved
1136 // substantially when it is laid out at exactly 64 bytes.
1138 // Thus, we use `#[repr(C)]` on the struct to force a suboptimal layout and check that it stays 64
1140 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1141 const _GRAPH_NODE_SMALL: usize = 64 - core::mem::size_of::<RouteGraphNode>();
1142 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1143 const _GRAPH_NODE_FIXED_SIZE: usize = core::mem::size_of::<RouteGraphNode>() - 64;
1145 /// A [`CandidateRouteHop::FirstHop`] entry.
1146 #[derive(Clone, Debug)]
1147 pub struct FirstHopCandidate<'a> {
1148 /// Channel details of the first hop
1150 /// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1151 /// has been funded and is able to pay), and accessor methods may panic otherwise.
1153 /// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1154 pub details: &'a ChannelDetails,
1155 /// The node id of the payer, which is also the source side of this candidate route hop.
1156 pub payer_node_id: &'a NodeId,
1159 /// A [`CandidateRouteHop::PublicHop`] entry.
1160 #[derive(Clone, Debug)]
1161 pub struct PublicHopCandidate<'a> {
1162 /// Information about the channel, including potentially its capacity and
1163 /// direction-specific information.
1164 pub info: DirectedChannelInfo<'a>,
1165 /// The short channel ID of the channel, i.e. the identifier by which we refer to this
1167 pub short_channel_id: u64,
1170 /// A [`CandidateRouteHop::PrivateHop`] entry.
1171 #[derive(Clone, Debug)]
1172 pub struct PrivateHopCandidate<'a> {
1173 /// Information about the private hop communicated via BOLT 11.
1174 pub hint: &'a RouteHintHop,
1175 /// Node id of the next hop in BOLT 11 route hint.
1176 pub target_node_id: &'a NodeId
1179 /// A [`CandidateRouteHop::Blinded`] entry.
1180 #[derive(Clone, Debug)]
1181 pub struct BlindedPathCandidate<'a> {
1182 /// Information about the blinded path including the fee, HTLC amount limits, and
1183 /// cryptographic material required to build an HTLC through the given path.
1184 pub hint: &'a (BlindedPayInfo, BlindedPath),
1185 /// Index of the hint in the original list of blinded hints.
1187 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1188 /// a short channel ID for this hop.
1192 /// A [`CandidateRouteHop::OneHopBlinded`] entry.
1193 #[derive(Clone, Debug)]
1194 pub struct OneHopBlindedPathCandidate<'a> {
1195 /// Information about the blinded path including the fee, HTLC amount limits, and
1196 /// cryptographic material required to build an HTLC terminating with the given path.
1198 /// Note that the [`BlindedPayInfo`] is ignored here.
1199 pub hint: &'a (BlindedPayInfo, BlindedPath),
1200 /// Index of the hint in the original list of blinded hints.
1202 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1203 /// a short channel ID for this hop.
1207 /// A wrapper around the various hop representations.
1209 /// Can be used to examine the properties of a hop,
1210 /// potentially to decide whether to include it in a route.
1211 #[derive(Clone, Debug)]
1212 pub enum CandidateRouteHop<'a> {
1213 /// A hop from the payer, where the outbound liquidity is known.
1214 FirstHop(FirstHopCandidate<'a>),
1215 /// A hop found in the [`ReadOnlyNetworkGraph`].
1216 PublicHop(PublicHopCandidate<'a>),
1217 /// A private hop communicated by the payee, generally via a BOLT 11 invoice.
1219 /// Because BOLT 11 route hints can take multiple hops to get to the destination, this may not
1220 /// terminate at the payee.
1221 PrivateHop(PrivateHopCandidate<'a>),
1222 /// A blinded path which starts with an introduction point and ultimately terminates with the
1225 /// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1226 /// `None` in this state.
1228 /// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1229 /// path, the full path is treated as a single [`CandidateRouteHop`].
1230 Blinded(BlindedPathCandidate<'a>),
1231 /// Similar to [`Self::Blinded`], but the path here only has one hop.
1233 /// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1234 /// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1235 /// payee's identity - it's the introduction point!
1237 /// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1238 /// to the hops *between* the introduction node and the destination.
1240 /// This primarily exists to track that we need to included a blinded path at the end of our
1241 /// [`Route`], even though it doesn't actually add an additional hop in the payment.
1242 OneHopBlinded(OneHopBlindedPathCandidate<'a>),
1245 impl<'a> CandidateRouteHop<'a> {
1246 /// Returns the short channel ID for this hop, if one is known.
1248 /// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1249 /// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1251 /// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1252 /// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1253 /// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1254 /// (which is always true for channels which are funded and ready for use).
1256 /// In other words, this should always return `Some` as long as the candidate hop is not a
1257 /// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1259 /// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1260 /// define a global namespace.
1262 fn short_channel_id(&self) -> Option<u64> {
1264 CandidateRouteHop::FirstHop(hop) => hop.details.get_outbound_payment_scid(),
1265 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1266 CandidateRouteHop::PrivateHop(hop) => Some(hop.hint.short_channel_id),
1267 CandidateRouteHop::Blinded(_) => None,
1268 CandidateRouteHop::OneHopBlinded(_) => None,
1272 /// Returns the globally unique short channel ID for this hop, if one is known.
1274 /// This only returns `Some` if the channel is public (either our own, or one we've learned
1275 /// from the public network graph), and thus the short channel ID we have for this channel is
1276 /// globally unique and identifies this channel in a global namespace.
1278 pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1280 CandidateRouteHop::FirstHop(hop) => if hop.details.is_public { hop.details.short_channel_id } else { None },
1281 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1282 CandidateRouteHop::PrivateHop(_) => None,
1283 CandidateRouteHop::Blinded(_) => None,
1284 CandidateRouteHop::OneHopBlinded(_) => None,
1288 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1289 fn features(&self) -> ChannelFeatures {
1291 CandidateRouteHop::FirstHop(hop) => hop.details.counterparty.features.to_context(),
1292 CandidateRouteHop::PublicHop(hop) => hop.info.channel().features.clone(),
1293 CandidateRouteHop::PrivateHop(_) => ChannelFeatures::empty(),
1294 CandidateRouteHop::Blinded(_) => ChannelFeatures::empty(),
1295 CandidateRouteHop::OneHopBlinded(_) => ChannelFeatures::empty(),
1299 /// Returns the required difference in HTLC CLTV expiry between the [`Self::source`] and the
1300 /// next-hop for an HTLC taking this hop.
1302 /// This is the time that the node(s) in this hop have to claim the HTLC on-chain if the
1303 /// next-hop goes on chain with a payment preimage.
1305 pub fn cltv_expiry_delta(&self) -> u32 {
1307 CandidateRouteHop::FirstHop(_) => 0,
1308 CandidateRouteHop::PublicHop(hop) => hop.info.direction().cltv_expiry_delta as u32,
1309 CandidateRouteHop::PrivateHop(hop) => hop.hint.cltv_expiry_delta as u32,
1310 CandidateRouteHop::Blinded(hop) => hop.hint.0.cltv_expiry_delta as u32,
1311 CandidateRouteHop::OneHopBlinded(_) => 0,
1315 /// Returns the minimum amount that can be sent over this hop, in millisatoshis.
1317 pub fn htlc_minimum_msat(&self) -> u64 {
1319 CandidateRouteHop::FirstHop(hop) => hop.details.next_outbound_htlc_minimum_msat,
1320 CandidateRouteHop::PublicHop(hop) => hop.info.direction().htlc_minimum_msat,
1321 CandidateRouteHop::PrivateHop(hop) => hop.hint.htlc_minimum_msat.unwrap_or(0),
1322 CandidateRouteHop::Blinded(hop) => hop.hint.0.htlc_minimum_msat,
1323 CandidateRouteHop::OneHopBlinded { .. } => 0,
1327 /// Returns the fees that must be paid to route an HTLC over this channel.
1329 pub fn fees(&self) -> RoutingFees {
1331 CandidateRouteHop::FirstHop(_) => RoutingFees {
1332 base_msat: 0, proportional_millionths: 0,
1334 CandidateRouteHop::PublicHop(hop) => hop.info.direction().fees,
1335 CandidateRouteHop::PrivateHop(hop) => hop.hint.fees,
1336 CandidateRouteHop::Blinded(hop) => {
1338 base_msat: hop.hint.0.fee_base_msat,
1339 proportional_millionths: hop.hint.0.fee_proportional_millionths
1342 CandidateRouteHop::OneHopBlinded(_) =>
1343 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1347 /// Fetch the effective capacity of this hop.
1349 /// Note that this may be somewhat expensive, so calls to this should be limited and results
1351 fn effective_capacity(&self) -> EffectiveCapacity {
1353 CandidateRouteHop::FirstHop(hop) => EffectiveCapacity::ExactLiquidity {
1354 liquidity_msat: hop.details.next_outbound_htlc_limit_msat,
1356 CandidateRouteHop::PublicHop(hop) => hop.info.effective_capacity(),
1357 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. }) =>
1358 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1359 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. }) =>
1360 EffectiveCapacity::Infinite,
1361 CandidateRouteHop::Blinded(hop) =>
1362 EffectiveCapacity::HintMaxHTLC { amount_msat: hop.hint.0.htlc_maximum_msat },
1363 CandidateRouteHop::OneHopBlinded(_) => EffectiveCapacity::Infinite,
1367 /// Returns an ID describing the given hop.
1369 /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1371 fn id(&self) -> CandidateHopId {
1373 CandidateRouteHop::Blinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1374 CandidateRouteHop::OneHopBlinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1375 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1378 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1380 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1386 fn blinded_hint_idx(&self) -> Option<usize> {
1388 Self::Blinded(BlindedPathCandidate { hint_idx, .. }) |
1389 Self::OneHopBlinded(OneHopBlindedPathCandidate { hint_idx, .. }) => {
1395 /// Returns the source node id of current hop.
1397 /// Source node id refers to the node forwarding the HTLC through this hop.
1399 /// For [`Self::FirstHop`] we return payer's node id.
1401 pub fn source(&self) -> NodeId {
1403 CandidateRouteHop::FirstHop(hop) => *hop.payer_node_id,
1404 CandidateRouteHop::PublicHop(hop) => *hop.info.source(),
1405 CandidateRouteHop::PrivateHop(hop) => hop.hint.src_node_id.into(),
1406 CandidateRouteHop::Blinded(hop) => hop.hint.1.introduction_node_id.into(),
1407 CandidateRouteHop::OneHopBlinded(hop) => hop.hint.1.introduction_node_id.into(),
1410 /// Returns the target node id of this hop, if known.
1412 /// Target node id refers to the node receiving the HTLC after this hop.
1414 /// For [`Self::Blinded`] we return `None` because the ultimate destination after the blinded
1415 /// path is unknown.
1417 /// For [`Self::OneHopBlinded`] we return `None` because the target is the same as the source,
1418 /// and such a return value would be somewhat nonsensical.
1420 pub fn target(&self) -> Option<NodeId> {
1422 CandidateRouteHop::FirstHop(hop) => Some(hop.details.counterparty.node_id.into()),
1423 CandidateRouteHop::PublicHop(hop) => Some(*hop.info.target()),
1424 CandidateRouteHop::PrivateHop(hop) => Some(*hop.target_node_id),
1425 CandidateRouteHop::Blinded(_) => None,
1426 CandidateRouteHop::OneHopBlinded(_) => None,
1431 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1433 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1435 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1436 /// isn't guaranteed to be unique at all.
1438 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1439 /// difficult-to-use API.
1440 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1441 enum CandidateHopId {
1442 /// Contains (scid, src_node_id < target_node_id)
1444 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1449 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1450 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1452 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1453 EffectiveCapacity::Infinite => u64::max_value(),
1454 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1455 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1456 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1457 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1458 // expected to have been generated from up-to-date capacity information.
1459 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1460 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1461 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1465 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1466 -> bool where I1::Item: PartialEq<I2::Item> {
1468 let a = iter_a.next();
1469 let b = iter_b.next();
1470 if a.is_none() && b.is_none() { return true; }
1471 if a.is_none() || b.is_none() { return false; }
1472 if a.unwrap().ne(&b.unwrap()) { return false; }
1476 /// It's useful to keep track of the hops associated with the fees required to use them,
1477 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1478 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1479 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1481 #[repr(C)] // Force fields to appear in the order we define them.
1482 struct PathBuildingHop<'a> {
1483 candidate: CandidateRouteHop<'a>,
1484 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1485 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1486 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1487 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1488 /// avoid processing them again.
1489 was_processed: bool,
1490 /// Used to compare channels when choosing the for routing.
1491 /// Includes paying for the use of a hop and the following hops, as well as
1492 /// an estimated cost of reaching this hop.
1493 /// Might get stale when fees are recomputed. Primarily for internal use.
1494 total_fee_msat: u64,
1495 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1496 /// walk and may be invalid thereafter.
1497 path_htlc_minimum_msat: u64,
1498 /// All penalties incurred from this channel on the way to the destination, as calculated using
1499 /// channel scoring.
1500 path_penalty_msat: u64,
1502 // The last 16 bytes are on the next cache line by default in glibc's malloc. Thus, we should
1503 // only place fields which are not hot there. Luckily, the next three fields are only read if
1504 // we end up on the selected path, and only in the final path layout phase, so we don't care
1505 // too much if reading them is slow.
1509 /// All the fees paid *after* this channel on the way to the destination
1510 next_hops_fee_msat: u64,
1511 /// Fee paid for the use of the current channel (see candidate.fees()).
1512 /// The value will be actually deducted from the counterparty balance on the previous link.
1513 hop_use_fee_msat: u64,
1515 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1516 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1517 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1518 // value_contribution_msat, which requires tracking it here. See comments below where it is
1519 // used for more info.
1520 value_contribution_msat: u64,
1523 // Checks that the entries in the `find_route` `dist` map fit in (exactly) two standard x86-64
1524 // cache lines. Sadly, they're not guaranteed to actually lie on a cache line (and in fact,
1525 // generally won't, because at least glibc's malloc will align to a nice, big, round
1526 // boundary...plus 16), but at least it will reduce the amount of data we'll need to load.
1528 // Note that these assertions only pass on somewhat recent rustc, and thus are gated on the
1531 const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::<(NodeId, PathBuildingHop)>();
1533 const _NODE_MAP_SIZE_EXACTLY_CACHE_LINES: usize = core::mem::size_of::<(NodeId, PathBuildingHop)>() - 128;
1535 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1536 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1537 let mut debug_struct = f.debug_struct("PathBuildingHop");
1539 .field("node_id", &self.candidate.target())
1540 .field("short_channel_id", &self.candidate.short_channel_id())
1541 .field("total_fee_msat", &self.total_fee_msat)
1542 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1543 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1544 .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)))
1545 .field("path_penalty_msat", &self.path_penalty_msat)
1546 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1547 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1548 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1549 let debug_struct = debug_struct
1550 .field("value_contribution_msat", &self.value_contribution_msat);
1551 debug_struct.finish()
1555 // Instantiated with a list of hops with correct data in them collected during path finding,
1556 // an instance of this struct should be further modified only via given methods.
1558 struct PaymentPath<'a> {
1559 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1562 impl<'a> PaymentPath<'a> {
1563 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1564 fn get_value_msat(&self) -> u64 {
1565 self.hops.last().unwrap().0.fee_msat
1568 fn get_path_penalty_msat(&self) -> u64 {
1569 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1572 fn get_total_fee_paid_msat(&self) -> u64 {
1573 if self.hops.len() < 1 {
1577 // Can't use next_hops_fee_msat because it gets outdated.
1578 for (i, (hop, _)) in self.hops.iter().enumerate() {
1579 if i != self.hops.len() - 1 {
1580 result += hop.fee_msat;
1586 fn get_cost_msat(&self) -> u64 {
1587 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1590 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1591 // to change fees may result in an inconsistency.
1593 // Sometimes we call this function right after constructing a path which is inconsistent in
1594 // that it the value being transferred has decreased while we were doing path finding, leading
1595 // to the fees being paid not lining up with the actual limits.
1597 // Note that this function is not aware of the available_liquidity limit, and thus does not
1598 // support increasing the value being transferred beyond what was selected during the initial
1601 // Returns the amount that this path contributes to the total payment value, which may be greater
1602 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1603 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1604 let mut extra_contribution_msat = 0;
1605 let mut total_fee_paid_msat = 0 as u64;
1606 for i in (0..self.hops.len()).rev() {
1607 let last_hop = i == self.hops.len() - 1;
1609 // For non-last-hop, this value will represent the fees paid on the current hop. It
1610 // will consist of the fees for the use of the next hop, and extra fees to match
1611 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1612 let mut cur_hop_fees_msat = 0;
1614 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1617 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1618 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1619 cur_hop.path_penalty_msat += extra_contribution_msat;
1620 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1621 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1622 // set it too high just to maliciously take more fees by exploiting this
1623 // match htlc_minimum_msat logic.
1624 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1625 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1626 // Note that there is a risk that *previous hops* (those closer to us, as we go
1627 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1629 // This might make us end up with a broken route, although this should be super-rare
1630 // in practice, both because of how healthy channels look like, and how we pick
1631 // channels in add_entry.
1632 // Also, this can't be exploited more heavily than *announce a free path and fail
1634 cur_hop_transferred_amount_msat += extra_fees_msat;
1636 // We remember and return the extra fees on the final hop to allow accounting for
1637 // them in the path's value contribution.
1639 extra_contribution_msat = extra_fees_msat;
1641 total_fee_paid_msat += extra_fees_msat;
1642 cur_hop_fees_msat += extra_fees_msat;
1647 // Final hop is a special case: it usually has just value_msat (by design), but also
1648 // it still could overpay for the htlc_minimum_msat.
1649 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1651 // Propagate updated fees for the use of the channels to one hop back, where they
1652 // will be actually paid (fee_msat). The last hop is handled above separately.
1653 cur_hop.fee_msat = cur_hop_fees_msat;
1656 // Fee for the use of the current hop which will be deducted on the previous hop.
1657 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1658 // this channel is free for us.
1660 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1661 cur_hop.hop_use_fee_msat = new_fee;
1662 total_fee_paid_msat += new_fee;
1664 // It should not be possible because this function is called only to reduce the
1665 // value. In that case, compute_fee was already called with the same fees for
1666 // larger amount and there was no overflow.
1671 value_msat + extra_contribution_msat
1676 /// Calculate the fees required to route the given amount over a channel with the given fees.
1677 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1678 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1679 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1683 /// Calculate the fees required to route the given amount over a channel with the given fees,
1684 /// saturating to [`u64::max_value`].
1685 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1686 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1687 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1688 .saturating_add(channel_fees.base_msat as u64)
1691 /// The default `features` we assume for a node in a route, when no `features` are known about that
1694 /// Default features are:
1695 /// * variable_length_onion_optional
1696 fn default_node_features() -> NodeFeatures {
1697 let mut features = NodeFeatures::empty();
1698 features.set_variable_length_onion_optional();
1702 struct LoggedPayeePubkey(Option<PublicKey>);
1703 impl fmt::Display for LoggedPayeePubkey {
1704 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1707 "payee node id ".fmt(f)?;
1711 "blinded payee".fmt(f)
1717 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1718 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1719 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1721 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1722 "blinded route hint with introduction node id ".fmt(f)?;
1723 hint.1.introduction_node_id.fmt(f)?;
1724 " and blinding point ".fmt(f)?;
1725 hint.1.blinding_point.fmt(f)
1727 CandidateRouteHop::FirstHop(_) => {
1728 "first hop with SCID ".fmt(f)?;
1729 self.0.short_channel_id().unwrap().fmt(f)
1731 CandidateRouteHop::PrivateHop(_) => {
1732 "route hint with SCID ".fmt(f)?;
1733 self.0.short_channel_id().unwrap().fmt(f)
1737 self.0.short_channel_id().unwrap().fmt(f)
1744 fn sort_first_hop_channels(
1745 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1746 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1748 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1749 // most like to use.
1751 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1752 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1755 // Second, because simply always sorting in descending order would always use our largest
1756 // available outbound capacity, needlessly fragmenting our available channel capacities,
1757 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1758 // which have enough, but not too much, capacity for the payment.
1760 // Available outbound balances factor in liquidity already reserved for previously found paths.
1761 channels.sort_unstable_by(|chan_a, chan_b| {
1762 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1763 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1764 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1765 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1766 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1767 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1768 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1769 // Sort in descending order
1770 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1772 // Sort in ascending order
1773 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1778 /// Finds a route from us (payer) to the given target node (payee).
1780 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1781 /// in the given [`RouteParameters::payment_params`].
1782 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1784 /// Private routing paths between a public node and the target may be included in the `payee` field
1785 /// of [`RouteParameters::payment_params`].
1787 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1788 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1789 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1791 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1792 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1793 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1797 /// Panics if first_hops contains channels without `short_channel_id`s;
1798 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1800 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1801 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1802 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1803 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1804 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1805 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1806 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1807 ) -> Result<Route, LightningError>
1808 where L::Target: Logger, GL::Target: Logger {
1809 let graph_lock = network_graph.read_only();
1810 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1811 scorer, score_params, random_seed_bytes)?;
1812 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1816 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1817 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1818 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1819 _random_seed_bytes: &[u8; 32]
1820 ) -> Result<Route, LightningError>
1821 where L::Target: Logger {
1823 let payment_params = &route_params.payment_params;
1824 let final_value_msat = route_params.final_value_msat;
1825 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1826 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1827 // so use a dummy id for this in the blinded case.
1828 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1829 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1830 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1831 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1832 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1834 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1835 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1837 if our_node_id == maybe_dummy_payee_node_id {
1838 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1841 if final_value_msat > MAX_VALUE_MSAT {
1842 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1845 if final_value_msat == 0 {
1846 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1849 match &payment_params.payee {
1850 Payee::Clear { route_hints, node_id, .. } => {
1851 for route in route_hints.iter() {
1852 for hop in &route.0 {
1853 if hop.src_node_id == *node_id {
1854 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1859 Payee::Blinded { route_hints, .. } => {
1860 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1861 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});
1863 for (_, blinded_path) in route_hints.iter() {
1864 if blinded_path.blinded_hops.len() == 0 {
1865 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1866 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1867 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1868 } else if blinded_path.blinded_hops.len() == 1 &&
1869 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1870 && p.introduction_node_id != blinded_path.introduction_node_id)
1872 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1877 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1878 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1879 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});
1882 // The general routing idea is the following:
1883 // 1. Fill first/last hops communicated by the caller.
1884 // 2. Attempt to construct a path from payer to payee for transferring
1885 // any ~sufficient (described later) value.
1886 // If succeed, remember which channels were used and how much liquidity they have available,
1887 // so that future paths don't rely on the same liquidity.
1888 // 3. Proceed to the next step if:
1889 // - we hit the recommended target value;
1890 // - OR if we could not construct a new path. Any next attempt will fail too.
1891 // Otherwise, repeat step 2.
1892 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1893 // (not recommended value).
1894 // 5. If yes, proceed. If not, fail routing.
1895 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1896 // transferred up to the transfer target value.
1897 // 7. Reduce the value of the last path until we are sending only the target value.
1898 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1899 // them so that we're not sending two HTLCs along the same path.
1901 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1902 // distance from the payee
1904 // We are not a faithful Dijkstra's implementation because we can change values which impact
1905 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1906 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1907 // the value we are currently attempting to send over a path, we simply reduce the value being
1908 // sent along the path for any hops after that channel. This may imply that later fees (which
1909 // we've already tabulated) are lower because a smaller value is passing through the channels
1910 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1911 // channels which were selected earlier (and which may still be used for other paths without a
1912 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1915 // One potentially problematic case for this algorithm would be if there are many
1916 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1917 // graph walking), we may never find a path which is not liquidity-limited and has lower
1918 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1919 // Because we only consider paths with at least 5% of the total value being sent, the damage
1920 // from such a case should be limited, however this could be further reduced in the future by
1921 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1922 // limits for the purposes of fee calculation.
1924 // Alternatively, we could store more detailed path information in the heap (targets, below)
1925 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1926 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1927 // and practically (as we would need to store dynamically-allocated path information in heap
1928 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1929 // results of such an algorithm would likely be biased towards lower-value paths.
1931 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1932 // outside of our current search value, running a path search more times to gather candidate
1933 // paths at different values. While this may be acceptable, further path searches may increase
1934 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1935 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1936 // the same time, remaining generic across different payment values.
1938 let network_channels = network_graph.channels();
1939 let network_nodes = network_graph.nodes();
1941 if payment_params.max_path_count == 0 {
1942 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1945 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1946 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1948 let allow_mpp = if payment_params.max_path_count == 1 {
1950 } else if payment_params.payee.supports_basic_mpp() {
1952 } else if let Some(payee) = payee_node_id_opt {
1953 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1954 |info| info.features.supports_basic_mpp()))
1957 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1959 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph with a fee limit of {} msat",
1960 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
1961 if allow_mpp { "with" } else { "without" },
1962 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " },
1963 max_total_routing_fee_msat);
1966 // Prepare the data we'll use for payee-to-payer search by
1967 // inserting first hops suggested by the caller as targets.
1968 // Our search will then attempt to reach them while traversing from the payee node.
1969 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1970 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1971 if let Some(hops) = first_hops {
1973 if chan.get_outbound_payment_scid().is_none() {
1974 panic!("first_hops should be filled in with usable channels, not pending ones");
1976 if chan.counterparty.node_id == *our_node_pubkey {
1977 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1980 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1981 .or_insert(Vec::new())
1984 if first_hop_targets.is_empty() {
1985 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1989 let mut private_hop_key_cache = HashMap::with_capacity(
1990 payment_params.payee.unblinded_route_hints().iter().map(|path| path.0.len()).sum()
1993 // Because we store references to private hop node_ids in `dist`, below, we need them to exist
1994 // (as `NodeId`, not `PublicKey`) for the lifetime of `dist`. Thus, we calculate all the keys
1995 // we'll need here and simply fetch them when routing.
1996 private_hop_key_cache.insert(maybe_dummy_payee_pk, NodeId::from_pubkey(&maybe_dummy_payee_pk));
1997 for route in payment_params.payee.unblinded_route_hints().iter() {
1998 for hop in route.0.iter() {
1999 private_hop_key_cache.insert(hop.src_node_id, NodeId::from_pubkey(&hop.src_node_id));
2003 // The main heap containing all candidate next-hops sorted by their score (max(fee,
2004 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
2005 // adding duplicate entries when we find a better path to a given node.
2006 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
2008 // Map from node_id to information about the best current path to that node, including feerate
2010 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
2012 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
2013 // indicating that we may wish to try again with a higher value, potentially paying to meet an
2014 // htlc_minimum with extra fees while still finding a cheaper path.
2015 let mut hit_minimum_limit;
2017 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
2018 // We start with a path_value of the exact amount we want, and if that generates a route we may
2019 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
2020 // amount we want in total across paths, selecting the best subset at the end.
2021 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
2022 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
2023 let mut path_value_msat = final_value_msat;
2025 // Routing Fragmentation Mitigation heuristic:
2027 // Routing fragmentation across many payment paths increases the overall routing
2028 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
2029 // Taking too many smaller paths also increases the chance of payment failure.
2030 // Thus to avoid this effect, we require from our collected links to provide
2031 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
2032 // This requirement is currently set to be 1/max_path_count of the payment
2033 // value to ensure we only ever return routes that do not violate this limit.
2034 let minimal_value_contribution_msat: u64 = if allow_mpp {
2035 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
2040 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
2041 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
2042 // drop the requirement by setting this to 0.
2043 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
2045 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
2046 // determine if the channel can be used by additional MPP paths or to inform path finding
2047 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
2048 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
2050 let mut used_liquidities: HashMap<CandidateHopId, u64> =
2051 HashMap::with_capacity(network_nodes.len());
2053 // Keeping track of how much value we already collected across other paths. Helps to decide
2054 // when we want to stop looking for new paths.
2055 let mut already_collected_value_msat = 0;
2057 for (_, channels) in first_hop_targets.iter_mut() {
2058 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
2062 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
2063 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
2065 // Remember how many candidates we ignored to allow for some logging afterwards.
2066 let mut num_ignored_value_contribution: u32 = 0;
2067 let mut num_ignored_path_length_limit: u32 = 0;
2068 let mut num_ignored_cltv_delta_limit: u32 = 0;
2069 let mut num_ignored_previously_failed: u32 = 0;
2070 let mut num_ignored_total_fee_limit: u32 = 0;
2071 let mut num_ignored_avoid_overpayment: u32 = 0;
2072 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
2074 macro_rules! add_entry {
2075 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
2076 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
2077 // since that value has to be transferred over this channel.
2078 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
2079 ( $candidate: expr, $next_hops_fee_msat: expr,
2080 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
2081 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
2082 // We "return" whether we updated the path at the end, and how much we can route via
2083 // this channel, via this:
2084 let mut hop_contribution_amt_msat = None;
2085 // Channels to self should not be used. This is more of belt-and-suspenders, because in
2086 // practice these cases should be caught earlier:
2087 // - for regular channels at channel announcement (TODO)
2088 // - for first and last hops early in get_route
2089 let src_node_id = $candidate.source();
2090 if Some(src_node_id) != $candidate.target() {
2091 let scid_opt = $candidate.short_channel_id();
2092 let effective_capacity = $candidate.effective_capacity();
2093 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
2095 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
2096 // It may be misleading because we might later choose to reduce the value transferred
2097 // over these channels, and the channel which was insufficient might become sufficient.
2098 // Worst case: we drop a good channel here because it can't cover the high following
2099 // fees caused by one expensive channel, but then this channel could have been used
2100 // if the amount being transferred over this path is lower.
2101 // We do this for now, but this is a subject for removal.
2102 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
2103 let used_liquidity_msat = used_liquidities
2104 .get(&$candidate.id())
2105 .map_or(0, |used_liquidity_msat| {
2106 available_value_contribution_msat = available_value_contribution_msat
2107 .saturating_sub(*used_liquidity_msat);
2108 *used_liquidity_msat
2111 // Verify the liquidity offered by this channel complies to the minimal contribution.
2112 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
2113 // Do not consider candidate hops that would exceed the maximum path length.
2114 let path_length_to_node = $next_hops_path_length + 1;
2115 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
2117 // Do not consider candidates that exceed the maximum total cltv expiry limit.
2118 // In order to already account for some of the privacy enhancing random CLTV
2119 // expiry delta offset we add on top later, we subtract a rough estimate
2120 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
2121 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
2122 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
2123 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
2124 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
2125 .saturating_add($candidate.cltv_expiry_delta());
2126 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
2128 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
2129 // Includes paying fees for the use of the following channels.
2130 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
2131 Some(result) => result,
2132 // Can't overflow due to how the values were computed right above.
2133 None => unreachable!(),
2135 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2136 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
2137 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
2139 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2140 let may_overpay_to_meet_path_minimum_msat =
2141 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
2142 recommended_value_msat >= $candidate.htlc_minimum_msat()) ||
2143 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
2144 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
2146 let payment_failed_on_this_channel = match scid_opt {
2147 Some(scid) => payment_params.previously_failed_channels.contains(&scid),
2148 None => match $candidate.blinded_hint_idx() {
2150 payment_params.previously_failed_blinded_path_idxs.contains(&(idx as u64))
2156 let (should_log_candidate, first_hop_details) = match $candidate {
2157 CandidateRouteHop::FirstHop(hop) => (true, Some(hop.details)),
2158 CandidateRouteHop::PrivateHop(_) => (true, None),
2159 CandidateRouteHop::Blinded(_) => (true, None),
2160 CandidateRouteHop::OneHopBlinded(_) => (true, None),
2164 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
2165 // bother considering this channel. If retrying with recommended_value_msat may
2166 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
2167 // around again with a higher amount.
2168 if !contributes_sufficient_value {
2169 if should_log_candidate {
2170 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
2172 if let Some(details) = first_hop_details {
2174 "First hop candidate next_outbound_htlc_limit_msat: {}",
2175 details.next_outbound_htlc_limit_msat,
2179 num_ignored_value_contribution += 1;
2180 } else if exceeds_max_path_length {
2181 if should_log_candidate {
2182 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
2184 num_ignored_path_length_limit += 1;
2185 } else if exceeds_cltv_delta_limit {
2186 if should_log_candidate {
2187 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
2189 if let Some(_) = first_hop_details {
2191 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
2192 hop_total_cltv_delta,
2193 max_total_cltv_expiry_delta,
2197 num_ignored_cltv_delta_limit += 1;
2198 } else if payment_failed_on_this_channel {
2199 if should_log_candidate {
2200 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
2202 num_ignored_previously_failed += 1;
2203 } else if may_overpay_to_meet_path_minimum_msat {
2204 if should_log_candidate {
2206 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit.",
2207 LoggedCandidateHop(&$candidate));
2209 if let Some(details) = first_hop_details {
2211 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2212 details.next_outbound_htlc_minimum_msat,
2216 num_ignored_avoid_overpayment += 1;
2217 hit_minimum_limit = true;
2218 } else if over_path_minimum_msat {
2219 // Note that low contribution here (limited by available_liquidity_msat)
2220 // might violate htlc_minimum_msat on the hops which are next along the
2221 // payment path (upstream to the payee). To avoid that, we recompute
2222 // path fees knowing the final path contribution after constructing it.
2223 let curr_min = cmp::max(
2224 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
2226 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
2227 .saturating_add(curr_min);
2228 let hm_entry = dist.entry(src_node_id);
2229 let old_entry = hm_entry.or_insert_with(|| {
2230 // If there was previously no known way to access the source node
2231 // (recall it goes payee-to-payer) of short_channel_id, first add a
2232 // semi-dummy record just to compute the fees to reach the source node.
2233 // This will affect our decision on selecting short_channel_id
2234 // as a way to reach the $candidate.target() node.
2236 candidate: $candidate.clone(),
2238 next_hops_fee_msat: u64::max_value(),
2239 hop_use_fee_msat: u64::max_value(),
2240 total_fee_msat: u64::max_value(),
2241 path_htlc_minimum_msat,
2242 path_penalty_msat: u64::max_value(),
2243 was_processed: false,
2244 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2245 value_contribution_msat,
2249 #[allow(unused_mut)] // We only use the mut in cfg(test)
2250 let mut should_process = !old_entry.was_processed;
2251 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2253 // In test/fuzzing builds, we do extra checks to make sure the skipping
2254 // of already-seen nodes only happens in cases we expect (see below).
2255 if !should_process { should_process = true; }
2259 let mut hop_use_fee_msat = 0;
2260 let mut total_fee_msat: u64 = $next_hops_fee_msat;
2262 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2263 // will have the same effective-fee
2264 if src_node_id != our_node_id {
2265 // Note that `u64::max_value` means we'll always fail the
2266 // `old_entry.total_fee_msat > total_fee_msat` check below
2267 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
2268 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2271 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2272 if total_fee_msat > max_total_routing_fee_msat {
2273 if should_log_candidate {
2274 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2276 if let Some(_) = first_hop_details {
2278 "First hop candidate routing fee: {}. Limit: {}",
2280 max_total_routing_fee_msat,
2284 num_ignored_total_fee_limit += 1;
2286 let channel_usage = ChannelUsage {
2287 amount_msat: amount_to_transfer_over_msat,
2288 inflight_htlc_msat: used_liquidity_msat,
2291 let channel_penalty_msat =
2292 scorer.channel_penalty_msat($candidate,
2295 let path_penalty_msat = $next_hops_path_penalty_msat
2296 .saturating_add(channel_penalty_msat);
2298 // Update the way of reaching $candidate.source()
2299 // with the given short_channel_id (from $candidate.target()),
2300 // if this way is cheaper than the already known
2301 // (considering the cost to "reach" this channel from the route destination,
2302 // the cost of using this channel,
2303 // and the cost of routing to the source node of this channel).
2304 // Also, consider that htlc_minimum_msat_difference, because we might end up
2305 // paying it. Consider the following exploit:
2306 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2307 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2308 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2309 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2311 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2312 // but it may require additional tracking - we don't want to double-count
2313 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2314 // can't use something that may decrease on future hops.
2315 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2316 .saturating_add(old_entry.path_penalty_msat);
2317 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2318 .saturating_add(path_penalty_msat);
2320 if !old_entry.was_processed && new_cost < old_cost {
2321 let new_graph_node = RouteGraphNode {
2322 node_id: src_node_id,
2323 score: cmp::max(total_fee_msat, path_htlc_minimum_msat).saturating_add(path_penalty_msat),
2324 total_cltv_delta: hop_total_cltv_delta,
2325 value_contribution_msat,
2326 path_length_to_node,
2328 targets.push(new_graph_node);
2329 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2330 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2331 old_entry.total_fee_msat = total_fee_msat;
2332 old_entry.candidate = $candidate.clone();
2333 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2334 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2335 old_entry.path_penalty_msat = path_penalty_msat;
2336 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2338 old_entry.value_contribution_msat = value_contribution_msat;
2340 hop_contribution_amt_msat = Some(value_contribution_msat);
2341 } else if old_entry.was_processed && new_cost < old_cost {
2342 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2344 // If we're skipping processing a node which was previously
2345 // processed even though we found another path to it with a
2346 // cheaper fee, check that it was because the second path we
2347 // found (which we are processing now) has a lower value
2348 // contribution due to an HTLC minimum limit.
2350 // e.g. take a graph with two paths from node 1 to node 2, one
2351 // through channel A, and one through channel B. Channel A and
2352 // B are both in the to-process heap, with their scores set by
2353 // a higher htlc_minimum than fee.
2354 // Channel A is processed first, and the channels onwards from
2355 // node 1 are added to the to-process heap. Thereafter, we pop
2356 // Channel B off of the heap, note that it has a much more
2357 // restrictive htlc_maximum_msat, and recalculate the fees for
2358 // all of node 1's channels using the new, reduced, amount.
2360 // This would be bogus - we'd be selecting a higher-fee path
2361 // with a lower htlc_maximum_msat instead of the one we'd
2362 // already decided to use.
2363 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2365 value_contribution_msat + path_penalty_msat <
2366 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2373 if should_log_candidate {
2375 "Ignoring {} due to its htlc_minimum_msat limit.",
2376 LoggedCandidateHop(&$candidate));
2378 if let Some(details) = first_hop_details {
2380 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2381 details.next_outbound_htlc_minimum_msat,
2385 num_ignored_htlc_minimum_msat_limit += 1;
2389 hop_contribution_amt_msat
2393 let default_node_features = default_node_features();
2395 // Find ways (channels with destination) to reach a given node and store them
2396 // in the corresponding data structures (routing graph etc).
2397 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2398 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2399 // This data can later be helpful to optimize routing (pay lower fees).
2400 macro_rules! add_entries_to_cheapest_to_target_node {
2401 ( $node: expr, $node_id: expr, $next_hops_value_contribution: expr,
2402 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2403 let fee_to_target_msat;
2404 let next_hops_path_htlc_minimum_msat;
2405 let next_hops_path_penalty_msat;
2406 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
2407 let was_processed = elem.was_processed;
2408 elem.was_processed = true;
2409 fee_to_target_msat = elem.total_fee_msat;
2410 next_hops_path_htlc_minimum_msat = elem.path_htlc_minimum_msat;
2411 next_hops_path_penalty_msat = elem.path_penalty_msat;
2414 // Entries are added to dist in add_entry!() when there is a channel from a node.
2415 // Because there are no channels from payee, it will not have a dist entry at this point.
2416 // If we're processing any other node, it is always be the result of a channel from it.
2417 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2418 fee_to_target_msat = 0;
2419 next_hops_path_htlc_minimum_msat = 0;
2420 next_hops_path_penalty_msat = 0;
2425 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
2426 for details in first_channels {
2427 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2428 details, payer_node_id: &our_node_id,
2430 add_entry!(&candidate, fee_to_target_msat,
2431 $next_hops_value_contribution,
2432 next_hops_path_htlc_minimum_msat, next_hops_path_penalty_msat,
2433 $next_hops_cltv_delta, $next_hops_path_length);
2437 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2440 &default_node_features
2443 if !features.requires_unknown_bits() {
2444 for chan_id in $node.channels.iter() {
2445 let chan = network_channels.get(chan_id).unwrap();
2446 if !chan.features.requires_unknown_bits() {
2447 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2448 if first_hops.is_none() || *source != our_node_id {
2449 if directed_channel.direction().enabled {
2450 let candidate = CandidateRouteHop::PublicHop(PublicHopCandidate {
2451 info: directed_channel,
2452 short_channel_id: *chan_id,
2454 add_entry!(&candidate,
2456 $next_hops_value_contribution,
2457 next_hops_path_htlc_minimum_msat,
2458 next_hops_path_penalty_msat,
2459 $next_hops_cltv_delta, $next_hops_path_length);
2470 let mut payment_paths = Vec::<PaymentPath>::new();
2472 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2473 'paths_collection: loop {
2474 // For every new path, start from scratch, except for used_liquidities, which
2475 // helps to avoid reusing previously selected paths in future iterations.
2478 hit_minimum_limit = false;
2480 // If first hop is a private channel and the only way to reach the payee, this is the only
2481 // place where it could be added.
2482 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2483 for details in first_channels {
2484 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2485 details, payer_node_id: &our_node_id,
2487 let added = add_entry!(&candidate, 0, path_value_msat,
2488 0, 0u64, 0, 0).is_some();
2489 log_trace!(logger, "{} direct route to payee via {}",
2490 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2494 // Add the payee as a target, so that the payee-to-payer
2495 // search algorithm knows what to start with.
2496 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2497 // The payee is not in our network graph, so nothing to add here.
2498 // There is still a chance of reaching them via last_hops though,
2499 // so don't yet fail the payment here.
2500 // If not, targets.pop() will not even let us enter the loop in step 2.
2503 add_entries_to_cheapest_to_target_node!(node, payee, path_value_msat, 0, 0);
2508 // If a caller provided us with last hops, add them to routing targets. Since this happens
2509 // earlier than general path finding, they will be somewhat prioritized, although currently
2510 // it matters only if the fees are exactly the same.
2511 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2512 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2513 let have_intro_node_in_graph =
2514 // Only add the hops in this route to our candidate set if either
2515 // we have a direct channel to the first hop or the first hop is
2516 // in the regular network graph.
2517 first_hop_targets.get(&intro_node_id).is_some() ||
2518 network_nodes.get(&intro_node_id).is_some();
2519 if !have_intro_node_in_graph || our_node_id == intro_node_id { continue }
2520 let candidate = if hint.1.blinded_hops.len() == 1 {
2521 CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, hint_idx })
2522 } else { CandidateRouteHop::Blinded(BlindedPathCandidate { hint, hint_idx }) };
2523 let mut path_contribution_msat = path_value_msat;
2524 if let Some(hop_used_msat) = add_entry!(&candidate,
2525 0, path_contribution_msat, 0, 0_u64, 0, 0)
2527 path_contribution_msat = hop_used_msat;
2529 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2530 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2532 for details in first_channels {
2533 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2534 details, payer_node_id: &our_node_id,
2536 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2540 let path_min = candidate.htlc_minimum_msat().saturating_add(
2541 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2542 add_entry!(&first_hop_candidate, blinded_path_fee,
2543 path_contribution_msat, path_min, 0_u64, candidate.cltv_expiry_delta(),
2544 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2548 for route in payment_params.payee.unblinded_route_hints().iter()
2549 .filter(|route| !route.0.is_empty())
2551 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2552 let first_hop_src_is_reachable =
2553 // Only add the hops in this route to our candidate set if either we are part of
2554 // the first hop, we have a direct channel to the first hop, or the first hop is in
2555 // the regular network graph.
2556 our_node_id == first_hop_src_id ||
2557 first_hop_targets.get(&first_hop_src_id).is_some() ||
2558 network_nodes.get(&first_hop_src_id).is_some();
2559 if first_hop_src_is_reachable {
2560 // We start building the path from reverse, i.e., from payee
2561 // to the first RouteHintHop in the path.
2562 let hop_iter = route.0.iter().rev();
2563 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2564 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2565 let mut hop_used = true;
2566 let mut aggregate_next_hops_fee_msat: u64 = 0;
2567 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2568 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2569 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2570 let mut aggregate_next_hops_path_length: u8 = 0;
2571 let mut aggregate_path_contribution_msat = path_value_msat;
2573 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2574 let target = private_hop_key_cache.get(&prev_hop_id).unwrap();
2576 if let Some(first_channels) = first_hop_targets.get(&target) {
2577 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2578 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2579 hop.short_channel_id);
2584 let candidate = network_channels
2585 .get(&hop.short_channel_id)
2586 .and_then(|channel| channel.as_directed_to(&target))
2587 .map(|(info, _)| CandidateRouteHop::PublicHop(PublicHopCandidate {
2589 short_channel_id: hop.short_channel_id,
2591 .unwrap_or_else(|| CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: hop, target_node_id: target }));
2593 if let Some(hop_used_msat) = add_entry!(&candidate,
2594 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2595 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2596 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2598 aggregate_path_contribution_msat = hop_used_msat;
2600 // If this hop was not used then there is no use checking the preceding
2601 // hops in the RouteHint. We can break by just searching for a direct
2602 // channel between last checked hop and first_hop_targets.
2606 let used_liquidity_msat = used_liquidities
2607 .get(&candidate.id()).copied()
2609 let channel_usage = ChannelUsage {
2610 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2611 inflight_htlc_msat: used_liquidity_msat,
2612 effective_capacity: candidate.effective_capacity(),
2614 let channel_penalty_msat = scorer.channel_penalty_msat(
2615 &candidate, channel_usage, score_params
2617 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2618 .saturating_add(channel_penalty_msat);
2620 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2621 .saturating_add(hop.cltv_expiry_delta as u32);
2623 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2626 // Searching for a direct channel between last checked hop and first_hop_targets
2627 if let Some(first_channels) = first_hop_targets.get_mut(&target) {
2628 sort_first_hop_channels(first_channels, &used_liquidities,
2629 recommended_value_msat, our_node_pubkey);
2630 for details in first_channels {
2631 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2632 details, payer_node_id: &our_node_id,
2634 add_entry!(&first_hop_candidate,
2635 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2636 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2637 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2645 // In the next values of the iterator, the aggregate fees already reflects
2646 // the sum of value sent from payer (final_value_msat) and routing fees
2647 // for the last node in the RouteHint. We need to just add the fees to
2648 // route through the current node so that the preceding node (next iteration)
2650 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2651 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2652 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2654 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2655 // this route hint's source node to forward said min over this channel.
2656 aggregate_next_hops_path_htlc_minimum_msat = {
2657 let curr_htlc_min = cmp::max(
2658 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2660 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2661 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2664 if idx == route.0.len() - 1 {
2665 // The last hop in this iterator is the first hop in
2666 // overall RouteHint.
2667 // If this hop connects to a node with which we have a direct channel,
2668 // ignore the network graph and, if the last hop was added, add our
2669 // direct channel to the candidate set.
2671 // Note that we *must* check if the last hop was added as `add_entry`
2672 // always assumes that the third argument is a node to which we have a
2674 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2675 sort_first_hop_channels(first_channels, &used_liquidities,
2676 recommended_value_msat, our_node_pubkey);
2677 for details in first_channels {
2678 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2679 details, payer_node_id: &our_node_id,
2681 add_entry!(&first_hop_candidate,
2682 aggregate_next_hops_fee_msat,
2683 aggregate_path_contribution_msat,
2684 aggregate_next_hops_path_htlc_minimum_msat,
2685 aggregate_next_hops_path_penalty_msat,
2686 aggregate_next_hops_cltv_delta,
2687 aggregate_next_hops_path_length);
2695 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2697 // At this point, targets are filled with the data from first and
2698 // last hops communicated by the caller, and the payment receiver.
2699 let mut found_new_path = false;
2702 // If this loop terminates due the exhaustion of targets, two situations are possible:
2703 // - not enough outgoing liquidity:
2704 // 0 < already_collected_value_msat < final_value_msat
2705 // - enough outgoing liquidity:
2706 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2707 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2708 // paths_collection will be stopped because found_new_path==false.
2709 // This is not necessarily a routing failure.
2710 'path_construction: while let Some(RouteGraphNode { node_id, total_cltv_delta, mut value_contribution_msat, path_length_to_node, .. }) = targets.pop() {
2712 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2713 // traversing the graph and arrange the path out of what we found.
2714 if node_id == our_node_id {
2715 let mut new_entry = dist.remove(&our_node_id).unwrap();
2716 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2719 let mut features_set = false;
2720 let target = ordered_hops.last().unwrap().0.candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2721 if let Some(first_channels) = first_hop_targets.get(&target) {
2722 for details in first_channels {
2723 if let CandidateRouteHop::FirstHop(FirstHopCandidate { details: last_hop_details, .. })
2724 = ordered_hops.last().unwrap().0.candidate
2726 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2727 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2728 features_set = true;
2735 if let Some(node) = network_nodes.get(&target) {
2736 if let Some(node_info) = node.announcement_info.as_ref() {
2737 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2739 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2742 // We can fill in features for everything except hops which were
2743 // provided via the invoice we're paying. We could guess based on the
2744 // recipient's features but for now we simply avoid guessing at all.
2748 // Means we succesfully traversed from the payer to the payee, now
2749 // save this path for the payment route. Also, update the liquidity
2750 // remaining on the used hops, so that we take them into account
2751 // while looking for more paths.
2752 if target == maybe_dummy_payee_node_id {
2756 new_entry = match dist.remove(&target) {
2757 Some(payment_hop) => payment_hop,
2758 // We can't arrive at None because, if we ever add an entry to targets,
2759 // we also fill in the entry in dist (see add_entry!).
2760 None => unreachable!(),
2762 // We "propagate" the fees one hop backward (topologically) here,
2763 // so that fees paid for a HTLC forwarding on the current channel are
2764 // associated with the previous channel (where they will be subtracted).
2765 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2766 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2768 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2769 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2771 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2772 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2774 let mut payment_path = PaymentPath {hops: ordered_hops};
2776 // We could have possibly constructed a slightly inconsistent path: since we reduce
2777 // value being transferred along the way, we could have violated htlc_minimum_msat
2778 // on some channels we already passed (assuming dest->source direction). Here, we
2779 // recompute the fees again, so that if that's the case, we match the currently
2780 // underpaid htlc_minimum_msat with fees.
2781 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2782 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2783 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2785 // Since a path allows to transfer as much value as
2786 // the smallest channel it has ("bottleneck"), we should recompute
2787 // the fees so sender HTLC don't overpay fees when traversing
2788 // larger channels than the bottleneck. This may happen because
2789 // when we were selecting those channels we were not aware how much value
2790 // this path will transfer, and the relative fee for them
2791 // might have been computed considering a larger value.
2792 // Remember that we used these channels so that we don't rely
2793 // on the same liquidity in future paths.
2794 let mut prevented_redundant_path_selection = false;
2795 for (hop, _) in payment_path.hops.iter() {
2796 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2797 let used_liquidity_msat = used_liquidities
2798 .entry(hop.candidate.id())
2799 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2800 .or_insert(spent_on_hop_msat);
2801 let hop_capacity = hop.candidate.effective_capacity();
2802 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2803 if *used_liquidity_msat == hop_max_msat {
2804 // If this path used all of this channel's available liquidity, we know
2805 // this path will not be selected again in the next loop iteration.
2806 prevented_redundant_path_selection = true;
2808 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2810 if !prevented_redundant_path_selection {
2811 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2812 // we'll probably end up picking the same path again on the next iteration.
2813 // Decrease the available liquidity of a hop in the middle of the path.
2814 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2815 let exhausted = u64::max_value();
2817 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2818 LoggedCandidateHop(victim_candidate));
2819 if let Some(scid) = victim_candidate.short_channel_id() {
2820 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2821 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2825 // Track the total amount all our collected paths allow to send so that we know
2826 // when to stop looking for more paths
2827 already_collected_value_msat += value_contribution_msat;
2829 payment_paths.push(payment_path);
2830 found_new_path = true;
2831 break 'path_construction;
2834 // If we found a path back to the payee, we shouldn't try to process it again. This is
2835 // the equivalent of the `elem.was_processed` check in
2836 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2837 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2839 // Otherwise, since the current target node is not us,
2840 // keep "unrolling" the payment graph from payee to payer by
2841 // finding a way to reach the current target from the payer side.
2842 match network_nodes.get(&node_id) {
2845 add_entries_to_cheapest_to_target_node!(node, node_id,
2846 value_contribution_msat,
2847 total_cltv_delta, path_length_to_node);
2853 if !found_new_path && channel_saturation_pow_half != 0 {
2854 channel_saturation_pow_half = 0;
2855 continue 'paths_collection;
2857 // If we don't support MPP, no use trying to gather more value ever.
2858 break 'paths_collection;
2862 // Stop either when the recommended value is reached or if no new path was found in this
2864 // In the latter case, making another path finding attempt won't help,
2865 // because we deterministically terminated the search due to low liquidity.
2866 if !found_new_path && channel_saturation_pow_half != 0 {
2867 channel_saturation_pow_half = 0;
2868 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2869 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
2870 path_value_msat = recommended_value_msat;
2871 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2872 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2873 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2874 break 'paths_collection;
2875 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2876 // Further, if this was our first walk of the graph, and we weren't limited by an
2877 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2878 // limited by an htlc_minimum_msat value, find another path with a higher value,
2879 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2880 // still keeping a lower total fee than this path.
2881 if !hit_minimum_limit {
2882 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2883 break 'paths_collection;
2885 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.");
2886 path_value_msat = recommended_value_msat;
2890 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2891 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
2892 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
2893 num_ignored_total_fee_limit;
2894 if num_ignored_total > 0 {
2896 "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.",
2897 num_ignored_value_contribution, num_ignored_path_length_limit,
2898 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
2899 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
2900 num_ignored_total_fee_limit, num_ignored_total);
2904 if payment_paths.len() == 0 {
2905 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2908 if already_collected_value_msat < final_value_msat {
2909 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2913 let mut selected_route = payment_paths;
2915 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2916 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2918 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2919 // the value they contribute towards the payment amount.
2920 // We sort in descending order as we will remove from the front in `retain`, next.
2921 selected_route.sort_unstable_by(|a, b|
2922 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2923 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2926 // We should make sure that at least 1 path left.
2927 let mut paths_left = selected_route.len();
2928 selected_route.retain(|path| {
2929 if paths_left == 1 {
2932 let path_value_msat = path.get_value_msat();
2933 if path_value_msat <= overpaid_value_msat {
2934 overpaid_value_msat -= path_value_msat;
2940 debug_assert!(selected_route.len() > 0);
2942 if overpaid_value_msat != 0 {
2944 // Now, subtract the remaining overpaid value from the most-expensive path.
2945 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2946 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2947 selected_route.sort_unstable_by(|a, b| {
2948 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2949 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2950 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2952 let expensive_payment_path = selected_route.first_mut().unwrap();
2954 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2955 // can't go negative.
2956 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2957 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2961 // Sort by the path itself and combine redundant paths.
2962 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2963 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2965 selected_route.sort_unstable_by_key(|path| {
2966 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2967 debug_assert!(path.hops.len() <= key.len());
2968 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
2973 for idx in 0..(selected_route.len() - 1) {
2974 if idx + 1 >= selected_route.len() { break; }
2975 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
2976 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
2977 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2978 selected_route[idx].update_value_and_recompute_fees(new_value);
2979 selected_route.remove(idx + 1);
2983 let mut paths = Vec::new();
2984 for payment_path in selected_route {
2985 let mut hops = Vec::with_capacity(payment_path.hops.len());
2986 for (hop, node_features) in payment_path.hops.iter()
2987 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2989 let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
2990 let maybe_announced_channel = if let CandidateRouteHop::PublicHop(_) = hop.candidate {
2991 // If we sourced the hop from the graph we're sure the target node is announced.
2993 } else if let CandidateRouteHop::FirstHop(first_hop) = &hop.candidate {
2994 // If this is a first hop we also know if it's announced.
2995 first_hop.details.is_public
2997 // If we sourced it any other way, we double-check the network graph to see if
2998 // there are announced channels between the endpoints. If so, the hop might be
2999 // referring to any of the announced channels, as its `short_channel_id` might be
3000 // an alias, in which case we don't take any chances here.
3001 network_graph.node(&target).map_or(false, |hop_node|
3002 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
3003 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
3007 hops.push(RouteHop {
3008 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
3009 node_features: node_features.clone(),
3010 short_channel_id: hop.candidate.short_channel_id().unwrap(),
3011 channel_features: hop.candidate.features(),
3012 fee_msat: hop.fee_msat,
3013 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
3014 maybe_announced_channel,
3017 let mut final_cltv_delta = final_cltv_expiry_delta;
3018 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
3019 if let Some(blinded_path) = h.candidate.blinded_path() {
3020 final_cltv_delta = h.candidate.cltv_expiry_delta();
3022 hops: blinded_path.blinded_hops.clone(),
3023 blinding_point: blinded_path.blinding_point,
3024 excess_final_cltv_expiry_delta: 0,
3025 final_value_msat: h.fee_msat,
3029 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
3030 // applicable for the previous hop.
3031 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
3032 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
3035 paths.push(Path { hops, blinded_tail });
3037 // Make sure we would never create a route with more paths than we allow.
3038 debug_assert!(paths.len() <= payment_params.max_path_count.into());
3040 if let Some(node_features) = payment_params.payee.node_features() {
3041 for path in paths.iter_mut() {
3042 path.hops.last_mut().unwrap().node_features = node_features.clone();
3046 let route = Route { paths, route_params: Some(route_params.clone()) };
3048 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
3049 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
3050 if route.get_total_fees() > max_total_routing_fee_msat {
3051 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
3052 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
3056 log_info!(logger, "Got route: {}", log_route!(route));
3060 // When an adversarial intermediary node observes a payment, it may be able to infer its
3061 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
3062 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
3063 // payment path by adding a randomized 'shadow route' offset to the final hop.
3064 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
3065 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
3067 let network_channels = network_graph.channels();
3068 let network_nodes = network_graph.nodes();
3070 for path in route.paths.iter_mut() {
3071 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
3073 // Remember the last three nodes of the random walk and avoid looping back on them.
3074 // Init with the last three nodes from the actual path, if possible.
3075 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
3076 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
3077 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
3079 // Choose the last publicly known node as the starting point for the random walk.
3080 let mut cur_hop: Option<NodeId> = None;
3081 let mut path_nonce = [0u8; 12];
3082 if let Some(starting_hop) = path.hops.iter().rev()
3083 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
3084 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
3085 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
3088 // Init PRNG with the path-dependant nonce, which is static for private paths.
3089 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
3090 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
3092 // Pick a random path length in [1 .. 3]
3093 prng.process_in_place(&mut random_path_bytes);
3094 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
3096 for random_hop in 0..random_walk_length {
3097 // If we don't find a suitable offset in the public network graph, we default to
3098 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3099 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
3101 if let Some(cur_node_id) = cur_hop {
3102 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
3103 // Randomly choose the next unvisited hop.
3104 prng.process_in_place(&mut random_path_bytes);
3105 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
3106 .checked_rem(cur_node.channels.len())
3107 .and_then(|index| cur_node.channels.get(index))
3108 .and_then(|id| network_channels.get(id)) {
3109 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
3110 if !nodes_to_avoid.iter().any(|x| x == next_id) {
3111 nodes_to_avoid[random_hop] = *next_id;
3112 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
3113 cur_hop = Some(*next_id);
3120 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
3121 .checked_add(random_hop_offset)
3122 .unwrap_or(shadow_ctlv_expiry_delta_offset);
3125 // Limit the total offset to reduce the worst-case locked liquidity timevalue
3126 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
3127 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
3129 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
3130 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3131 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
3132 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
3133 max_path_offset = cmp::max(
3134 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
3135 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
3136 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
3138 // Add 'shadow' CLTV offset to the final hop
3139 if let Some(tail) = path.blinded_tail.as_mut() {
3140 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
3141 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
3143 if let Some(last_hop) = path.hops.last_mut() {
3144 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
3145 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
3150 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
3151 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
3153 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
3154 pub fn build_route_from_hops<L: Deref, GL: Deref>(
3155 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3156 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
3157 ) -> Result<Route, LightningError>
3158 where L::Target: Logger, GL::Target: Logger {
3159 let graph_lock = network_graph.read_only();
3160 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
3161 &graph_lock, logger, random_seed_bytes)?;
3162 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
3166 fn build_route_from_hops_internal<L: Deref>(
3167 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3168 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
3169 ) -> Result<Route, LightningError> where L::Target: Logger {
3172 our_node_id: NodeId,
3173 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
3176 impl ScoreLookUp for HopScorer {
3177 type ScoreParams = ();
3178 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
3179 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
3181 let mut cur_id = self.our_node_id;
3182 for i in 0..self.hop_ids.len() {
3183 if let Some(next_id) = self.hop_ids[i] {
3184 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
3196 impl<'a> Writeable for HopScorer {
3198 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
3203 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
3204 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
3207 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
3208 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
3209 for i in 0..hops.len() {
3210 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
3213 let scorer = HopScorer { our_node_id, hop_ids };
3215 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
3220 use crate::blinded_path::{BlindedHop, BlindedPath};
3221 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
3222 use crate::routing::utxo::UtxoResult;
3223 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
3224 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
3225 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop, PublicHopCandidate};
3226 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
3227 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
3228 use crate::chain::transaction::OutPoint;
3229 use crate::sign::EntropySource;
3230 use crate::ln::ChannelId;
3231 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
3232 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
3233 use crate::ln::channelmanager;
3234 use crate::offers::invoice::BlindedPayInfo;
3235 use crate::util::config::UserConfig;
3236 use crate::util::test_utils as ln_test_utils;
3237 use crate::util::chacha20::ChaCha20;
3238 use crate::util::ser::{Readable, Writeable};
3240 use crate::util::ser::Writer;
3242 use bitcoin::hashes::Hash;
3243 use bitcoin::network::constants::Network;
3244 use bitcoin::blockdata::constants::ChainHash;
3245 use bitcoin::blockdata::script::Builder;
3246 use bitcoin::blockdata::opcodes;
3247 use bitcoin::blockdata::transaction::TxOut;
3248 use bitcoin::hashes::hex::FromHex;
3249 use bitcoin::secp256k1::{PublicKey,SecretKey};
3250 use bitcoin::secp256k1::Secp256k1;
3252 use crate::io::Cursor;
3253 use crate::prelude::*;
3254 use crate::sync::Arc;
3256 use core::convert::TryInto;
3258 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3259 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
3260 channelmanager::ChannelDetails {
3261 channel_id: ChannelId::new_zero(),
3262 counterparty: channelmanager::ChannelCounterparty {
3265 unspendable_punishment_reserve: 0,
3266 forwarding_info: None,
3267 outbound_htlc_minimum_msat: None,
3268 outbound_htlc_maximum_msat: None,
3270 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3273 outbound_scid_alias: None,
3274 inbound_scid_alias: None,
3275 channel_value_satoshis: 0,
3278 outbound_capacity_msat,
3279 next_outbound_htlc_limit_msat: outbound_capacity_msat,
3280 next_outbound_htlc_minimum_msat: 0,
3281 inbound_capacity_msat: 42,
3282 unspendable_punishment_reserve: None,
3283 confirmations_required: None,
3284 confirmations: None,
3285 force_close_spend_delay: None,
3286 is_outbound: true, is_channel_ready: true,
3287 is_usable: true, is_public: true,
3288 inbound_htlc_minimum_msat: None,
3289 inbound_htlc_maximum_msat: None,
3291 feerate_sat_per_1000_weight: None,
3292 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
3297 fn simple_route_test() {
3298 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3299 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3300 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3301 let scorer = ln_test_utils::TestScorer::new();
3302 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3303 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3305 // Simple route to 2 via 1
3307 let route_params = RouteParameters::from_payment_params_and_value(
3308 payment_params.clone(), 0);
3309 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3310 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3311 &Default::default(), &random_seed_bytes) {
3312 assert_eq!(err, "Cannot send a payment of 0 msat");
3313 } else { panic!(); }
3315 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3316 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3317 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3318 assert_eq!(route.paths[0].hops.len(), 2);
3320 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3321 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3322 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3323 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3324 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3325 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3327 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3328 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3329 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3330 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3331 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3332 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3336 fn invalid_first_hop_test() {
3337 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3338 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3339 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3340 let scorer = ln_test_utils::TestScorer::new();
3341 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3342 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3344 // Simple route to 2 via 1
3346 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3348 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3349 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3350 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3351 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3352 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3353 } else { panic!(); }
3355 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3356 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3357 assert_eq!(route.paths[0].hops.len(), 2);
3361 fn htlc_minimum_test() {
3362 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3363 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3364 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3365 let scorer = ln_test_utils::TestScorer::new();
3366 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3367 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3369 // Simple route to 2 via 1
3371 // Disable other paths
3372 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3373 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3374 short_channel_id: 12,
3376 flags: 2, // to disable
3377 cltv_expiry_delta: 0,
3378 htlc_minimum_msat: 0,
3379 htlc_maximum_msat: MAX_VALUE_MSAT,
3381 fee_proportional_millionths: 0,
3382 excess_data: Vec::new()
3384 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3385 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3386 short_channel_id: 3,
3388 flags: 2, // to disable
3389 cltv_expiry_delta: 0,
3390 htlc_minimum_msat: 0,
3391 htlc_maximum_msat: MAX_VALUE_MSAT,
3393 fee_proportional_millionths: 0,
3394 excess_data: Vec::new()
3396 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3397 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3398 short_channel_id: 13,
3400 flags: 2, // to disable
3401 cltv_expiry_delta: 0,
3402 htlc_minimum_msat: 0,
3403 htlc_maximum_msat: MAX_VALUE_MSAT,
3405 fee_proportional_millionths: 0,
3406 excess_data: Vec::new()
3408 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3409 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3410 short_channel_id: 6,
3412 flags: 2, // to disable
3413 cltv_expiry_delta: 0,
3414 htlc_minimum_msat: 0,
3415 htlc_maximum_msat: MAX_VALUE_MSAT,
3417 fee_proportional_millionths: 0,
3418 excess_data: Vec::new()
3420 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3421 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3422 short_channel_id: 7,
3424 flags: 2, // to disable
3425 cltv_expiry_delta: 0,
3426 htlc_minimum_msat: 0,
3427 htlc_maximum_msat: MAX_VALUE_MSAT,
3429 fee_proportional_millionths: 0,
3430 excess_data: Vec::new()
3433 // Check against amount_to_transfer_over_msat.
3434 // Set minimal HTLC of 200_000_000 msat.
3435 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3436 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3437 short_channel_id: 2,
3440 cltv_expiry_delta: 0,
3441 htlc_minimum_msat: 200_000_000,
3442 htlc_maximum_msat: MAX_VALUE_MSAT,
3444 fee_proportional_millionths: 0,
3445 excess_data: Vec::new()
3448 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3450 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3451 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3452 short_channel_id: 4,
3455 cltv_expiry_delta: 0,
3456 htlc_minimum_msat: 0,
3457 htlc_maximum_msat: 199_999_999,
3459 fee_proportional_millionths: 0,
3460 excess_data: Vec::new()
3463 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3464 let route_params = RouteParameters::from_payment_params_and_value(
3465 payment_params, 199_999_999);
3466 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3467 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3468 &Default::default(), &random_seed_bytes) {
3469 assert_eq!(err, "Failed to find a path to the given destination");
3470 } else { panic!(); }
3472 // Lift the restriction on the first hop.
3473 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3474 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3475 short_channel_id: 2,
3478 cltv_expiry_delta: 0,
3479 htlc_minimum_msat: 0,
3480 htlc_maximum_msat: MAX_VALUE_MSAT,
3482 fee_proportional_millionths: 0,
3483 excess_data: Vec::new()
3486 // A payment above the minimum should pass
3487 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3488 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3489 assert_eq!(route.paths[0].hops.len(), 2);
3493 fn htlc_minimum_overpay_test() {
3494 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3495 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3496 let config = UserConfig::default();
3497 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3498 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3500 let scorer = ln_test_utils::TestScorer::new();
3501 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3502 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3504 // A route to node#2 via two paths.
3505 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3506 // Thus, they can't send 60 without overpaying.
3507 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3508 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3509 short_channel_id: 2,
3512 cltv_expiry_delta: 0,
3513 htlc_minimum_msat: 35_000,
3514 htlc_maximum_msat: 40_000,
3516 fee_proportional_millionths: 0,
3517 excess_data: Vec::new()
3519 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3520 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3521 short_channel_id: 12,
3524 cltv_expiry_delta: 0,
3525 htlc_minimum_msat: 35_000,
3526 htlc_maximum_msat: 40_000,
3528 fee_proportional_millionths: 0,
3529 excess_data: Vec::new()
3533 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3534 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3535 short_channel_id: 13,
3538 cltv_expiry_delta: 0,
3539 htlc_minimum_msat: 0,
3540 htlc_maximum_msat: MAX_VALUE_MSAT,
3542 fee_proportional_millionths: 0,
3543 excess_data: Vec::new()
3545 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3546 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3547 short_channel_id: 4,
3550 cltv_expiry_delta: 0,
3551 htlc_minimum_msat: 0,
3552 htlc_maximum_msat: MAX_VALUE_MSAT,
3554 fee_proportional_millionths: 0,
3555 excess_data: Vec::new()
3558 // Disable other paths
3559 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3560 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3561 short_channel_id: 1,
3563 flags: 2, // to disable
3564 cltv_expiry_delta: 0,
3565 htlc_minimum_msat: 0,
3566 htlc_maximum_msat: MAX_VALUE_MSAT,
3568 fee_proportional_millionths: 0,
3569 excess_data: Vec::new()
3572 let mut route_params = RouteParameters::from_payment_params_and_value(
3573 payment_params.clone(), 60_000);
3574 route_params.max_total_routing_fee_msat = Some(15_000);
3575 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3576 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3577 // Overpay fees to hit htlc_minimum_msat.
3578 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3579 // TODO: this could be better balanced to overpay 10k and not 15k.
3580 assert_eq!(overpaid_fees, 15_000);
3582 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3583 // while taking even more fee to match htlc_minimum_msat.
3584 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3585 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3586 short_channel_id: 12,
3589 cltv_expiry_delta: 0,
3590 htlc_minimum_msat: 65_000,
3591 htlc_maximum_msat: 80_000,
3593 fee_proportional_millionths: 0,
3594 excess_data: Vec::new()
3596 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3597 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3598 short_channel_id: 2,
3601 cltv_expiry_delta: 0,
3602 htlc_minimum_msat: 0,
3603 htlc_maximum_msat: MAX_VALUE_MSAT,
3605 fee_proportional_millionths: 0,
3606 excess_data: Vec::new()
3608 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3609 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3610 short_channel_id: 4,
3613 cltv_expiry_delta: 0,
3614 htlc_minimum_msat: 0,
3615 htlc_maximum_msat: MAX_VALUE_MSAT,
3617 fee_proportional_millionths: 100_000,
3618 excess_data: Vec::new()
3621 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3622 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3623 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3624 assert_eq!(route.paths.len(), 1);
3625 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3626 let fees = route.paths[0].hops[0].fee_msat;
3627 assert_eq!(fees, 5_000);
3629 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
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 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3633 // the other channel.
3634 assert_eq!(route.paths.len(), 1);
3635 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3636 let fees = route.paths[0].hops[0].fee_msat;
3637 assert_eq!(fees, 5_000);
3641 fn htlc_minimum_recipient_overpay_test() {
3642 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3643 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3644 let config = UserConfig::default();
3645 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3646 let scorer = ln_test_utils::TestScorer::new();
3647 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3648 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3650 // Route to node2 over a single path which requires overpaying the recipient themselves.
3652 // First disable all paths except the us -> node1 -> node2 path
3653 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3654 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3655 short_channel_id: 13,
3658 cltv_expiry_delta: 0,
3659 htlc_minimum_msat: 0,
3660 htlc_maximum_msat: 0,
3662 fee_proportional_millionths: 0,
3663 excess_data: Vec::new()
3666 // Set channel 4 to free but with a high htlc_minimum_msat
3667 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3668 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3669 short_channel_id: 4,
3672 cltv_expiry_delta: 0,
3673 htlc_minimum_msat: 15_000,
3674 htlc_maximum_msat: MAX_VALUE_MSAT,
3676 fee_proportional_millionths: 0,
3677 excess_data: Vec::new()
3680 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3681 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3682 // what we try to find a route for, so this test only just happens to work out to exactly
3684 let mut route_params = RouteParameters::from_payment_params_and_value(
3685 payment_params.clone(), 5_000);
3686 route_params.max_total_routing_fee_msat = Some(9_999);
3687 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3688 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3689 &Default::default(), &random_seed_bytes) {
3690 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3691 } else { panic!(); }
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(10_000);
3696 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3697 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3698 assert_eq!(route.get_total_fees(), 10_000);
3702 fn disable_channels_test() {
3703 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3704 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3705 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3706 let scorer = ln_test_utils::TestScorer::new();
3707 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3708 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3710 // // Disable channels 4 and 12 by flags=2
3711 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3712 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3713 short_channel_id: 4,
3715 flags: 2, // to disable
3716 cltv_expiry_delta: 0,
3717 htlc_minimum_msat: 0,
3718 htlc_maximum_msat: MAX_VALUE_MSAT,
3720 fee_proportional_millionths: 0,
3721 excess_data: Vec::new()
3723 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3724 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3725 short_channel_id: 12,
3727 flags: 2, // to disable
3728 cltv_expiry_delta: 0,
3729 htlc_minimum_msat: 0,
3730 htlc_maximum_msat: MAX_VALUE_MSAT,
3732 fee_proportional_millionths: 0,
3733 excess_data: Vec::new()
3736 // If all the channels require some features we don't understand, route should fail
3737 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3738 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3739 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3740 &Default::default(), &random_seed_bytes) {
3741 assert_eq!(err, "Failed to find a path to the given destination");
3742 } else { panic!(); }
3744 // If we specify a channel to node7, that overrides our local channel view and that gets used
3745 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3746 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3747 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3748 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3749 &Default::default(), &random_seed_bytes).unwrap();
3750 assert_eq!(route.paths[0].hops.len(), 2);
3752 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3753 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3754 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3755 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3756 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3757 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3759 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3760 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3761 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3762 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3763 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3764 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3768 fn disable_node_test() {
3769 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3770 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3771 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3772 let scorer = ln_test_utils::TestScorer::new();
3773 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3774 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3776 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3777 let mut unknown_features = NodeFeatures::empty();
3778 unknown_features.set_unknown_feature_required();
3779 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3780 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3781 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3783 // If all nodes require some features we don't understand, route should fail
3784 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3785 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3786 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3787 &Default::default(), &random_seed_bytes) {
3788 assert_eq!(err, "Failed to find a path to the given destination");
3789 } else { panic!(); }
3791 // If we specify a channel to node7, that overrides our local channel view and that gets used
3792 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3793 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3794 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3795 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3796 &Default::default(), &random_seed_bytes).unwrap();
3797 assert_eq!(route.paths[0].hops.len(), 2);
3799 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3800 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3801 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3802 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3803 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3804 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3806 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3807 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3808 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3809 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3810 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3811 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3813 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3814 // naively) assume that the user checked the feature bits on the invoice, which override
3815 // the node_announcement.
3819 fn our_chans_test() {
3820 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3821 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3822 let scorer = ln_test_utils::TestScorer::new();
3823 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3824 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3826 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3827 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3828 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3829 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3830 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3831 assert_eq!(route.paths[0].hops.len(), 3);
3833 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3834 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3835 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3836 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3837 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3838 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3840 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3841 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3842 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3843 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3844 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3845 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3847 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3848 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3849 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3850 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3851 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3852 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3854 // If we specify a channel to node7, that overrides our local channel view and that gets used
3855 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3856 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3857 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3858 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3859 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3860 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3861 &Default::default(), &random_seed_bytes).unwrap();
3862 assert_eq!(route.paths[0].hops.len(), 2);
3864 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3865 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3866 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3867 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3868 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3869 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3871 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3872 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3873 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3874 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3875 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3876 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3879 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3880 let zero_fees = RoutingFees {
3882 proportional_millionths: 0,
3884 vec![RouteHint(vec![RouteHintHop {
3885 src_node_id: nodes[3],
3886 short_channel_id: 8,
3888 cltv_expiry_delta: (8 << 4) | 1,
3889 htlc_minimum_msat: None,
3890 htlc_maximum_msat: None,
3892 ]), RouteHint(vec![RouteHintHop {
3893 src_node_id: nodes[4],
3894 short_channel_id: 9,
3897 proportional_millionths: 0,
3899 cltv_expiry_delta: (9 << 4) | 1,
3900 htlc_minimum_msat: None,
3901 htlc_maximum_msat: None,
3902 }]), RouteHint(vec![RouteHintHop {
3903 src_node_id: nodes[5],
3904 short_channel_id: 10,
3906 cltv_expiry_delta: (10 << 4) | 1,
3907 htlc_minimum_msat: None,
3908 htlc_maximum_msat: None,
3912 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3913 let zero_fees = RoutingFees {
3915 proportional_millionths: 0,
3917 vec![RouteHint(vec![RouteHintHop {
3918 src_node_id: nodes[2],
3919 short_channel_id: 5,
3922 proportional_millionths: 0,
3924 cltv_expiry_delta: (5 << 4) | 1,
3925 htlc_minimum_msat: None,
3926 htlc_maximum_msat: None,
3928 src_node_id: nodes[3],
3929 short_channel_id: 8,
3931 cltv_expiry_delta: (8 << 4) | 1,
3932 htlc_minimum_msat: None,
3933 htlc_maximum_msat: None,
3935 ]), RouteHint(vec![RouteHintHop {
3936 src_node_id: nodes[4],
3937 short_channel_id: 9,
3940 proportional_millionths: 0,
3942 cltv_expiry_delta: (9 << 4) | 1,
3943 htlc_minimum_msat: None,
3944 htlc_maximum_msat: None,
3945 }]), RouteHint(vec![RouteHintHop {
3946 src_node_id: nodes[5],
3947 short_channel_id: 10,
3949 cltv_expiry_delta: (10 << 4) | 1,
3950 htlc_minimum_msat: None,
3951 htlc_maximum_msat: None,
3956 fn partial_route_hint_test() {
3957 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3958 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3959 let scorer = ln_test_utils::TestScorer::new();
3960 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3961 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3963 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3964 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3965 // RouteHint may be partially used by the algo to build the best path.
3967 // First check that last hop can't have its source as the payee.
3968 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3969 src_node_id: nodes[6],
3970 short_channel_id: 8,
3973 proportional_millionths: 0,
3975 cltv_expiry_delta: (8 << 4) | 1,
3976 htlc_minimum_msat: None,
3977 htlc_maximum_msat: None,
3980 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3981 invalid_last_hops.push(invalid_last_hop);
3983 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3984 .with_route_hints(invalid_last_hops).unwrap();
3985 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3986 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3987 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3988 &Default::default(), &random_seed_bytes) {
3989 assert_eq!(err, "Route hint cannot have the payee as the source.");
3990 } else { panic!(); }
3993 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3994 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3995 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3996 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3997 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3998 assert_eq!(route.paths[0].hops.len(), 5);
4000 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4001 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4002 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4003 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4004 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4005 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4007 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4008 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4009 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4010 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4011 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4012 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4014 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4015 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4016 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4017 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4018 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4019 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4021 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4022 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4023 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4024 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4025 // If we have a peer in the node map, we'll use their features here since we don't have
4026 // a way of figuring out their features from the invoice:
4027 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4028 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4030 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4031 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4032 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4033 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4034 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4035 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4038 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4039 let zero_fees = RoutingFees {
4041 proportional_millionths: 0,
4043 vec![RouteHint(vec![RouteHintHop {
4044 src_node_id: nodes[3],
4045 short_channel_id: 8,
4047 cltv_expiry_delta: (8 << 4) | 1,
4048 htlc_minimum_msat: None,
4049 htlc_maximum_msat: None,
4050 }]), RouteHint(vec![
4052 ]), RouteHint(vec![RouteHintHop {
4053 src_node_id: nodes[5],
4054 short_channel_id: 10,
4056 cltv_expiry_delta: (10 << 4) | 1,
4057 htlc_minimum_msat: None,
4058 htlc_maximum_msat: None,
4063 fn ignores_empty_last_hops_test() {
4064 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4065 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4066 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
4067 let scorer = ln_test_utils::TestScorer::new();
4068 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4069 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4071 // Test handling of an empty RouteHint passed in Invoice.
4072 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4073 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4074 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4075 assert_eq!(route.paths[0].hops.len(), 5);
4077 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4078 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4079 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4080 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4081 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4082 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4084 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4085 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4086 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4087 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4088 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4089 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4091 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4092 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4093 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4094 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4095 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4096 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4098 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4099 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4100 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4101 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4102 // If we have a peer in the node map, we'll use their features here since we don't have
4103 // a way of figuring out their features from the invoice:
4104 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4105 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4107 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4108 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4109 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4110 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4111 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4112 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4115 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
4117 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
4118 let zero_fees = RoutingFees {
4120 proportional_millionths: 0,
4122 vec![RouteHint(vec![RouteHintHop {
4123 src_node_id: hint_hops[0],
4124 short_channel_id: 0xff00,
4127 proportional_millionths: 0,
4129 cltv_expiry_delta: (5 << 4) | 1,
4130 htlc_minimum_msat: None,
4131 htlc_maximum_msat: None,
4133 src_node_id: hint_hops[1],
4134 short_channel_id: 0xff01,
4136 cltv_expiry_delta: (8 << 4) | 1,
4137 htlc_minimum_msat: None,
4138 htlc_maximum_msat: None,
4143 fn multi_hint_last_hops_test() {
4144 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4145 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4146 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
4147 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4148 let scorer = ln_test_utils::TestScorer::new();
4149 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4150 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4151 // Test through channels 2, 3, 0xff00, 0xff01.
4152 // Test shows that multiple hop hints are considered.
4154 // Disabling channels 6 & 7 by flags=2
4155 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4156 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4157 short_channel_id: 6,
4159 flags: 2, // to disable
4160 cltv_expiry_delta: 0,
4161 htlc_minimum_msat: 0,
4162 htlc_maximum_msat: MAX_VALUE_MSAT,
4164 fee_proportional_millionths: 0,
4165 excess_data: Vec::new()
4167 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4168 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4169 short_channel_id: 7,
4171 flags: 2, // to disable
4172 cltv_expiry_delta: 0,
4173 htlc_minimum_msat: 0,
4174 htlc_maximum_msat: MAX_VALUE_MSAT,
4176 fee_proportional_millionths: 0,
4177 excess_data: Vec::new()
4180 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4181 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4182 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4183 assert_eq!(route.paths[0].hops.len(), 4);
4185 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4186 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4187 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4188 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4189 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4190 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4192 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4193 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4194 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4195 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4196 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4197 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4199 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4200 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4201 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4202 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4203 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4204 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4206 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4207 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4208 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4209 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4210 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4211 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4215 fn private_multi_hint_last_hops_test() {
4216 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4217 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4219 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4220 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4222 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4223 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4224 let scorer = ln_test_utils::TestScorer::new();
4225 // Test through channels 2, 3, 0xff00, 0xff01.
4226 // Test shows that multiple hop hints are considered.
4228 // Disabling channels 6 & 7 by flags=2
4229 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4230 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4231 short_channel_id: 6,
4233 flags: 2, // to disable
4234 cltv_expiry_delta: 0,
4235 htlc_minimum_msat: 0,
4236 htlc_maximum_msat: MAX_VALUE_MSAT,
4238 fee_proportional_millionths: 0,
4239 excess_data: Vec::new()
4241 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4242 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4243 short_channel_id: 7,
4245 flags: 2, // to disable
4246 cltv_expiry_delta: 0,
4247 htlc_minimum_msat: 0,
4248 htlc_maximum_msat: MAX_VALUE_MSAT,
4250 fee_proportional_millionths: 0,
4251 excess_data: Vec::new()
4254 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4255 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4256 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4257 assert_eq!(route.paths[0].hops.len(), 4);
4259 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4260 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4261 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4262 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4263 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4264 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4266 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4267 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4268 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4269 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4270 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4271 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4273 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4274 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4275 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4276 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4277 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4278 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4280 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4281 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4282 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4283 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4284 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4285 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4288 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4289 let zero_fees = RoutingFees {
4291 proportional_millionths: 0,
4293 vec![RouteHint(vec![RouteHintHop {
4294 src_node_id: nodes[4],
4295 short_channel_id: 11,
4297 cltv_expiry_delta: (11 << 4) | 1,
4298 htlc_minimum_msat: None,
4299 htlc_maximum_msat: None,
4301 src_node_id: nodes[3],
4302 short_channel_id: 8,
4304 cltv_expiry_delta: (8 << 4) | 1,
4305 htlc_minimum_msat: None,
4306 htlc_maximum_msat: None,
4307 }]), RouteHint(vec![RouteHintHop {
4308 src_node_id: nodes[4],
4309 short_channel_id: 9,
4312 proportional_millionths: 0,
4314 cltv_expiry_delta: (9 << 4) | 1,
4315 htlc_minimum_msat: None,
4316 htlc_maximum_msat: None,
4317 }]), RouteHint(vec![RouteHintHop {
4318 src_node_id: nodes[5],
4319 short_channel_id: 10,
4321 cltv_expiry_delta: (10 << 4) | 1,
4322 htlc_minimum_msat: None,
4323 htlc_maximum_msat: None,
4328 fn last_hops_with_public_channel_test() {
4329 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4330 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4331 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4332 let scorer = ln_test_utils::TestScorer::new();
4333 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4334 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4335 // This test shows that public routes can be present in the invoice
4336 // which would be handled in the same manner.
4338 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4339 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4340 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4341 assert_eq!(route.paths[0].hops.len(), 5);
4343 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4344 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4345 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4346 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4347 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4348 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4350 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4351 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4352 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4353 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4354 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4355 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4357 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4358 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4359 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4360 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4361 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4362 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4364 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4365 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4366 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4367 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4368 // If we have a peer in the node map, we'll use their features here since we don't have
4369 // a way of figuring out their features from the invoice:
4370 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4371 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4373 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4374 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4375 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4376 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4377 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4378 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4382 fn our_chans_last_hop_connect_test() {
4383 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4384 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4385 let scorer = ln_test_utils::TestScorer::new();
4386 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4387 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4389 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4390 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4391 let mut last_hops = last_hops(&nodes);
4392 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4393 .with_route_hints(last_hops.clone()).unwrap();
4394 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4395 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4396 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4397 &Default::default(), &random_seed_bytes).unwrap();
4398 assert_eq!(route.paths[0].hops.len(), 2);
4400 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4401 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4402 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4403 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4404 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4405 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4407 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4408 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4409 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4410 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4411 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4412 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4414 last_hops[0].0[0].fees.base_msat = 1000;
4416 // Revert to via 6 as the fee on 8 goes up
4417 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4418 .with_route_hints(last_hops).unwrap();
4419 let route_params = RouteParameters::from_payment_params_and_value(
4420 payment_params.clone(), 100);
4421 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4422 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4423 assert_eq!(route.paths[0].hops.len(), 4);
4425 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4426 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4427 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4428 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4429 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4430 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4432 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4433 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4434 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4435 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4436 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4437 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4439 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4440 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4441 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4442 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4443 // If we have a peer in the node map, we'll use their features here since we don't have
4444 // a way of figuring out their features from the invoice:
4445 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4446 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4448 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4449 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4450 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4451 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4452 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4453 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4455 // ...but still use 8 for larger payments as 6 has a variable feerate
4456 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4457 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4458 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4459 assert_eq!(route.paths[0].hops.len(), 5);
4461 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4462 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4463 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4464 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4465 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4466 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4468 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4469 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4470 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4471 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4472 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4473 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4475 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4476 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4477 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4478 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4479 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4480 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4482 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4483 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4484 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4485 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4486 // If we have a peer in the node map, we'll use their features here since we don't have
4487 // a way of figuring out their features from the invoice:
4488 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4489 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4491 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4492 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4493 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4494 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4495 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4496 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4499 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> {
4500 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4501 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4502 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4504 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4505 let last_hops = RouteHint(vec![RouteHintHop {
4506 src_node_id: middle_node_id,
4507 short_channel_id: 8,
4510 proportional_millionths: last_hop_fee_prop,
4512 cltv_expiry_delta: (8 << 4) | 1,
4513 htlc_minimum_msat: None,
4514 htlc_maximum_msat: last_hop_htlc_max,
4516 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4517 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4518 let scorer = ln_test_utils::TestScorer::new();
4519 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4520 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4521 let logger = ln_test_utils::TestLogger::new();
4522 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4523 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4524 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4525 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4526 &random_seed_bytes);
4531 fn unannounced_path_test() {
4532 // We should be able to send a payment to a destination without any help of a routing graph
4533 // if we have a channel with a common counterparty that appears in the first and last hop
4535 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4537 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4538 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4539 assert_eq!(route.paths[0].hops.len(), 2);
4541 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4542 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4543 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4544 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4545 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4546 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4548 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4549 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4550 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4551 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4552 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4553 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4557 fn overflow_unannounced_path_test_liquidity_underflow() {
4558 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4559 // the last-hop had a fee which overflowed a u64, we'd panic.
4560 // This was due to us adding the first-hop from us unconditionally, causing us to think
4561 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4562 // In this test, we previously hit a subtraction underflow due to having less available
4563 // liquidity at the last hop than 0.
4564 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());
4568 fn overflow_unannounced_path_test_feerate_overflow() {
4569 // This tests for the same case as above, except instead of hitting a subtraction
4570 // underflow, we hit a case where the fee charged at a hop overflowed.
4571 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());
4575 fn available_amount_while_routing_test() {
4576 // Tests whether we choose the correct available channel amount while routing.
4578 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4579 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4580 let scorer = ln_test_utils::TestScorer::new();
4581 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4582 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4583 let config = UserConfig::default();
4584 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4585 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4588 // We will use a simple single-path route from
4589 // our node to node2 via node0: channels {1, 3}.
4591 // First disable all other paths.
4592 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4593 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4594 short_channel_id: 2,
4597 cltv_expiry_delta: 0,
4598 htlc_minimum_msat: 0,
4599 htlc_maximum_msat: 100_000,
4601 fee_proportional_millionths: 0,
4602 excess_data: Vec::new()
4604 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4605 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4606 short_channel_id: 12,
4609 cltv_expiry_delta: 0,
4610 htlc_minimum_msat: 0,
4611 htlc_maximum_msat: 100_000,
4613 fee_proportional_millionths: 0,
4614 excess_data: Vec::new()
4617 // Make the first channel (#1) very permissive,
4618 // and we will be testing all limits on the second channel.
4619 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4620 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4621 short_channel_id: 1,
4624 cltv_expiry_delta: 0,
4625 htlc_minimum_msat: 0,
4626 htlc_maximum_msat: 1_000_000_000,
4628 fee_proportional_millionths: 0,
4629 excess_data: Vec::new()
4632 // First, let's see if routing works if we have absolutely no idea about the available amount.
4633 // In this case, it should be set to 250_000 sats.
4634 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4635 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4636 short_channel_id: 3,
4639 cltv_expiry_delta: 0,
4640 htlc_minimum_msat: 0,
4641 htlc_maximum_msat: 250_000_000,
4643 fee_proportional_millionths: 0,
4644 excess_data: Vec::new()
4648 // Attempt to route more than available results in a failure.
4649 let route_params = RouteParameters::from_payment_params_and_value(
4650 payment_params.clone(), 250_000_001);
4651 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4652 &our_id, &route_params, &network_graph.read_only(), None,
4653 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4654 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4655 } else { panic!(); }
4659 // Now, attempt to route an exact amount we have should be fine.
4660 let route_params = RouteParameters::from_payment_params_and_value(
4661 payment_params.clone(), 250_000_000);
4662 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4663 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4664 assert_eq!(route.paths.len(), 1);
4665 let path = route.paths.last().unwrap();
4666 assert_eq!(path.hops.len(), 2);
4667 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4668 assert_eq!(path.final_value_msat(), 250_000_000);
4671 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4672 // Disable channel #1 and use another first hop.
4673 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4674 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4675 short_channel_id: 1,
4678 cltv_expiry_delta: 0,
4679 htlc_minimum_msat: 0,
4680 htlc_maximum_msat: 1_000_000_000,
4682 fee_proportional_millionths: 0,
4683 excess_data: Vec::new()
4686 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4687 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4690 // Attempt to route more than available results in a failure.
4691 let route_params = RouteParameters::from_payment_params_and_value(
4692 payment_params.clone(), 200_000_001);
4693 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4694 &our_id, &route_params, &network_graph.read_only(),
4695 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4696 &Default::default(), &random_seed_bytes) {
4697 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4698 } else { panic!(); }
4702 // Now, attempt to route an exact amount we have should be fine.
4703 let route_params = RouteParameters::from_payment_params_and_value(
4704 payment_params.clone(), 200_000_000);
4705 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4706 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4707 &Default::default(), &random_seed_bytes).unwrap();
4708 assert_eq!(route.paths.len(), 1);
4709 let path = route.paths.last().unwrap();
4710 assert_eq!(path.hops.len(), 2);
4711 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4712 assert_eq!(path.final_value_msat(), 200_000_000);
4715 // Enable channel #1 back.
4716 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4717 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4718 short_channel_id: 1,
4721 cltv_expiry_delta: 0,
4722 htlc_minimum_msat: 0,
4723 htlc_maximum_msat: 1_000_000_000,
4725 fee_proportional_millionths: 0,
4726 excess_data: Vec::new()
4730 // Now let's see if routing works if we know only htlc_maximum_msat.
4731 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4732 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4733 short_channel_id: 3,
4736 cltv_expiry_delta: 0,
4737 htlc_minimum_msat: 0,
4738 htlc_maximum_msat: 15_000,
4740 fee_proportional_millionths: 0,
4741 excess_data: Vec::new()
4745 // Attempt to route more than available results in a failure.
4746 let route_params = RouteParameters::from_payment_params_and_value(
4747 payment_params.clone(), 15_001);
4748 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4749 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4750 &scorer, &Default::default(), &random_seed_bytes) {
4751 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4752 } else { panic!(); }
4756 // Now, attempt to route an exact amount we have should be fine.
4757 let route_params = RouteParameters::from_payment_params_and_value(
4758 payment_params.clone(), 15_000);
4759 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4760 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4761 assert_eq!(route.paths.len(), 1);
4762 let path = route.paths.last().unwrap();
4763 assert_eq!(path.hops.len(), 2);
4764 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4765 assert_eq!(path.final_value_msat(), 15_000);
4768 // Now let's see if routing works if we know only capacity from the UTXO.
4770 // We can't change UTXO capacity on the fly, so we'll disable
4771 // the existing channel and add another one with the capacity we need.
4772 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4773 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4774 short_channel_id: 3,
4777 cltv_expiry_delta: 0,
4778 htlc_minimum_msat: 0,
4779 htlc_maximum_msat: MAX_VALUE_MSAT,
4781 fee_proportional_millionths: 0,
4782 excess_data: Vec::new()
4785 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4786 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4787 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4788 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4789 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4791 *chain_monitor.utxo_ret.lock().unwrap() =
4792 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4793 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4795 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4796 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4797 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4798 short_channel_id: 333,
4801 cltv_expiry_delta: (3 << 4) | 1,
4802 htlc_minimum_msat: 0,
4803 htlc_maximum_msat: 15_000,
4805 fee_proportional_millionths: 0,
4806 excess_data: Vec::new()
4808 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4809 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4810 short_channel_id: 333,
4813 cltv_expiry_delta: (3 << 4) | 2,
4814 htlc_minimum_msat: 0,
4815 htlc_maximum_msat: 15_000,
4817 fee_proportional_millionths: 0,
4818 excess_data: Vec::new()
4822 // Attempt to route more than available results in a failure.
4823 let route_params = RouteParameters::from_payment_params_and_value(
4824 payment_params.clone(), 15_001);
4825 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4826 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4827 &scorer, &Default::default(), &random_seed_bytes) {
4828 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4829 } else { panic!(); }
4833 // Now, attempt to route an exact amount we have should be fine.
4834 let route_params = RouteParameters::from_payment_params_and_value(
4835 payment_params.clone(), 15_000);
4836 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4837 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4838 assert_eq!(route.paths.len(), 1);
4839 let path = route.paths.last().unwrap();
4840 assert_eq!(path.hops.len(), 2);
4841 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4842 assert_eq!(path.final_value_msat(), 15_000);
4845 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4846 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4847 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4848 short_channel_id: 333,
4851 cltv_expiry_delta: 0,
4852 htlc_minimum_msat: 0,
4853 htlc_maximum_msat: 10_000,
4855 fee_proportional_millionths: 0,
4856 excess_data: Vec::new()
4860 // Attempt to route more than available results in a failure.
4861 let route_params = RouteParameters::from_payment_params_and_value(
4862 payment_params.clone(), 10_001);
4863 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4864 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4865 &scorer, &Default::default(), &random_seed_bytes) {
4866 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4867 } else { panic!(); }
4871 // Now, attempt to route an exact amount we have should be fine.
4872 let route_params = RouteParameters::from_payment_params_and_value(
4873 payment_params.clone(), 10_000);
4874 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4875 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4876 assert_eq!(route.paths.len(), 1);
4877 let path = route.paths.last().unwrap();
4878 assert_eq!(path.hops.len(), 2);
4879 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4880 assert_eq!(path.final_value_msat(), 10_000);
4885 fn available_liquidity_last_hop_test() {
4886 // Check that available liquidity properly limits the path even when only
4887 // one of the latter hops is limited.
4888 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4889 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4890 let scorer = ln_test_utils::TestScorer::new();
4891 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4892 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4893 let config = UserConfig::default();
4894 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4895 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4898 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4899 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4900 // Total capacity: 50 sats.
4902 // Disable other potential paths.
4903 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4904 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4905 short_channel_id: 2,
4908 cltv_expiry_delta: 0,
4909 htlc_minimum_msat: 0,
4910 htlc_maximum_msat: 100_000,
4912 fee_proportional_millionths: 0,
4913 excess_data: Vec::new()
4915 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4916 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4917 short_channel_id: 7,
4920 cltv_expiry_delta: 0,
4921 htlc_minimum_msat: 0,
4922 htlc_maximum_msat: 100_000,
4924 fee_proportional_millionths: 0,
4925 excess_data: Vec::new()
4930 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4931 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4932 short_channel_id: 12,
4935 cltv_expiry_delta: 0,
4936 htlc_minimum_msat: 0,
4937 htlc_maximum_msat: 100_000,
4939 fee_proportional_millionths: 0,
4940 excess_data: Vec::new()
4942 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4943 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4944 short_channel_id: 13,
4947 cltv_expiry_delta: 0,
4948 htlc_minimum_msat: 0,
4949 htlc_maximum_msat: 100_000,
4951 fee_proportional_millionths: 0,
4952 excess_data: Vec::new()
4955 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4956 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4957 short_channel_id: 6,
4960 cltv_expiry_delta: 0,
4961 htlc_minimum_msat: 0,
4962 htlc_maximum_msat: 50_000,
4964 fee_proportional_millionths: 0,
4965 excess_data: Vec::new()
4967 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4968 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4969 short_channel_id: 11,
4972 cltv_expiry_delta: 0,
4973 htlc_minimum_msat: 0,
4974 htlc_maximum_msat: 100_000,
4976 fee_proportional_millionths: 0,
4977 excess_data: Vec::new()
4980 // Attempt to route more than available results in a failure.
4981 let route_params = RouteParameters::from_payment_params_and_value(
4982 payment_params.clone(), 60_000);
4983 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4984 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4985 &scorer, &Default::default(), &random_seed_bytes) {
4986 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4987 } else { panic!(); }
4991 // Now, attempt to route 49 sats (just a bit below the capacity).
4992 let route_params = RouteParameters::from_payment_params_and_value(
4993 payment_params.clone(), 49_000);
4994 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4995 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4996 assert_eq!(route.paths.len(), 1);
4997 let mut total_amount_paid_msat = 0;
4998 for path in &route.paths {
4999 assert_eq!(path.hops.len(), 4);
5000 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5001 total_amount_paid_msat += path.final_value_msat();
5003 assert_eq!(total_amount_paid_msat, 49_000);
5007 // Attempt to route an exact amount is also fine
5008 let route_params = RouteParameters::from_payment_params_and_value(
5009 payment_params, 50_000);
5010 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5011 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5012 assert_eq!(route.paths.len(), 1);
5013 let mut total_amount_paid_msat = 0;
5014 for path in &route.paths {
5015 assert_eq!(path.hops.len(), 4);
5016 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5017 total_amount_paid_msat += path.final_value_msat();
5019 assert_eq!(total_amount_paid_msat, 50_000);
5024 fn ignore_fee_first_hop_test() {
5025 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5026 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5027 let scorer = ln_test_utils::TestScorer::new();
5028 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5029 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5030 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5032 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5033 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5034 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5035 short_channel_id: 1,
5038 cltv_expiry_delta: 0,
5039 htlc_minimum_msat: 0,
5040 htlc_maximum_msat: 100_000,
5041 fee_base_msat: 1_000_000,
5042 fee_proportional_millionths: 0,
5043 excess_data: Vec::new()
5045 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5046 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5047 short_channel_id: 3,
5050 cltv_expiry_delta: 0,
5051 htlc_minimum_msat: 0,
5052 htlc_maximum_msat: 50_000,
5054 fee_proportional_millionths: 0,
5055 excess_data: Vec::new()
5059 let route_params = RouteParameters::from_payment_params_and_value(
5060 payment_params, 50_000);
5061 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5062 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5063 assert_eq!(route.paths.len(), 1);
5064 let mut total_amount_paid_msat = 0;
5065 for path in &route.paths {
5066 assert_eq!(path.hops.len(), 2);
5067 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5068 total_amount_paid_msat += path.final_value_msat();
5070 assert_eq!(total_amount_paid_msat, 50_000);
5075 fn simple_mpp_route_test() {
5076 let (secp_ctx, _, _, _, _) = build_graph();
5077 let (_, _, _, nodes) = get_nodes(&secp_ctx);
5078 let config = UserConfig::default();
5079 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5080 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5082 do_simple_mpp_route_test(clear_payment_params);
5084 // MPP to a 1-hop blinded path for nodes[2]
5085 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
5086 let blinded_path = BlindedPath {
5087 introduction_node_id: nodes[2],
5088 blinding_point: ln_test_utils::pubkey(42),
5089 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
5091 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
5093 fee_proportional_millionths: 0,
5094 htlc_minimum_msat: 0,
5095 htlc_maximum_msat: 0,
5096 cltv_expiry_delta: 0,
5097 features: BlindedHopFeatures::empty(),
5099 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
5100 .with_bolt12_features(bolt12_features.clone()).unwrap();
5101 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
5103 // MPP to 3 2-hop blinded paths
5104 let mut blinded_path_node_0 = blinded_path.clone();
5105 blinded_path_node_0.introduction_node_id = nodes[0];
5106 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
5107 let mut node_0_payinfo = blinded_payinfo.clone();
5108 node_0_payinfo.htlc_maximum_msat = 50_000;
5110 let mut blinded_path_node_7 = blinded_path_node_0.clone();
5111 blinded_path_node_7.introduction_node_id = nodes[7];
5112 let mut node_7_payinfo = blinded_payinfo.clone();
5113 node_7_payinfo.htlc_maximum_msat = 60_000;
5115 let mut blinded_path_node_1 = blinded_path_node_0.clone();
5116 blinded_path_node_1.introduction_node_id = nodes[1];
5117 let mut node_1_payinfo = blinded_payinfo.clone();
5118 node_1_payinfo.htlc_maximum_msat = 180_000;
5120 let two_hop_blinded_payment_params = PaymentParameters::blinded(
5122 (node_0_payinfo, blinded_path_node_0),
5123 (node_7_payinfo, blinded_path_node_7),
5124 (node_1_payinfo, blinded_path_node_1)
5126 .with_bolt12_features(bolt12_features).unwrap();
5127 do_simple_mpp_route_test(two_hop_blinded_payment_params);
5131 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
5132 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5133 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5134 let scorer = ln_test_utils::TestScorer::new();
5135 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5136 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5138 // We need a route consisting of 3 paths:
5139 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5140 // To achieve this, the amount being transferred should be around
5141 // the total capacity of these 3 paths.
5143 // First, we set limits on these (previously unlimited) channels.
5144 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
5146 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5147 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5148 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5149 short_channel_id: 1,
5152 cltv_expiry_delta: 0,
5153 htlc_minimum_msat: 0,
5154 htlc_maximum_msat: 100_000,
5156 fee_proportional_millionths: 0,
5157 excess_data: Vec::new()
5159 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5160 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5161 short_channel_id: 3,
5164 cltv_expiry_delta: 0,
5165 htlc_minimum_msat: 0,
5166 htlc_maximum_msat: 50_000,
5168 fee_proportional_millionths: 0,
5169 excess_data: Vec::new()
5172 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
5173 // (total limit 60).
5174 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5175 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5176 short_channel_id: 12,
5179 cltv_expiry_delta: 0,
5180 htlc_minimum_msat: 0,
5181 htlc_maximum_msat: 60_000,
5183 fee_proportional_millionths: 0,
5184 excess_data: Vec::new()
5186 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5187 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5188 short_channel_id: 13,
5191 cltv_expiry_delta: 0,
5192 htlc_minimum_msat: 0,
5193 htlc_maximum_msat: 60_000,
5195 fee_proportional_millionths: 0,
5196 excess_data: Vec::new()
5199 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5200 // (total capacity 180 sats).
5201 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5202 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5203 short_channel_id: 2,
5206 cltv_expiry_delta: 0,
5207 htlc_minimum_msat: 0,
5208 htlc_maximum_msat: 200_000,
5210 fee_proportional_millionths: 0,
5211 excess_data: Vec::new()
5213 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5214 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5215 short_channel_id: 4,
5218 cltv_expiry_delta: 0,
5219 htlc_minimum_msat: 0,
5220 htlc_maximum_msat: 180_000,
5222 fee_proportional_millionths: 0,
5223 excess_data: Vec::new()
5227 // Attempt to route more than available results in a failure.
5228 let route_params = RouteParameters::from_payment_params_and_value(
5229 payment_params.clone(), 300_000);
5230 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5231 &our_id, &route_params, &network_graph.read_only(), None,
5232 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5233 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5234 } else { panic!(); }
5238 // Attempt to route while setting max_path_count to 0 results in a failure.
5239 let zero_payment_params = payment_params.clone().with_max_path_count(0);
5240 let route_params = RouteParameters::from_payment_params_and_value(
5241 zero_payment_params, 100);
5242 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5243 &our_id, &route_params, &network_graph.read_only(), None,
5244 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5245 assert_eq!(err, "Can't find a route with no paths allowed.");
5246 } else { panic!(); }
5250 // Attempt to route while setting max_path_count to 3 results in a failure.
5251 // This is the case because the minimal_value_contribution_msat would require each path
5252 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5253 let fail_payment_params = payment_params.clone().with_max_path_count(3);
5254 let route_params = RouteParameters::from_payment_params_and_value(
5255 fail_payment_params, 250_000);
5256 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5257 &our_id, &route_params, &network_graph.read_only(), None,
5258 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5259 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5260 } else { panic!(); }
5264 // Now, attempt to route 250 sats (just a bit below the capacity).
5265 // Our algorithm should provide us with these 3 paths.
5266 let route_params = RouteParameters::from_payment_params_and_value(
5267 payment_params.clone(), 250_000);
5268 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5269 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5270 assert_eq!(route.paths.len(), 3);
5271 let mut total_amount_paid_msat = 0;
5272 for path in &route.paths {
5273 if let Some(bt) = &path.blinded_tail {
5274 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5276 assert_eq!(path.hops.len(), 2);
5277 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5279 total_amount_paid_msat += path.final_value_msat();
5281 assert_eq!(total_amount_paid_msat, 250_000);
5285 // Attempt to route an exact amount is also fine
5286 let route_params = RouteParameters::from_payment_params_and_value(
5287 payment_params.clone(), 290_000);
5288 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5289 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5290 assert_eq!(route.paths.len(), 3);
5291 let mut total_amount_paid_msat = 0;
5292 for path in &route.paths {
5293 if payment_params.payee.blinded_route_hints().len() != 0 {
5294 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5295 if let Some(bt) = &path.blinded_tail {
5296 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5297 if bt.hops.len() > 1 {
5298 assert_eq!(path.hops.last().unwrap().pubkey,
5299 payment_params.payee.blinded_route_hints().iter()
5300 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5301 .map(|(_, p)| p.introduction_node_id).unwrap());
5303 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5306 assert_eq!(path.hops.len(), 2);
5307 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5309 total_amount_paid_msat += path.final_value_msat();
5311 assert_eq!(total_amount_paid_msat, 290_000);
5316 fn long_mpp_route_test() {
5317 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5318 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5319 let scorer = ln_test_utils::TestScorer::new();
5320 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5321 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5322 let config = UserConfig::default();
5323 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5324 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5327 // We need a route consisting of 3 paths:
5328 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5329 // Note that these paths overlap (channels 5, 12, 13).
5330 // We will route 300 sats.
5331 // Each path will have 100 sats capacity, those channels which
5332 // are used twice will have 200 sats capacity.
5334 // Disable other potential paths.
5335 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5336 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5337 short_channel_id: 2,
5340 cltv_expiry_delta: 0,
5341 htlc_minimum_msat: 0,
5342 htlc_maximum_msat: 100_000,
5344 fee_proportional_millionths: 0,
5345 excess_data: Vec::new()
5347 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5348 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5349 short_channel_id: 7,
5352 cltv_expiry_delta: 0,
5353 htlc_minimum_msat: 0,
5354 htlc_maximum_msat: 100_000,
5356 fee_proportional_millionths: 0,
5357 excess_data: Vec::new()
5360 // Path via {node0, node2} is channels {1, 3, 5}.
5361 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5362 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5363 short_channel_id: 1,
5366 cltv_expiry_delta: 0,
5367 htlc_minimum_msat: 0,
5368 htlc_maximum_msat: 100_000,
5370 fee_proportional_millionths: 0,
5371 excess_data: Vec::new()
5373 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5374 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5375 short_channel_id: 3,
5378 cltv_expiry_delta: 0,
5379 htlc_minimum_msat: 0,
5380 htlc_maximum_msat: 100_000,
5382 fee_proportional_millionths: 0,
5383 excess_data: Vec::new()
5386 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5387 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5388 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5389 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5390 short_channel_id: 5,
5393 cltv_expiry_delta: 0,
5394 htlc_minimum_msat: 0,
5395 htlc_maximum_msat: 200_000,
5397 fee_proportional_millionths: 0,
5398 excess_data: Vec::new()
5401 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5402 // Add 100 sats to the capacities of {12, 13}, because these channels
5403 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5404 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5405 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5406 short_channel_id: 12,
5409 cltv_expiry_delta: 0,
5410 htlc_minimum_msat: 0,
5411 htlc_maximum_msat: 200_000,
5413 fee_proportional_millionths: 0,
5414 excess_data: Vec::new()
5416 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5417 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5418 short_channel_id: 13,
5421 cltv_expiry_delta: 0,
5422 htlc_minimum_msat: 0,
5423 htlc_maximum_msat: 200_000,
5425 fee_proportional_millionths: 0,
5426 excess_data: Vec::new()
5429 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5430 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5431 short_channel_id: 6,
5434 cltv_expiry_delta: 0,
5435 htlc_minimum_msat: 0,
5436 htlc_maximum_msat: 100_000,
5438 fee_proportional_millionths: 0,
5439 excess_data: Vec::new()
5441 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5442 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5443 short_channel_id: 11,
5446 cltv_expiry_delta: 0,
5447 htlc_minimum_msat: 0,
5448 htlc_maximum_msat: 100_000,
5450 fee_proportional_millionths: 0,
5451 excess_data: Vec::new()
5454 // Path via {node7, node2} is channels {12, 13, 5}.
5455 // We already limited them to 200 sats (they are used twice for 100 sats).
5456 // Nothing to do here.
5459 // Attempt to route more than available results in a failure.
5460 let route_params = RouteParameters::from_payment_params_and_value(
5461 payment_params.clone(), 350_000);
5462 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5463 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5464 &scorer, &Default::default(), &random_seed_bytes) {
5465 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5466 } else { panic!(); }
5470 // Now, attempt to route 300 sats (exact amount we can route).
5471 // Our algorithm should provide us with these 3 paths, 100 sats each.
5472 let route_params = RouteParameters::from_payment_params_and_value(
5473 payment_params, 300_000);
5474 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5475 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5476 assert_eq!(route.paths.len(), 3);
5478 let mut total_amount_paid_msat = 0;
5479 for path in &route.paths {
5480 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5481 total_amount_paid_msat += path.final_value_msat();
5483 assert_eq!(total_amount_paid_msat, 300_000);
5489 fn mpp_cheaper_route_test() {
5490 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5491 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5492 let scorer = ln_test_utils::TestScorer::new();
5493 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5494 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5495 let config = UserConfig::default();
5496 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5497 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5500 // This test checks that if we have two cheaper paths and one more expensive path,
5501 // so that liquidity-wise any 2 of 3 combination is sufficient,
5502 // two cheaper paths will be taken.
5503 // These paths have equal available liquidity.
5505 // We need a combination of 3 paths:
5506 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5507 // Note that these paths overlap (channels 5, 12, 13).
5508 // Each path will have 100 sats capacity, those channels which
5509 // are used twice will have 200 sats capacity.
5511 // Disable other potential paths.
5512 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5513 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5514 short_channel_id: 2,
5517 cltv_expiry_delta: 0,
5518 htlc_minimum_msat: 0,
5519 htlc_maximum_msat: 100_000,
5521 fee_proportional_millionths: 0,
5522 excess_data: Vec::new()
5524 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5525 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5526 short_channel_id: 7,
5529 cltv_expiry_delta: 0,
5530 htlc_minimum_msat: 0,
5531 htlc_maximum_msat: 100_000,
5533 fee_proportional_millionths: 0,
5534 excess_data: Vec::new()
5537 // Path via {node0, node2} is channels {1, 3, 5}.
5538 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5539 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5540 short_channel_id: 1,
5543 cltv_expiry_delta: 0,
5544 htlc_minimum_msat: 0,
5545 htlc_maximum_msat: 100_000,
5547 fee_proportional_millionths: 0,
5548 excess_data: Vec::new()
5550 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5551 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5552 short_channel_id: 3,
5555 cltv_expiry_delta: 0,
5556 htlc_minimum_msat: 0,
5557 htlc_maximum_msat: 100_000,
5559 fee_proportional_millionths: 0,
5560 excess_data: Vec::new()
5563 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5564 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5565 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5566 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5567 short_channel_id: 5,
5570 cltv_expiry_delta: 0,
5571 htlc_minimum_msat: 0,
5572 htlc_maximum_msat: 200_000,
5574 fee_proportional_millionths: 0,
5575 excess_data: Vec::new()
5578 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5579 // Add 100 sats to the capacities of {12, 13}, because these channels
5580 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5581 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5582 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5583 short_channel_id: 12,
5586 cltv_expiry_delta: 0,
5587 htlc_minimum_msat: 0,
5588 htlc_maximum_msat: 200_000,
5590 fee_proportional_millionths: 0,
5591 excess_data: Vec::new()
5593 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5594 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5595 short_channel_id: 13,
5598 cltv_expiry_delta: 0,
5599 htlc_minimum_msat: 0,
5600 htlc_maximum_msat: 200_000,
5602 fee_proportional_millionths: 0,
5603 excess_data: Vec::new()
5606 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5607 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5608 short_channel_id: 6,
5611 cltv_expiry_delta: 0,
5612 htlc_minimum_msat: 0,
5613 htlc_maximum_msat: 100_000,
5614 fee_base_msat: 1_000,
5615 fee_proportional_millionths: 0,
5616 excess_data: Vec::new()
5618 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5619 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5620 short_channel_id: 11,
5623 cltv_expiry_delta: 0,
5624 htlc_minimum_msat: 0,
5625 htlc_maximum_msat: 100_000,
5627 fee_proportional_millionths: 0,
5628 excess_data: Vec::new()
5631 // Path via {node7, node2} is channels {12, 13, 5}.
5632 // We already limited them to 200 sats (they are used twice for 100 sats).
5633 // Nothing to do here.
5636 // Now, attempt to route 180 sats.
5637 // Our algorithm should provide us with these 2 paths.
5638 let route_params = RouteParameters::from_payment_params_and_value(
5639 payment_params, 180_000);
5640 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5641 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5642 assert_eq!(route.paths.len(), 2);
5644 let mut total_value_transferred_msat = 0;
5645 let mut total_paid_msat = 0;
5646 for path in &route.paths {
5647 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5648 total_value_transferred_msat += path.final_value_msat();
5649 for hop in &path.hops {
5650 total_paid_msat += hop.fee_msat;
5653 // If we paid fee, this would be higher.
5654 assert_eq!(total_value_transferred_msat, 180_000);
5655 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5656 assert_eq!(total_fees_paid, 0);
5661 fn fees_on_mpp_route_test() {
5662 // This test makes sure that MPP algorithm properly takes into account
5663 // fees charged on the channels, by making the fees impactful:
5664 // if the fee is not properly accounted for, the behavior is different.
5665 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5666 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5667 let scorer = ln_test_utils::TestScorer::new();
5668 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5669 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5670 let config = UserConfig::default();
5671 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5672 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5675 // We need a route consisting of 2 paths:
5676 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5677 // We will route 200 sats, Each path will have 100 sats capacity.
5679 // This test is not particularly stable: e.g.,
5680 // there's a way to route via {node0, node2, node4}.
5681 // It works while pathfinding is deterministic, but can be broken otherwise.
5682 // It's fine to ignore this concern for now.
5684 // Disable other potential paths.
5685 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5686 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5687 short_channel_id: 2,
5690 cltv_expiry_delta: 0,
5691 htlc_minimum_msat: 0,
5692 htlc_maximum_msat: 100_000,
5694 fee_proportional_millionths: 0,
5695 excess_data: Vec::new()
5698 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5699 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5700 short_channel_id: 7,
5703 cltv_expiry_delta: 0,
5704 htlc_minimum_msat: 0,
5705 htlc_maximum_msat: 100_000,
5707 fee_proportional_millionths: 0,
5708 excess_data: Vec::new()
5711 // Path via {node0, node2} is channels {1, 3, 5}.
5712 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5713 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5714 short_channel_id: 1,
5717 cltv_expiry_delta: 0,
5718 htlc_minimum_msat: 0,
5719 htlc_maximum_msat: 100_000,
5721 fee_proportional_millionths: 0,
5722 excess_data: Vec::new()
5724 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5725 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5726 short_channel_id: 3,
5729 cltv_expiry_delta: 0,
5730 htlc_minimum_msat: 0,
5731 htlc_maximum_msat: 100_000,
5733 fee_proportional_millionths: 0,
5734 excess_data: Vec::new()
5737 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5738 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5739 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5740 short_channel_id: 5,
5743 cltv_expiry_delta: 0,
5744 htlc_minimum_msat: 0,
5745 htlc_maximum_msat: 100_000,
5747 fee_proportional_millionths: 0,
5748 excess_data: Vec::new()
5751 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5752 // All channels should be 100 sats capacity. But for the fee experiment,
5753 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5754 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5755 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5756 // so no matter how large are other channels,
5757 // the whole path will be limited by 100 sats with just these 2 conditions:
5758 // - channel 12 capacity is 250 sats
5759 // - fee for channel 6 is 150 sats
5760 // Let's test this by enforcing these 2 conditions and removing other limits.
5761 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5762 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5763 short_channel_id: 12,
5766 cltv_expiry_delta: 0,
5767 htlc_minimum_msat: 0,
5768 htlc_maximum_msat: 250_000,
5770 fee_proportional_millionths: 0,
5771 excess_data: Vec::new()
5773 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5774 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5775 short_channel_id: 13,
5778 cltv_expiry_delta: 0,
5779 htlc_minimum_msat: 0,
5780 htlc_maximum_msat: MAX_VALUE_MSAT,
5782 fee_proportional_millionths: 0,
5783 excess_data: Vec::new()
5786 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5787 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5788 short_channel_id: 6,
5791 cltv_expiry_delta: 0,
5792 htlc_minimum_msat: 0,
5793 htlc_maximum_msat: MAX_VALUE_MSAT,
5794 fee_base_msat: 150_000,
5795 fee_proportional_millionths: 0,
5796 excess_data: Vec::new()
5798 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5799 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5800 short_channel_id: 11,
5803 cltv_expiry_delta: 0,
5804 htlc_minimum_msat: 0,
5805 htlc_maximum_msat: MAX_VALUE_MSAT,
5807 fee_proportional_millionths: 0,
5808 excess_data: Vec::new()
5812 // Attempt to route more than available results in a failure.
5813 let route_params = RouteParameters::from_payment_params_and_value(
5814 payment_params.clone(), 210_000);
5815 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5816 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5817 &scorer, &Default::default(), &random_seed_bytes) {
5818 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5819 } else { panic!(); }
5823 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5824 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5825 max_total_routing_fee_msat: Some(149_999) };
5826 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5827 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5828 &scorer, &Default::default(), &random_seed_bytes) {
5829 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5830 } else { panic!(); }
5834 // Now, attempt to route 200 sats (exact amount we can route).
5835 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5836 max_total_routing_fee_msat: Some(150_000) };
5837 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5838 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5839 assert_eq!(route.paths.len(), 2);
5841 let mut total_amount_paid_msat = 0;
5842 for path in &route.paths {
5843 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5844 total_amount_paid_msat += path.final_value_msat();
5846 assert_eq!(total_amount_paid_msat, 200_000);
5847 assert_eq!(route.get_total_fees(), 150_000);
5852 fn mpp_with_last_hops() {
5853 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5854 // via a single last-hop route hint, we'd fail to route if we first collected routes
5855 // totaling close but not quite enough to fund the full payment.
5857 // This was because we considered last-hop hints to have exactly the sought payment amount
5858 // instead of the amount we were trying to collect, needlessly limiting our path searching
5859 // at the very first hop.
5861 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5862 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5863 // to only have the remaining to-collect amount in available liquidity.
5865 // This bug appeared in production in some specific channel configurations.
5866 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5867 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5868 let scorer = ln_test_utils::TestScorer::new();
5869 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5870 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5871 let config = UserConfig::default();
5872 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
5873 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
5874 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5875 src_node_id: nodes[2],
5876 short_channel_id: 42,
5877 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5878 cltv_expiry_delta: 42,
5879 htlc_minimum_msat: None,
5880 htlc_maximum_msat: None,
5881 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5883 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5884 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5885 // would first use the no-fee route and then fail to find a path along the second route as
5886 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5887 // under 5% of our payment amount.
5888 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5889 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5890 short_channel_id: 1,
5893 cltv_expiry_delta: (5 << 4) | 5,
5894 htlc_minimum_msat: 0,
5895 htlc_maximum_msat: 99_000,
5896 fee_base_msat: u32::max_value(),
5897 fee_proportional_millionths: u32::max_value(),
5898 excess_data: Vec::new()
5900 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5901 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5902 short_channel_id: 2,
5905 cltv_expiry_delta: (5 << 4) | 3,
5906 htlc_minimum_msat: 0,
5907 htlc_maximum_msat: 99_000,
5908 fee_base_msat: u32::max_value(),
5909 fee_proportional_millionths: u32::max_value(),
5910 excess_data: Vec::new()
5912 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5913 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5914 short_channel_id: 4,
5917 cltv_expiry_delta: (4 << 4) | 1,
5918 htlc_minimum_msat: 0,
5919 htlc_maximum_msat: MAX_VALUE_MSAT,
5921 fee_proportional_millionths: 0,
5922 excess_data: Vec::new()
5924 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5925 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5926 short_channel_id: 13,
5928 flags: 0|2, // Channel disabled
5929 cltv_expiry_delta: (13 << 4) | 1,
5930 htlc_minimum_msat: 0,
5931 htlc_maximum_msat: MAX_VALUE_MSAT,
5933 fee_proportional_millionths: 2000000,
5934 excess_data: Vec::new()
5937 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5939 let route_params = RouteParameters::from_payment_params_and_value(
5940 payment_params, 100_000);
5941 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5942 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5943 assert_eq!(route.paths.len(), 2);
5944 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5945 // Paths are manually ordered ordered by SCID, so:
5946 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5947 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5948 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5949 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5950 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5951 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5952 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5953 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5954 assert_eq!(route.get_total_fees(), 1);
5955 assert_eq!(route.get_total_amount(), 100_000);
5959 fn drop_lowest_channel_mpp_route_test() {
5960 // This test checks that low-capacity channel is dropped when after
5961 // path finding we realize that we found more capacity than we need.
5962 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5963 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5964 let scorer = ln_test_utils::TestScorer::new();
5965 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5966 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5967 let config = UserConfig::default();
5968 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5969 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5971 .with_max_channel_saturation_power_of_half(0);
5973 // We need a route consisting of 3 paths:
5974 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5976 // The first and the second paths should be sufficient, but the third should be
5977 // cheaper, so that we select it but drop later.
5979 // First, we set limits on these (previously unlimited) channels.
5980 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5982 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5983 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5984 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5985 short_channel_id: 1,
5988 cltv_expiry_delta: 0,
5989 htlc_minimum_msat: 0,
5990 htlc_maximum_msat: 100_000,
5992 fee_proportional_millionths: 0,
5993 excess_data: Vec::new()
5995 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5996 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5997 short_channel_id: 3,
6000 cltv_expiry_delta: 0,
6001 htlc_minimum_msat: 0,
6002 htlc_maximum_msat: 50_000,
6004 fee_proportional_millionths: 0,
6005 excess_data: Vec::new()
6008 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
6009 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6010 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6011 short_channel_id: 12,
6014 cltv_expiry_delta: 0,
6015 htlc_minimum_msat: 0,
6016 htlc_maximum_msat: 60_000,
6018 fee_proportional_millionths: 0,
6019 excess_data: Vec::new()
6021 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6022 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6023 short_channel_id: 13,
6026 cltv_expiry_delta: 0,
6027 htlc_minimum_msat: 0,
6028 htlc_maximum_msat: 60_000,
6030 fee_proportional_millionths: 0,
6031 excess_data: Vec::new()
6034 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
6035 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6036 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6037 short_channel_id: 2,
6040 cltv_expiry_delta: 0,
6041 htlc_minimum_msat: 0,
6042 htlc_maximum_msat: 20_000,
6044 fee_proportional_millionths: 0,
6045 excess_data: Vec::new()
6047 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6048 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6049 short_channel_id: 4,
6052 cltv_expiry_delta: 0,
6053 htlc_minimum_msat: 0,
6054 htlc_maximum_msat: 20_000,
6056 fee_proportional_millionths: 0,
6057 excess_data: Vec::new()
6061 // Attempt to route more than available results in a failure.
6062 let route_params = RouteParameters::from_payment_params_and_value(
6063 payment_params.clone(), 150_000);
6064 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6065 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6066 &scorer, &Default::default(), &random_seed_bytes) {
6067 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6068 } else { panic!(); }
6072 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
6073 // Our algorithm should provide us with these 3 paths.
6074 let route_params = RouteParameters::from_payment_params_and_value(
6075 payment_params.clone(), 125_000);
6076 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6077 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6078 assert_eq!(route.paths.len(), 3);
6079 let mut total_amount_paid_msat = 0;
6080 for path in &route.paths {
6081 assert_eq!(path.hops.len(), 2);
6082 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6083 total_amount_paid_msat += path.final_value_msat();
6085 assert_eq!(total_amount_paid_msat, 125_000);
6089 // Attempt to route without the last small cheap channel
6090 let route_params = RouteParameters::from_payment_params_and_value(
6091 payment_params, 90_000);
6092 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6093 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6094 assert_eq!(route.paths.len(), 2);
6095 let mut total_amount_paid_msat = 0;
6096 for path in &route.paths {
6097 assert_eq!(path.hops.len(), 2);
6098 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6099 total_amount_paid_msat += path.final_value_msat();
6101 assert_eq!(total_amount_paid_msat, 90_000);
6106 fn min_criteria_consistency() {
6107 // Test that we don't use an inconsistent metric between updating and walking nodes during
6108 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
6109 // was updated with a different criterion from the heap sorting, resulting in loops in
6110 // calculated paths. We test for that specific case here.
6112 // We construct a network that looks like this:
6114 // node2 -1(3)2- node3
6118 // node1 -1(5)2- node4 -1(1)2- node6
6124 // We create a loop on the side of our real path - our destination is node 6, with a
6125 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
6126 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
6127 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
6128 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
6129 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
6130 // "previous hop" being set to node 3, creating a loop in the path.
6131 let secp_ctx = Secp256k1::new();
6132 let logger = Arc::new(ln_test_utils::TestLogger::new());
6133 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6134 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
6135 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6136 let scorer = ln_test_utils::TestScorer::new();
6137 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6138 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6139 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
6141 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
6142 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6143 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6144 short_channel_id: 6,
6147 cltv_expiry_delta: (6 << 4) | 0,
6148 htlc_minimum_msat: 0,
6149 htlc_maximum_msat: MAX_VALUE_MSAT,
6151 fee_proportional_millionths: 0,
6152 excess_data: Vec::new()
6154 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
6156 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6157 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6158 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6159 short_channel_id: 5,
6162 cltv_expiry_delta: (5 << 4) | 0,
6163 htlc_minimum_msat: 0,
6164 htlc_maximum_msat: MAX_VALUE_MSAT,
6166 fee_proportional_millionths: 0,
6167 excess_data: Vec::new()
6169 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
6171 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
6172 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6173 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6174 short_channel_id: 4,
6177 cltv_expiry_delta: (4 << 4) | 0,
6178 htlc_minimum_msat: 0,
6179 htlc_maximum_msat: MAX_VALUE_MSAT,
6181 fee_proportional_millionths: 0,
6182 excess_data: Vec::new()
6184 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6186 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6187 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
6188 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6189 short_channel_id: 3,
6192 cltv_expiry_delta: (3 << 4) | 0,
6193 htlc_minimum_msat: 0,
6194 htlc_maximum_msat: MAX_VALUE_MSAT,
6196 fee_proportional_millionths: 0,
6197 excess_data: Vec::new()
6199 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6201 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6202 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
6203 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6204 short_channel_id: 2,
6207 cltv_expiry_delta: (2 << 4) | 0,
6208 htlc_minimum_msat: 0,
6209 htlc_maximum_msat: MAX_VALUE_MSAT,
6211 fee_proportional_millionths: 0,
6212 excess_data: Vec::new()
6215 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6216 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6217 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6218 short_channel_id: 1,
6221 cltv_expiry_delta: (1 << 4) | 0,
6222 htlc_minimum_msat: 100,
6223 htlc_maximum_msat: MAX_VALUE_MSAT,
6225 fee_proportional_millionths: 0,
6226 excess_data: Vec::new()
6228 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6231 // Now ensure the route flows simply over nodes 1 and 4 to 6.
6232 let route_params = RouteParameters::from_payment_params_and_value(
6233 payment_params, 10_000);
6234 let route = get_route(&our_id, &route_params, &network.read_only(), None,
6235 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6236 assert_eq!(route.paths.len(), 1);
6237 assert_eq!(route.paths[0].hops.len(), 3);
6239 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6240 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6241 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6242 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6243 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6244 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6246 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6247 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6248 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6249 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6250 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6251 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6253 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6254 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6255 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6256 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6257 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6258 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6264 fn exact_fee_liquidity_limit() {
6265 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6266 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6267 // we calculated fees on a higher value, resulting in us ignoring such paths.
6268 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6269 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6270 let scorer = ln_test_utils::TestScorer::new();
6271 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6272 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6273 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6275 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6277 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6278 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6279 short_channel_id: 2,
6282 cltv_expiry_delta: 0,
6283 htlc_minimum_msat: 0,
6284 htlc_maximum_msat: 85_000,
6286 fee_proportional_millionths: 0,
6287 excess_data: Vec::new()
6290 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6291 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6292 short_channel_id: 12,
6295 cltv_expiry_delta: (4 << 4) | 1,
6296 htlc_minimum_msat: 0,
6297 htlc_maximum_msat: 270_000,
6299 fee_proportional_millionths: 1000000,
6300 excess_data: Vec::new()
6304 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6305 // 200% fee charged channel 13 in the 1-to-2 direction.
6306 let mut route_params = RouteParameters::from_payment_params_and_value(
6307 payment_params, 90_000);
6308 route_params.max_total_routing_fee_msat = Some(90_000*2);
6309 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6310 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6311 assert_eq!(route.paths.len(), 1);
6312 assert_eq!(route.paths[0].hops.len(), 2);
6314 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6315 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6316 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6317 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6318 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6319 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6321 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6322 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6323 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6324 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6325 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6326 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6331 fn htlc_max_reduction_below_min() {
6332 // Test that if, while walking the graph, we reduce the value being sent to meet an
6333 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6334 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6335 // resulting in us thinking there is no possible path, even if other paths exist.
6336 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6337 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6338 let scorer = ln_test_utils::TestScorer::new();
6339 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6340 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6341 let config = UserConfig::default();
6342 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6343 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6346 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6347 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6348 // then try to send 90_000.
6349 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6350 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6351 short_channel_id: 2,
6354 cltv_expiry_delta: 0,
6355 htlc_minimum_msat: 0,
6356 htlc_maximum_msat: 80_000,
6358 fee_proportional_millionths: 0,
6359 excess_data: Vec::new()
6361 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6362 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6363 short_channel_id: 4,
6366 cltv_expiry_delta: (4 << 4) | 1,
6367 htlc_minimum_msat: 90_000,
6368 htlc_maximum_msat: MAX_VALUE_MSAT,
6370 fee_proportional_millionths: 0,
6371 excess_data: Vec::new()
6375 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6376 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6377 // expensive) channels 12-13 path.
6378 let mut route_params = RouteParameters::from_payment_params_and_value(
6379 payment_params, 90_000);
6380 route_params.max_total_routing_fee_msat = Some(90_000*2);
6381 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6382 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6383 assert_eq!(route.paths.len(), 1);
6384 assert_eq!(route.paths[0].hops.len(), 2);
6386 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6387 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6388 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6389 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6390 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6391 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6393 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6394 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6395 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6396 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6397 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6398 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6403 fn multiple_direct_first_hops() {
6404 // Previously we'd only ever considered one first hop path per counterparty.
6405 // However, as we don't restrict users to one channel per peer, we really need to support
6406 // looking at all first hop paths.
6407 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6408 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6409 // route over multiple channels with the same first hop.
6410 let secp_ctx = Secp256k1::new();
6411 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6412 let logger = Arc::new(ln_test_utils::TestLogger::new());
6413 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6414 let scorer = ln_test_utils::TestScorer::new();
6415 let config = UserConfig::default();
6416 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6417 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6419 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6420 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6423 let route_params = RouteParameters::from_payment_params_and_value(
6424 payment_params.clone(), 100_000);
6425 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6426 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6427 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6428 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6429 assert_eq!(route.paths.len(), 1);
6430 assert_eq!(route.paths[0].hops.len(), 1);
6432 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6433 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6434 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6437 let route_params = RouteParameters::from_payment_params_and_value(
6438 payment_params.clone(), 100_000);
6439 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6440 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6441 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6442 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6443 assert_eq!(route.paths.len(), 2);
6444 assert_eq!(route.paths[0].hops.len(), 1);
6445 assert_eq!(route.paths[1].hops.len(), 1);
6447 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6448 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6450 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6451 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6453 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6454 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6458 // If we have a bunch of outbound channels to the same node, where most are not
6459 // sufficient to pay the full payment, but one is, we should default to just using the
6460 // one single channel that has sufficient balance, avoiding MPP.
6462 // If we have several options above the 3xpayment value threshold, we should pick the
6463 // smallest of them, avoiding further fragmenting our available outbound balance to
6465 let route_params = RouteParameters::from_payment_params_and_value(
6466 payment_params, 100_000);
6467 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6468 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6469 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6470 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6471 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6472 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6473 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6474 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6475 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6476 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6477 assert_eq!(route.paths.len(), 1);
6478 assert_eq!(route.paths[0].hops.len(), 1);
6480 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6481 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6482 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6487 fn prefers_shorter_route_with_higher_fees() {
6488 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6489 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6490 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6492 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6493 let scorer = ln_test_utils::TestScorer::new();
6494 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6495 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6496 let route_params = RouteParameters::from_payment_params_and_value(
6497 payment_params.clone(), 100);
6498 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6499 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6500 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6502 assert_eq!(route.get_total_fees(), 100);
6503 assert_eq!(route.get_total_amount(), 100);
6504 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6506 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6507 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6508 let scorer = FixedPenaltyScorer::with_penalty(100);
6509 let route_params = RouteParameters::from_payment_params_and_value(
6510 payment_params, 100);
6511 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6512 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6513 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6515 assert_eq!(route.get_total_fees(), 300);
6516 assert_eq!(route.get_total_amount(), 100);
6517 assert_eq!(path, vec![2, 4, 7, 10]);
6520 struct BadChannelScorer {
6521 short_channel_id: u64,
6525 impl Writeable for BadChannelScorer {
6526 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6528 impl ScoreLookUp for BadChannelScorer {
6529 type ScoreParams = ();
6530 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6531 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6535 struct BadNodeScorer {
6540 impl Writeable for BadNodeScorer {
6541 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6544 impl ScoreLookUp for BadNodeScorer {
6545 type ScoreParams = ();
6546 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6547 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6552 fn avoids_routing_through_bad_channels_and_nodes() {
6553 let (secp_ctx, network, _, _, logger) = build_graph();
6554 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6555 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6556 let network_graph = network.read_only();
6558 // A path to nodes[6] exists when no penalties are applied to any channel.
6559 let scorer = ln_test_utils::TestScorer::new();
6560 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6561 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6562 let route_params = RouteParameters::from_payment_params_and_value(
6563 payment_params, 100);
6564 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6565 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6566 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6568 assert_eq!(route.get_total_fees(), 100);
6569 assert_eq!(route.get_total_amount(), 100);
6570 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6572 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6573 let scorer = BadChannelScorer { short_channel_id: 6 };
6574 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6575 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6576 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6578 assert_eq!(route.get_total_fees(), 300);
6579 assert_eq!(route.get_total_amount(), 100);
6580 assert_eq!(path, vec![2, 4, 7, 10]);
6582 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6583 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6584 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6585 &scorer, &Default::default(), &random_seed_bytes) {
6586 Err(LightningError { err, .. } ) => {
6587 assert_eq!(err, "Failed to find a path to the given destination");
6589 Ok(_) => panic!("Expected error"),
6594 fn total_fees_single_path() {
6596 paths: vec![Path { hops: vec![
6598 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6599 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6600 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6603 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6604 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6605 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6608 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6609 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6610 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6612 ], blinded_tail: None }],
6616 assert_eq!(route.get_total_fees(), 250);
6617 assert_eq!(route.get_total_amount(), 225);
6621 fn total_fees_multi_path() {
6623 paths: vec![Path { hops: vec![
6625 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6626 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6627 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6630 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6631 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6632 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6634 ], blinded_tail: None }, Path { hops: vec![
6636 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6637 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6638 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6641 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6642 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6643 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6645 ], blinded_tail: None }],
6649 assert_eq!(route.get_total_fees(), 200);
6650 assert_eq!(route.get_total_amount(), 300);
6654 fn total_empty_route_no_panic() {
6655 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6656 // would both panic if the route was completely empty. We test to ensure they return 0
6657 // here, even though its somewhat nonsensical as a route.
6658 let route = Route { paths: Vec::new(), route_params: None };
6660 assert_eq!(route.get_total_fees(), 0);
6661 assert_eq!(route.get_total_amount(), 0);
6665 fn limits_total_cltv_delta() {
6666 let (secp_ctx, network, _, _, logger) = build_graph();
6667 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6668 let network_graph = network.read_only();
6670 let scorer = ln_test_utils::TestScorer::new();
6672 // Make sure that generally there is at least one route available
6673 let feasible_max_total_cltv_delta = 1008;
6674 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6675 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6676 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6677 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6678 let route_params = RouteParameters::from_payment_params_and_value(
6679 feasible_payment_params, 100);
6680 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6681 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6682 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6683 assert_ne!(path.len(), 0);
6685 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6686 let fail_max_total_cltv_delta = 23;
6687 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6688 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6689 let route_params = RouteParameters::from_payment_params_and_value(
6690 fail_payment_params, 100);
6691 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6692 &Default::default(), &random_seed_bytes)
6694 Err(LightningError { err, .. } ) => {
6695 assert_eq!(err, "Failed to find a path to the given destination");
6697 Ok(_) => panic!("Expected error"),
6702 fn avoids_recently_failed_paths() {
6703 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6704 // randomly inserting channels into it until we can't find a route anymore.
6705 let (secp_ctx, network, _, _, logger) = build_graph();
6706 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6707 let network_graph = network.read_only();
6709 let scorer = ln_test_utils::TestScorer::new();
6710 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6711 .with_max_path_count(1);
6712 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6713 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6715 // We should be able to find a route initially, and then after we fail a few random
6716 // channels eventually we won't be able to any longer.
6717 let route_params = RouteParameters::from_payment_params_and_value(
6718 payment_params.clone(), 100);
6719 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6720 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6722 let route_params = RouteParameters::from_payment_params_and_value(
6723 payment_params.clone(), 100);
6724 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6725 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6727 for chan in route.paths[0].hops.iter() {
6728 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6730 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6731 % route.paths[0].hops.len();
6732 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6738 fn limits_path_length() {
6739 let (secp_ctx, network, _, _, logger) = build_line_graph();
6740 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6741 let network_graph = network.read_only();
6743 let scorer = ln_test_utils::TestScorer::new();
6744 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6745 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6747 // First check we can actually create a long route on this graph.
6748 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6749 let route_params = RouteParameters::from_payment_params_and_value(
6750 feasible_payment_params, 100);
6751 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6752 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6753 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6754 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6756 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6757 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6758 let route_params = RouteParameters::from_payment_params_and_value(
6759 fail_payment_params, 100);
6760 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6761 &Default::default(), &random_seed_bytes)
6763 Err(LightningError { err, .. } ) => {
6764 assert_eq!(err, "Failed to find a path to the given destination");
6766 Ok(_) => panic!("Expected error"),
6771 fn adds_and_limits_cltv_offset() {
6772 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6773 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6775 let scorer = ln_test_utils::TestScorer::new();
6777 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6778 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6779 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6780 let route_params = RouteParameters::from_payment_params_and_value(
6781 payment_params.clone(), 100);
6782 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6783 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6784 assert_eq!(route.paths.len(), 1);
6786 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6788 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6789 let mut route_default = route.clone();
6790 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6791 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6792 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6793 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6794 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6796 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6797 let mut route_limited = route.clone();
6798 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6799 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6800 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6801 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6802 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6806 fn adds_plausible_cltv_offset() {
6807 let (secp_ctx, network, _, _, logger) = build_graph();
6808 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6809 let network_graph = network.read_only();
6810 let network_nodes = network_graph.nodes();
6811 let network_channels = network_graph.channels();
6812 let scorer = ln_test_utils::TestScorer::new();
6813 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6814 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6815 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6817 let route_params = RouteParameters::from_payment_params_and_value(
6818 payment_params.clone(), 100);
6819 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6820 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6821 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6823 let mut path_plausibility = vec![];
6825 for p in route.paths {
6826 // 1. Select random observation point
6827 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6828 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6830 prng.process_in_place(&mut random_bytes);
6831 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6832 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6834 // 2. Calculate what CLTV expiry delta we would observe there
6835 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6837 // 3. Starting from the observation point, find candidate paths
6838 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6839 candidates.push_back((observation_point, vec![]));
6841 let mut found_plausible_candidate = false;
6843 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6844 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6845 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6846 found_plausible_candidate = true;
6847 break 'candidate_loop;
6851 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6852 for channel_id in &cur_node.channels {
6853 if let Some(channel_info) = network_channels.get(&channel_id) {
6854 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6855 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6856 if cur_path_cltv_deltas.iter().sum::<u32>()
6857 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6858 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6859 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6860 candidates.push_back((*next_id, new_path_cltv_deltas));
6868 path_plausibility.push(found_plausible_candidate);
6870 assert!(path_plausibility.iter().all(|x| *x));
6874 fn builds_correct_path_from_hops() {
6875 let (secp_ctx, network, _, _, logger) = build_graph();
6876 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6877 let network_graph = network.read_only();
6879 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6880 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6882 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6883 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6884 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6885 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6886 Arc::clone(&logger), &random_seed_bytes).unwrap();
6887 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6888 assert_eq!(hops.len(), route.paths[0].hops.len());
6889 for (idx, hop_pubkey) in hops.iter().enumerate() {
6890 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6895 fn avoids_saturating_channels() {
6896 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6897 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6898 let decay_params = ProbabilisticScoringDecayParameters::default();
6899 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6901 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6902 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6903 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6904 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6905 short_channel_id: 4,
6908 cltv_expiry_delta: (4 << 4) | 1,
6909 htlc_minimum_msat: 0,
6910 htlc_maximum_msat: 250_000_000,
6912 fee_proportional_millionths: 0,
6913 excess_data: Vec::new()
6915 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6916 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6917 short_channel_id: 13,
6920 cltv_expiry_delta: (13 << 4) | 1,
6921 htlc_minimum_msat: 0,
6922 htlc_maximum_msat: 250_000_000,
6924 fee_proportional_millionths: 0,
6925 excess_data: Vec::new()
6928 let config = UserConfig::default();
6929 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6930 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6932 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6933 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6934 // 100,000 sats is less than the available liquidity on each channel, set above.
6935 let route_params = RouteParameters::from_payment_params_and_value(
6936 payment_params, 100_000_000);
6937 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6938 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6939 assert_eq!(route.paths.len(), 2);
6940 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6941 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6944 #[cfg(not(feature = "no-std"))]
6945 pub(super) fn random_init_seed() -> u64 {
6946 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6947 use core::hash::{BuildHasher, Hasher};
6948 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6949 println!("Using seed of {}", seed);
6954 #[cfg(not(feature = "no-std"))]
6955 fn generate_routes() {
6956 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6958 let logger = ln_test_utils::TestLogger::new();
6959 let graph = match super::bench_utils::read_network_graph(&logger) {
6967 let params = ProbabilisticScoringFeeParameters::default();
6968 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6969 let features = super::Bolt11InvoiceFeatures::empty();
6971 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6975 #[cfg(not(feature = "no-std"))]
6976 fn generate_routes_mpp() {
6977 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6979 let logger = ln_test_utils::TestLogger::new();
6980 let graph = match super::bench_utils::read_network_graph(&logger) {
6988 let params = ProbabilisticScoringFeeParameters::default();
6989 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6990 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
6992 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6996 #[cfg(not(feature = "no-std"))]
6997 fn generate_large_mpp_routes() {
6998 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
7000 let logger = ln_test_utils::TestLogger::new();
7001 let graph = match super::bench_utils::read_network_graph(&logger) {
7009 let params = ProbabilisticScoringFeeParameters::default();
7010 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
7011 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7013 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
7017 fn honors_manual_penalties() {
7018 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
7019 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7021 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7022 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7024 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
7025 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
7027 // First check set manual penalties are returned by the scorer.
7028 let usage = ChannelUsage {
7030 inflight_htlc_msat: 0,
7031 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
7033 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
7034 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
7035 let network_graph = network_graph.read_only();
7036 let channels = network_graph.channels();
7037 let channel = channels.get(&5).unwrap();
7038 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
7039 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop(PublicHopCandidate {
7041 short_channel_id: 5,
7043 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
7045 // Then check we can get a normal route
7046 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
7047 let route_params = RouteParameters::from_payment_params_and_value(
7048 payment_params, 100);
7049 let route = get_route(&our_id, &route_params, &network_graph, None,
7050 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
7051 assert!(route.is_ok());
7053 // Then check that we can't get a route if we ban an intermediate node.
7054 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
7055 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7056 assert!(route.is_err());
7058 // Finally make sure we can route again, when we remove the ban.
7059 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
7060 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7061 assert!(route.is_ok());
7065 fn abide_by_route_hint_max_htlc() {
7066 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
7067 // params in the final route.
7068 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7069 let netgraph = network_graph.read_only();
7070 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7071 let scorer = ln_test_utils::TestScorer::new();
7072 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7073 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7074 let config = UserConfig::default();
7076 let max_htlc_msat = 50_000;
7077 let route_hint_1 = RouteHint(vec![RouteHintHop {
7078 src_node_id: nodes[2],
7079 short_channel_id: 42,
7082 proportional_millionths: 0,
7084 cltv_expiry_delta: 10,
7085 htlc_minimum_msat: None,
7086 htlc_maximum_msat: Some(max_htlc_msat),
7088 let dest_node_id = ln_test_utils::pubkey(42);
7089 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7090 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
7091 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7094 // Make sure we'll error if our route hints don't have enough liquidity according to their
7095 // htlc_maximum_msat.
7096 let mut route_params = RouteParameters::from_payment_params_and_value(
7097 payment_params, max_htlc_msat + 1);
7098 route_params.max_total_routing_fee_msat = None;
7099 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
7100 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
7103 assert_eq!(err, "Failed to find a sufficient route to the given destination");
7104 } else { panic!(); }
7106 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
7107 let mut route_hint_2 = route_hint_1.clone();
7108 route_hint_2.0[0].short_channel_id = 43;
7109 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7110 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7111 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7113 let mut route_params = RouteParameters::from_payment_params_and_value(
7114 payment_params, max_htlc_msat + 1);
7115 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
7116 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
7117 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7118 assert_eq!(route.paths.len(), 2);
7119 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7120 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7124 fn direct_channel_to_hints_with_max_htlc() {
7125 // Check that if we have a first hop channel peer that's connected to multiple provided route
7126 // hints, that we properly split the payment between the route hints if needed.
7127 let logger = Arc::new(ln_test_utils::TestLogger::new());
7128 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7129 let scorer = ln_test_utils::TestScorer::new();
7130 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7131 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7132 let config = UserConfig::default();
7134 let our_node_id = ln_test_utils::pubkey(42);
7135 let intermed_node_id = ln_test_utils::pubkey(43);
7136 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7138 let amt_msat = 900_000;
7139 let max_htlc_msat = 500_000;
7140 let route_hint_1 = RouteHint(vec![RouteHintHop {
7141 src_node_id: intermed_node_id,
7142 short_channel_id: 44,
7145 proportional_millionths: 0,
7147 cltv_expiry_delta: 10,
7148 htlc_minimum_msat: None,
7149 htlc_maximum_msat: Some(max_htlc_msat),
7151 src_node_id: intermed_node_id,
7152 short_channel_id: 45,
7155 proportional_millionths: 0,
7157 cltv_expiry_delta: 10,
7158 htlc_minimum_msat: None,
7159 // Check that later route hint max htlcs don't override earlier ones
7160 htlc_maximum_msat: Some(max_htlc_msat - 50),
7162 let mut route_hint_2 = route_hint_1.clone();
7163 route_hint_2.0[0].short_channel_id = 46;
7164 route_hint_2.0[1].short_channel_id = 47;
7165 let dest_node_id = ln_test_utils::pubkey(44);
7166 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7167 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7168 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7171 let route_params = RouteParameters::from_payment_params_and_value(
7172 payment_params, amt_msat);
7173 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7174 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7175 &Default::default(), &random_seed_bytes).unwrap();
7176 assert_eq!(route.paths.len(), 2);
7177 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7178 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7179 assert_eq!(route.get_total_amount(), amt_msat);
7181 // Re-run but with two first hop channels connected to the same route hint peers that must be
7183 let first_hops = vec![
7184 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7185 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7187 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7188 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7189 &Default::default(), &random_seed_bytes).unwrap();
7190 assert_eq!(route.paths.len(), 2);
7191 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7192 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7193 assert_eq!(route.get_total_amount(), amt_msat);
7195 // Make sure this works for blinded route hints.
7196 let blinded_path = BlindedPath {
7197 introduction_node_id: intermed_node_id,
7198 blinding_point: ln_test_utils::pubkey(42),
7200 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
7201 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
7204 let blinded_payinfo = BlindedPayInfo {
7206 fee_proportional_millionths: 0,
7207 htlc_minimum_msat: 1,
7208 htlc_maximum_msat: max_htlc_msat,
7209 cltv_expiry_delta: 10,
7210 features: BlindedHopFeatures::empty(),
7212 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7213 let payment_params = PaymentParameters::blinded(vec![
7214 (blinded_payinfo.clone(), blinded_path.clone()),
7215 (blinded_payinfo.clone(), blinded_path.clone())])
7216 .with_bolt12_features(bolt12_features).unwrap();
7217 let route_params = RouteParameters::from_payment_params_and_value(
7218 payment_params, amt_msat);
7219 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7220 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7221 &Default::default(), &random_seed_bytes).unwrap();
7222 assert_eq!(route.paths.len(), 2);
7223 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7224 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7225 assert_eq!(route.get_total_amount(), amt_msat);
7229 fn blinded_route_ser() {
7230 let blinded_path_1 = BlindedPath {
7231 introduction_node_id: ln_test_utils::pubkey(42),
7232 blinding_point: ln_test_utils::pubkey(43),
7234 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7235 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7238 let blinded_path_2 = BlindedPath {
7239 introduction_node_id: ln_test_utils::pubkey(46),
7240 blinding_point: ln_test_utils::pubkey(47),
7242 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7243 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7246 // (De)serialize a Route with 1 blinded path out of two total paths.
7247 let mut route = Route { paths: vec![Path {
7248 hops: vec![RouteHop {
7249 pubkey: ln_test_utils::pubkey(50),
7250 node_features: NodeFeatures::empty(),
7251 short_channel_id: 42,
7252 channel_features: ChannelFeatures::empty(),
7254 cltv_expiry_delta: 0,
7255 maybe_announced_channel: true,
7257 blinded_tail: Some(BlindedTail {
7258 hops: blinded_path_1.blinded_hops,
7259 blinding_point: blinded_path_1.blinding_point,
7260 excess_final_cltv_expiry_delta: 40,
7261 final_value_msat: 100,
7263 hops: vec![RouteHop {
7264 pubkey: ln_test_utils::pubkey(51),
7265 node_features: NodeFeatures::empty(),
7266 short_channel_id: 43,
7267 channel_features: ChannelFeatures::empty(),
7269 cltv_expiry_delta: 0,
7270 maybe_announced_channel: true,
7271 }], blinded_tail: None }],
7274 let encoded_route = route.encode();
7275 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7276 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7277 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7279 // (De)serialize a Route with two paths, each containing a blinded tail.
7280 route.paths[1].blinded_tail = Some(BlindedTail {
7281 hops: blinded_path_2.blinded_hops,
7282 blinding_point: blinded_path_2.blinding_point,
7283 excess_final_cltv_expiry_delta: 41,
7284 final_value_msat: 101,
7286 let encoded_route = route.encode();
7287 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7288 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7289 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7293 fn blinded_path_inflight_processing() {
7294 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7295 // account for the blinded tail's final amount_msat.
7296 let mut inflight_htlcs = InFlightHtlcs::new();
7297 let blinded_path = BlindedPath {
7298 introduction_node_id: ln_test_utils::pubkey(43),
7299 blinding_point: ln_test_utils::pubkey(48),
7300 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7303 hops: vec![RouteHop {
7304 pubkey: ln_test_utils::pubkey(42),
7305 node_features: NodeFeatures::empty(),
7306 short_channel_id: 42,
7307 channel_features: ChannelFeatures::empty(),
7309 cltv_expiry_delta: 0,
7310 maybe_announced_channel: false,
7313 pubkey: blinded_path.introduction_node_id,
7314 node_features: NodeFeatures::empty(),
7315 short_channel_id: 43,
7316 channel_features: ChannelFeatures::empty(),
7318 cltv_expiry_delta: 0,
7319 maybe_announced_channel: false,
7321 blinded_tail: Some(BlindedTail {
7322 hops: blinded_path.blinded_hops,
7323 blinding_point: blinded_path.blinding_point,
7324 excess_final_cltv_expiry_delta: 0,
7325 final_value_msat: 200,
7328 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7329 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7330 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7334 fn blinded_path_cltv_shadow_offset() {
7335 // Make sure we add a shadow offset when sending to blinded paths.
7336 let blinded_path = BlindedPath {
7337 introduction_node_id: ln_test_utils::pubkey(43),
7338 blinding_point: ln_test_utils::pubkey(44),
7340 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7341 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7344 let mut route = Route { paths: vec![Path {
7345 hops: vec![RouteHop {
7346 pubkey: ln_test_utils::pubkey(42),
7347 node_features: NodeFeatures::empty(),
7348 short_channel_id: 42,
7349 channel_features: ChannelFeatures::empty(),
7351 cltv_expiry_delta: 0,
7352 maybe_announced_channel: false,
7355 pubkey: blinded_path.introduction_node_id,
7356 node_features: NodeFeatures::empty(),
7357 short_channel_id: 43,
7358 channel_features: ChannelFeatures::empty(),
7360 cltv_expiry_delta: 0,
7361 maybe_announced_channel: false,
7364 blinded_tail: Some(BlindedTail {
7365 hops: blinded_path.blinded_hops,
7366 blinding_point: blinded_path.blinding_point,
7367 excess_final_cltv_expiry_delta: 0,
7368 final_value_msat: 200,
7370 }], route_params: None};
7372 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7373 let (_, network_graph, _, _, _) = build_line_graph();
7374 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7375 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7376 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7380 fn simple_blinded_route_hints() {
7381 do_simple_blinded_route_hints(1);
7382 do_simple_blinded_route_hints(2);
7383 do_simple_blinded_route_hints(3);
7386 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7387 // Check that we can generate a route to a blinded path with the expected hops.
7388 let (secp_ctx, network, _, _, logger) = build_graph();
7389 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7390 let network_graph = network.read_only();
7392 let scorer = ln_test_utils::TestScorer::new();
7393 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7394 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7396 let mut blinded_path = BlindedPath {
7397 introduction_node_id: nodes[2],
7398 blinding_point: ln_test_utils::pubkey(42),
7399 blinded_hops: Vec::with_capacity(num_blinded_hops),
7401 for i in 0..num_blinded_hops {
7402 blinded_path.blinded_hops.push(
7403 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7406 let blinded_payinfo = BlindedPayInfo {
7408 fee_proportional_millionths: 500,
7409 htlc_minimum_msat: 1000,
7410 htlc_maximum_msat: 100_000_000,
7411 cltv_expiry_delta: 15,
7412 features: BlindedHopFeatures::empty(),
7415 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7416 let route_params = RouteParameters::from_payment_params_and_value(
7417 payment_params, 1001);
7418 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7419 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7420 assert_eq!(route.paths.len(), 1);
7421 assert_eq!(route.paths[0].hops.len(), 2);
7423 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7424 assert_eq!(tail.hops, blinded_path.blinded_hops);
7425 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7426 assert_eq!(tail.final_value_msat, 1001);
7428 let final_hop = route.paths[0].hops.last().unwrap();
7429 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
7430 if tail.hops.len() > 1 {
7431 assert_eq!(final_hop.fee_msat,
7432 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7433 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7435 assert_eq!(final_hop.fee_msat, 0);
7436 assert_eq!(final_hop.cltv_expiry_delta, 0);
7441 fn blinded_path_routing_errors() {
7442 // Check that we can generate a route to a blinded path with the expected hops.
7443 let (secp_ctx, network, _, _, logger) = build_graph();
7444 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7445 let network_graph = network.read_only();
7447 let scorer = ln_test_utils::TestScorer::new();
7448 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7449 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7451 let mut invalid_blinded_path = BlindedPath {
7452 introduction_node_id: nodes[2],
7453 blinding_point: ln_test_utils::pubkey(42),
7455 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7458 let blinded_payinfo = BlindedPayInfo {
7460 fee_proportional_millionths: 500,
7461 htlc_minimum_msat: 1000,
7462 htlc_maximum_msat: 100_000_000,
7463 cltv_expiry_delta: 15,
7464 features: BlindedHopFeatures::empty(),
7467 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7468 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
7469 let payment_params = PaymentParameters::blinded(vec![
7470 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7471 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7472 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7473 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7474 &scorer, &Default::default(), &random_seed_bytes)
7476 Err(LightningError { err, .. }) => {
7477 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7479 _ => panic!("Expected error")
7482 invalid_blinded_path.introduction_node_id = our_id;
7483 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7484 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7485 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7486 &Default::default(), &random_seed_bytes)
7488 Err(LightningError { err, .. }) => {
7489 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7491 _ => panic!("Expected error")
7494 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
7495 invalid_blinded_path.blinded_hops.clear();
7496 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7497 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7498 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7499 &Default::default(), &random_seed_bytes)
7501 Err(LightningError { err, .. }) => {
7502 assert_eq!(err, "0-hop blinded path provided");
7504 _ => panic!("Expected error")
7509 fn matching_intro_node_paths_provided() {
7510 // Check that if multiple blinded paths with the same intro node are provided in payment
7511 // parameters, we'll return the correct paths in the resulting MPP route.
7512 let (secp_ctx, network, _, _, logger) = build_graph();
7513 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7514 let network_graph = network.read_only();
7516 let scorer = ln_test_utils::TestScorer::new();
7517 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7518 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7519 let config = UserConfig::default();
7521 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7522 let blinded_path_1 = BlindedPath {
7523 introduction_node_id: nodes[2],
7524 blinding_point: ln_test_utils::pubkey(42),
7526 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7527 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7530 let blinded_payinfo_1 = BlindedPayInfo {
7532 fee_proportional_millionths: 0,
7533 htlc_minimum_msat: 0,
7534 htlc_maximum_msat: 30_000,
7535 cltv_expiry_delta: 0,
7536 features: BlindedHopFeatures::empty(),
7539 let mut blinded_path_2 = blinded_path_1.clone();
7540 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7541 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7542 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7544 let blinded_hints = vec![
7545 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7546 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7548 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7549 .with_bolt12_features(bolt12_features).unwrap();
7551 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7552 route_params.max_total_routing_fee_msat = Some(100_000);
7553 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7554 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7555 assert_eq!(route.paths.len(), 2);
7556 let mut total_amount_paid_msat = 0;
7557 for path in route.paths.into_iter() {
7558 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7559 if let Some(bt) = &path.blinded_tail {
7560 assert_eq!(bt.blinding_point,
7561 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7562 .map(|(_, bp)| bp.blinding_point).unwrap());
7563 } else { panic!(); }
7564 total_amount_paid_msat += path.final_value_msat();
7566 assert_eq!(total_amount_paid_msat, 100_000);
7570 fn direct_to_intro_node() {
7571 // This previously caused a debug panic in the router when asserting
7572 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7573 // direct channels we failed to account for the fee charged for use of the blinded path.
7576 // node0 -1(1)2 - node1
7577 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7578 // doesn't account for the blinded path fee.
7580 let secp_ctx = Secp256k1::new();
7581 let logger = Arc::new(ln_test_utils::TestLogger::new());
7582 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7583 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7584 let scorer = ln_test_utils::TestScorer::new();
7585 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7586 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7588 let amt_msat = 10_000_000;
7589 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7590 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7591 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7592 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7593 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7594 short_channel_id: 1,
7597 cltv_expiry_delta: 42,
7598 htlc_minimum_msat: 1_000,
7599 htlc_maximum_msat: 10_000_000,
7601 fee_proportional_millionths: 0,
7602 excess_data: Vec::new()
7604 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7605 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7606 short_channel_id: 1,
7609 cltv_expiry_delta: 42,
7610 htlc_minimum_msat: 1_000,
7611 htlc_maximum_msat: 10_000_000,
7613 fee_proportional_millionths: 0,
7614 excess_data: Vec::new()
7616 let first_hops = vec![
7617 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7619 let blinded_path = BlindedPath {
7620 introduction_node_id: nodes[1],
7621 blinding_point: ln_test_utils::pubkey(42),
7623 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7624 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7627 let blinded_payinfo = BlindedPayInfo {
7628 fee_base_msat: 1000,
7629 fee_proportional_millionths: 0,
7630 htlc_minimum_msat: 1000,
7631 htlc_maximum_msat: MAX_VALUE_MSAT,
7632 cltv_expiry_delta: 0,
7633 features: BlindedHopFeatures::empty(),
7635 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7637 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7639 let netgraph = network_graph.read_only();
7640 let route_params = RouteParameters::from_payment_params_and_value(
7641 payment_params.clone(), amt_msat);
7642 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7643 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7644 &Default::default(), &random_seed_bytes) {
7645 assert_eq!(err, "Failed to find a path to the given destination");
7646 } else { panic!("Expected error") }
7648 // Sending an exact amount accounting for the blinded path fee works.
7649 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7650 let route_params = RouteParameters::from_payment_params_and_value(
7651 payment_params, amt_minus_blinded_path_fee);
7652 let route = get_route(&nodes[0], &route_params, &netgraph,
7653 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7654 &Default::default(), &random_seed_bytes).unwrap();
7655 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7656 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7660 fn direct_to_matching_intro_nodes() {
7661 // This previously caused us to enter `unreachable` code in the following situation:
7662 // 1. We add a route candidate for intro_node contributing a high amount
7663 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7664 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7665 // amount, and update our route candidate for intro_node for the lower amount
7666 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7667 // lower contribution amount, but fail (this was previously caused by failure to account for
7668 // blinded path fees when adding first_hop<>intro_node candidates)
7669 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7670 // candidate still thinks its path is contributing the original higher amount. This caused us
7671 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7673 let secp_ctx = Secp256k1::new();
7674 let logger = Arc::new(ln_test_utils::TestLogger::new());
7675 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7676 let scorer = ln_test_utils::TestScorer::new();
7677 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7678 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7679 let config = UserConfig::default();
7681 // Values are taken from the fuzz input that uncovered this panic.
7682 let amt_msat = 21_7020_5185_1403_2640;
7683 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7684 let first_hops = vec![
7685 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7686 18446744073709551615)];
7688 let blinded_path = BlindedPath {
7689 introduction_node_id: nodes[1],
7690 blinding_point: ln_test_utils::pubkey(42),
7692 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7693 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7696 let blinded_payinfo = BlindedPayInfo {
7697 fee_base_msat: 5046_2720,
7698 fee_proportional_millionths: 0,
7699 htlc_minimum_msat: 4503_5996_2737_0496,
7700 htlc_maximum_msat: 45_0359_9627_3704_9600,
7701 cltv_expiry_delta: 0,
7702 features: BlindedHopFeatures::empty(),
7704 let mut blinded_hints = vec![
7705 (blinded_payinfo.clone(), blinded_path.clone()),
7706 (blinded_payinfo.clone(), blinded_path.clone()),
7708 blinded_hints[1].0.fee_base_msat = 419_4304;
7709 blinded_hints[1].0.fee_proportional_millionths = 257;
7710 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7711 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7712 blinded_hints[1].0.cltv_expiry_delta = 0;
7714 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7715 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7716 .with_bolt12_features(bolt12_features).unwrap();
7718 let netgraph = network_graph.read_only();
7719 let route_params = RouteParameters::from_payment_params_and_value(
7720 payment_params, amt_msat);
7721 let route = get_route(&nodes[0], &route_params, &netgraph,
7722 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7723 &Default::default(), &random_seed_bytes).unwrap();
7724 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7725 assert_eq!(route.get_total_amount(), amt_msat);
7729 fn we_are_intro_node_candidate_hops() {
7730 // This previously led to a panic in the router because we'd generate a Path with only a
7731 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7732 // where the origin node is the intro node. We now fully disallow considering candidate hops
7733 // where the origin node is the intro node.
7734 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7735 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7736 let scorer = ln_test_utils::TestScorer::new();
7737 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7738 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7739 let config = UserConfig::default();
7741 // Values are taken from the fuzz input that uncovered this panic.
7742 let amt_msat = 21_7020_5185_1423_0019;
7744 let blinded_path = BlindedPath {
7745 introduction_node_id: our_id,
7746 blinding_point: ln_test_utils::pubkey(42),
7748 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7749 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7752 let blinded_payinfo = BlindedPayInfo {
7753 fee_base_msat: 5052_9027,
7754 fee_proportional_millionths: 0,
7755 htlc_minimum_msat: 21_7020_5185_1423_0019,
7756 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7757 cltv_expiry_delta: 0,
7758 features: BlindedHopFeatures::empty(),
7760 let mut blinded_hints = vec![
7761 (blinded_payinfo.clone(), blinded_path.clone()),
7762 (blinded_payinfo.clone(), blinded_path.clone()),
7764 blinded_hints[1].1.introduction_node_id = nodes[6];
7766 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7767 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7768 .with_bolt12_features(bolt12_features.clone()).unwrap();
7770 let netgraph = network_graph.read_only();
7771 let route_params = RouteParameters::from_payment_params_and_value(
7772 payment_params, amt_msat);
7773 if let Err(LightningError { err, .. }) = get_route(
7774 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7776 assert_eq!(err, "Failed to find a path to the given destination");
7781 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7782 // This previously led to a debug panic in the router because we'd find an invalid Path with
7783 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7784 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7785 // the payment, when it was intended to only include the final value of the payment.
7786 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7787 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7788 let scorer = ln_test_utils::TestScorer::new();
7789 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7790 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7791 let config = UserConfig::default();
7793 // Values are taken from the fuzz input that uncovered this panic.
7794 let amt_msat = 21_7020_5185_1423_0019;
7796 let blinded_path = BlindedPath {
7797 introduction_node_id: our_id,
7798 blinding_point: ln_test_utils::pubkey(42),
7800 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7801 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7804 let blinded_payinfo = BlindedPayInfo {
7805 fee_base_msat: 10_4425_1395,
7806 fee_proportional_millionths: 0,
7807 htlc_minimum_msat: 21_7301_9934_9094_0931,
7808 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7809 cltv_expiry_delta: 0,
7810 features: BlindedHopFeatures::empty(),
7812 let mut blinded_hints = vec![
7813 (blinded_payinfo.clone(), blinded_path.clone()),
7814 (blinded_payinfo.clone(), blinded_path.clone()),
7815 (blinded_payinfo.clone(), blinded_path.clone()),
7817 blinded_hints[1].0.fee_base_msat = 5052_9027;
7818 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7819 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7821 blinded_hints[2].1.introduction_node_id = nodes[6];
7823 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7824 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7825 .with_bolt12_features(bolt12_features.clone()).unwrap();
7827 let netgraph = network_graph.read_only();
7828 let route_params = RouteParameters::from_payment_params_and_value(
7829 payment_params, amt_msat);
7830 if let Err(LightningError { err, .. }) = get_route(
7831 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7833 assert_eq!(err, "Failed to find a path to the given destination");
7838 fn min_htlc_overpay_violates_max_htlc() {
7839 do_min_htlc_overpay_violates_max_htlc(true);
7840 do_min_htlc_overpay_violates_max_htlc(false);
7842 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7843 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7844 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7845 // to `targets` and build an invalid path with it, and subsquently hit a debug panic asserting
7846 // that the used liquidity for a hop was less than its available liquidity limit.
7847 let secp_ctx = Secp256k1::new();
7848 let logger = Arc::new(ln_test_utils::TestLogger::new());
7849 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7850 let scorer = ln_test_utils::TestScorer::new();
7851 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7852 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7853 let config = UserConfig::default();
7855 // Values are taken from the fuzz input that uncovered this panic.
7856 let amt_msat = 7_4009_8048;
7857 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7858 let first_hop_outbound_capacity = 2_7345_2000;
7859 let first_hops = vec![get_channel_details(
7860 Some(200), nodes[0], channelmanager::provided_init_features(&config),
7861 first_hop_outbound_capacity
7864 let base_fee = 1_6778_3453;
7865 let htlc_min = 2_5165_8240;
7866 let payment_params = if blinded_payee {
7867 let blinded_path = BlindedPath {
7868 introduction_node_id: nodes[0],
7869 blinding_point: ln_test_utils::pubkey(42),
7871 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7872 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7875 let blinded_payinfo = BlindedPayInfo {
7876 fee_base_msat: base_fee,
7877 fee_proportional_millionths: 0,
7878 htlc_minimum_msat: htlc_min,
7879 htlc_maximum_msat: htlc_min * 1000,
7880 cltv_expiry_delta: 0,
7881 features: BlindedHopFeatures::empty(),
7883 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7884 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
7885 .with_bolt12_features(bolt12_features.clone()).unwrap()
7887 let route_hint = RouteHint(vec![RouteHintHop {
7888 src_node_id: nodes[0],
7889 short_channel_id: 42,
7891 base_msat: base_fee,
7892 proportional_millionths: 0,
7894 cltv_expiry_delta: 10,
7895 htlc_minimum_msat: Some(htlc_min),
7896 htlc_maximum_msat: None,
7899 PaymentParameters::from_node_id(nodes[1], 42)
7900 .with_route_hints(vec![route_hint]).unwrap()
7901 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7904 let netgraph = network_graph.read_only();
7905 let route_params = RouteParameters::from_payment_params_and_value(
7906 payment_params, amt_msat);
7907 if let Err(LightningError { err, .. }) = get_route(
7908 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7909 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7911 assert_eq!(err, "Failed to find a path to the given destination");
7916 fn previously_used_liquidity_violates_max_htlc() {
7917 do_previously_used_liquidity_violates_max_htlc(true);
7918 do_previously_used_liquidity_violates_max_htlc(false);
7921 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
7922 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
7923 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
7924 // candidate. In this case, the candidate does not have enough due to a previous path taking up
7925 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
7926 // asserting that the used liquidity for a hop was less than its available liquidity limit.
7927 let secp_ctx = Secp256k1::new();
7928 let logger = Arc::new(ln_test_utils::TestLogger::new());
7929 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7930 let scorer = ln_test_utils::TestScorer::new();
7931 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7932 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7933 let config = UserConfig::default();
7935 // Values are taken from the fuzz input that uncovered this panic.
7936 let amt_msat = 52_4288;
7937 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7938 let first_hops = vec![get_channel_details(
7939 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
7940 ), get_channel_details(
7941 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
7944 let base_fees = [0, 425_9840, 0, 0];
7945 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
7946 let payment_params = if blinded_payee {
7947 let blinded_path = BlindedPath {
7948 introduction_node_id: nodes[0],
7949 blinding_point: ln_test_utils::pubkey(42),
7951 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7952 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7955 let mut blinded_hints = Vec::new();
7956 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
7957 blinded_hints.push((BlindedPayInfo {
7958 fee_base_msat: *base_fee,
7959 fee_proportional_millionths: 0,
7960 htlc_minimum_msat: *htlc_min,
7961 htlc_maximum_msat: htlc_min * 100,
7962 cltv_expiry_delta: 10,
7963 features: BlindedHopFeatures::empty(),
7964 }, blinded_path.clone()));
7966 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7967 PaymentParameters::blinded(blinded_hints.clone())
7968 .with_bolt12_features(bolt12_features.clone()).unwrap()
7970 let mut route_hints = Vec::new();
7971 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
7972 route_hints.push(RouteHint(vec![RouteHintHop {
7973 src_node_id: nodes[0],
7974 short_channel_id: 42 + idx as u64,
7976 base_msat: *base_fee,
7977 proportional_millionths: 0,
7979 cltv_expiry_delta: 10,
7980 htlc_minimum_msat: Some(*htlc_min),
7981 htlc_maximum_msat: Some(htlc_min * 100),
7984 PaymentParameters::from_node_id(nodes[1], 42)
7985 .with_route_hints(route_hints).unwrap()
7986 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7989 let netgraph = network_graph.read_only();
7990 let route_params = RouteParameters::from_payment_params_and_value(
7991 payment_params, amt_msat);
7993 let route = get_route(
7994 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7995 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7997 assert_eq!(route.paths.len(), 1);
7998 assert_eq!(route.get_total_amount(), amt_msat);
8002 fn candidate_path_min() {
8003 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
8004 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
8005 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
8006 // would add a connecting first_hop node that did not have enough contribution amount, leading
8007 // to a debug panic upon invalid path construction.
8008 let secp_ctx = Secp256k1::new();
8009 let logger = Arc::new(ln_test_utils::TestLogger::new());
8010 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8011 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
8012 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8013 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8014 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8015 let config = UserConfig::default();
8017 // Values are taken from the fuzz input that uncovered this panic.
8018 let amt_msat = 7_4009_8048;
8019 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
8020 let first_hops = vec![get_channel_details(
8021 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
8024 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
8025 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8026 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8027 short_channel_id: 6,
8030 cltv_expiry_delta: (6 << 4) | 0,
8031 htlc_minimum_msat: 0,
8032 htlc_maximum_msat: MAX_VALUE_MSAT,
8034 fee_proportional_millionths: 0,
8035 excess_data: Vec::new()
8037 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
8039 let htlc_min = 2_5165_8240;
8040 let blinded_hints = vec![
8042 fee_base_msat: 1_6778_3453,
8043 fee_proportional_millionths: 0,
8044 htlc_minimum_msat: htlc_min,
8045 htlc_maximum_msat: htlc_min * 100,
8046 cltv_expiry_delta: 10,
8047 features: BlindedHopFeatures::empty(),
8049 introduction_node_id: nodes[0],
8050 blinding_point: ln_test_utils::pubkey(42),
8052 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8053 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8057 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8058 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8059 .with_bolt12_features(bolt12_features.clone()).unwrap();
8060 let route_params = RouteParameters::from_payment_params_and_value(
8061 payment_params, amt_msat);
8062 let netgraph = network_graph.read_only();
8064 if let Err(LightningError { err, .. }) = get_route(
8065 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8066 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8069 assert_eq!(err, "Failed to find a path to the given destination");
8074 fn path_contribution_includes_min_htlc_overpay() {
8075 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
8076 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
8077 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
8078 // selection, both tested here.
8079 let secp_ctx = Secp256k1::new();
8080 let logger = Arc::new(ln_test_utils::TestLogger::new());
8081 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8082 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8083 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8084 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8085 let config = UserConfig::default();
8087 // Values are taken from the fuzz input that uncovered this panic.
8088 let amt_msat = 562_0000;
8089 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8090 let first_hops = vec![
8091 get_channel_details(
8092 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
8096 let htlc_mins = [49_0000, 1125_0000];
8097 let payment_params = {
8098 let blinded_path = BlindedPath {
8099 introduction_node_id: nodes[0],
8100 blinding_point: ln_test_utils::pubkey(42),
8102 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8103 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8106 let mut blinded_hints = Vec::new();
8107 for htlc_min in htlc_mins.iter() {
8108 blinded_hints.push((BlindedPayInfo {
8110 fee_proportional_millionths: 0,
8111 htlc_minimum_msat: *htlc_min,
8112 htlc_maximum_msat: *htlc_min * 100,
8113 cltv_expiry_delta: 10,
8114 features: BlindedHopFeatures::empty(),
8115 }, blinded_path.clone()));
8117 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8118 PaymentParameters::blinded(blinded_hints.clone())
8119 .with_bolt12_features(bolt12_features.clone()).unwrap()
8122 let netgraph = network_graph.read_only();
8123 let route_params = RouteParameters::from_payment_params_and_value(
8124 payment_params, amt_msat);
8125 let route = get_route(
8126 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8127 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8130 assert_eq!(route.paths.len(), 1);
8131 assert_eq!(route.get_total_amount(), amt_msat);
8135 fn first_hop_preferred_over_hint() {
8136 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
8137 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
8138 let secp_ctx = Secp256k1::new();
8139 let logger = Arc::new(ln_test_utils::TestLogger::new());
8140 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8141 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
8142 let scorer = ln_test_utils::TestScorer::new();
8143 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8144 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8145 let config = UserConfig::default();
8147 let amt_msat = 1_000_000;
8148 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
8150 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
8151 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
8152 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8153 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8154 short_channel_id: 1,
8157 cltv_expiry_delta: 42,
8158 htlc_minimum_msat: 1_000,
8159 htlc_maximum_msat: 10_000_000,
8161 fee_proportional_millionths: 0,
8162 excess_data: Vec::new()
8164 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8165 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8166 short_channel_id: 1,
8169 cltv_expiry_delta: 42,
8170 htlc_minimum_msat: 1_000,
8171 htlc_maximum_msat: 10_000_000,
8173 fee_proportional_millionths: 0,
8174 excess_data: Vec::new()
8177 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
8178 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
8179 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8180 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8181 short_channel_id: 2,
8184 cltv_expiry_delta: 42,
8185 htlc_minimum_msat: 1_000,
8186 htlc_maximum_msat: 10_000_000,
8188 fee_proportional_millionths: 0,
8189 excess_data: Vec::new()
8191 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8192 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8193 short_channel_id: 2,
8196 cltv_expiry_delta: 42,
8197 htlc_minimum_msat: 1_000,
8198 htlc_maximum_msat: 10_000_000,
8200 fee_proportional_millionths: 0,
8201 excess_data: Vec::new()
8204 let dest_node_id = nodes[2];
8206 let route_hint = RouteHint(vec![RouteHintHop {
8207 src_node_id: our_node_id,
8208 short_channel_id: 44,
8211 proportional_millionths: 0,
8213 cltv_expiry_delta: 10,
8214 htlc_minimum_msat: None,
8215 htlc_maximum_msat: Some(5_000_000),
8218 src_node_id: nodes[0],
8219 short_channel_id: 45,
8222 proportional_millionths: 0,
8224 cltv_expiry_delta: 10,
8225 htlc_minimum_msat: None,
8226 htlc_maximum_msat: None,
8229 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8230 .with_route_hints(vec![route_hint]).unwrap()
8231 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8232 let route_params = RouteParameters::from_payment_params_and_value(
8233 payment_params, amt_msat);
8235 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8237 let first_hop = get_channel_details(Some(1), nodes[0],
8238 channelmanager::provided_init_features(&config), 999_999);
8239 let first_hops = vec![first_hop];
8241 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8242 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8243 &Default::default(), &random_seed_bytes).unwrap();
8244 assert_eq!(route.paths.len(), 1);
8245 assert_eq!(route.get_total_amount(), amt_msat);
8246 assert_eq!(route.paths[0].hops.len(), 2);
8247 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8248 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8249 assert_eq!(route.get_total_fees(), 123);
8251 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8252 // for a first hop channel.
8253 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8254 first_hop.outbound_scid_alias = Some(44);
8255 let first_hops = vec![first_hop];
8257 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8258 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8259 &Default::default(), &random_seed_bytes);
8260 assert!(route_res.is_err());
8262 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8263 // use the cheaper second hop of the route hint.
8264 let mut first_hop = get_channel_details(Some(1), nodes[0],
8265 channelmanager::provided_init_features(&config), 10_000_000);
8266 first_hop.outbound_scid_alias = Some(44);
8267 let first_hops = vec![first_hop];
8269 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8270 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8271 &Default::default(), &random_seed_bytes).unwrap();
8272 assert_eq!(route.paths.len(), 1);
8273 assert_eq!(route.get_total_amount(), amt_msat);
8274 assert_eq!(route.paths[0].hops.len(), 2);
8275 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8276 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8277 assert_eq!(route.get_total_fees(), 123);
8281 fn allow_us_being_first_hint() {
8282 // Check that we consider a route hint even if we are the src of the first hop.
8283 let secp_ctx = Secp256k1::new();
8284 let logger = Arc::new(ln_test_utils::TestLogger::new());
8285 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8286 let scorer = ln_test_utils::TestScorer::new();
8287 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8288 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8289 let config = UserConfig::default();
8291 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8293 let amt_msat = 1_000_000;
8294 let dest_node_id = nodes[1];
8296 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8297 let first_hops = vec![first_hop];
8299 let route_hint = RouteHint(vec![RouteHintHop {
8300 src_node_id: our_node_id,
8301 short_channel_id: 44,
8304 proportional_millionths: 0,
8306 cltv_expiry_delta: 10,
8307 htlc_minimum_msat: None,
8308 htlc_maximum_msat: None,
8311 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8312 .with_route_hints(vec![route_hint]).unwrap()
8313 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8315 let route_params = RouteParameters::from_payment_params_and_value(
8316 payment_params, amt_msat);
8319 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8320 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8321 &Default::default(), &random_seed_bytes).unwrap();
8323 assert_eq!(route.paths.len(), 1);
8324 assert_eq!(route.get_total_amount(), amt_msat);
8325 assert_eq!(route.get_total_fees(), 0);
8326 assert_eq!(route.paths[0].hops.len(), 1);
8328 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8332 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
8333 pub(crate) mod bench_utils {
8336 use std::time::Duration;
8338 use bitcoin::hashes::Hash;
8339 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
8341 use crate::chain::transaction::OutPoint;
8342 use crate::routing::scoring::ScoreUpdate;
8343 use crate::sign::{EntropySource, KeysManager};
8344 use crate::ln::ChannelId;
8345 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
8346 use crate::ln::features::Bolt11InvoiceFeatures;
8347 use crate::routing::gossip::NetworkGraph;
8348 use crate::util::config::UserConfig;
8349 use crate::util::ser::ReadableArgs;
8350 use crate::util::test_utils::TestLogger;
8352 /// Tries to open a network graph file, or panics with a URL to fetch it.
8353 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
8354 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
8355 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
8356 .or_else(|_| { // Fall back to guessing based on the binary location
8357 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8358 let mut path = std::env::current_exe().unwrap();
8359 path.pop(); // lightning-...
8361 path.pop(); // debug
8362 path.pop(); // target
8363 path.push("lightning");
8364 path.push("net_graph-2023-01-18.bin");
8367 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8368 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8369 let mut path = std::env::current_exe().unwrap();
8370 path.pop(); // bench...
8372 path.pop(); // debug
8373 path.pop(); // target
8374 path.pop(); // bench
8375 path.push("lightning");
8376 path.push("net_graph-2023-01-18.bin");
8379 .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");
8380 #[cfg(require_route_graph_test)]
8381 return Ok(res.unwrap());
8382 #[cfg(not(require_route_graph_test))]
8386 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
8387 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
8390 pub(crate) fn payer_pubkey() -> PublicKey {
8391 let secp_ctx = Secp256k1::new();
8392 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8396 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8398 channel_id: ChannelId::new_zero(),
8399 counterparty: ChannelCounterparty {
8400 features: channelmanager::provided_init_features(&UserConfig::default()),
8402 unspendable_punishment_reserve: 0,
8403 forwarding_info: None,
8404 outbound_htlc_minimum_msat: None,
8405 outbound_htlc_maximum_msat: None,
8407 funding_txo: Some(OutPoint {
8408 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8411 short_channel_id: Some(1),
8412 inbound_scid_alias: None,
8413 outbound_scid_alias: None,
8414 channel_value_satoshis: 10_000_000_000,
8416 balance_msat: 10_000_000_000,
8417 outbound_capacity_msat: 10_000_000_000,
8418 next_outbound_htlc_minimum_msat: 0,
8419 next_outbound_htlc_limit_msat: 10_000_000_000,
8420 inbound_capacity_msat: 0,
8421 unspendable_punishment_reserve: None,
8422 confirmations_required: None,
8423 confirmations: None,
8424 force_close_spend_delay: None,
8426 is_channel_ready: true,
8429 inbound_htlc_minimum_msat: None,
8430 inbound_htlc_maximum_msat: None,
8432 feerate_sat_per_1000_weight: None,
8433 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
8437 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8438 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8439 starting_amount: u64, route_count: usize,
8440 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8441 let payer = payer_pubkey();
8442 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8443 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8445 let nodes = graph.read_only().nodes().clone();
8446 let mut route_endpoints = Vec::new();
8447 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
8448 // with some routes we picked being un-routable.
8449 for _ in 0..route_count * 3 / 2 {
8451 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8452 let src = PublicKey::from_slice(nodes.unordered_keys()
8453 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8454 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8455 let dst = PublicKey::from_slice(nodes.unordered_keys()
8456 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8457 let params = PaymentParameters::from_node_id(dst, 42)
8458 .with_bolt11_features(features.clone()).unwrap();
8459 let first_hop = first_hop(src);
8460 let amt_msat = starting_amount + seed % 1_000_000;
8461 let route_params = RouteParameters::from_payment_params_and_value(
8462 params.clone(), amt_msat);
8464 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8465 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8467 // ...and seed the scorer with success and failure data...
8468 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8469 let mut score_amt = seed % 1_000_000_000;
8471 // Generate fail/success paths for a wider range of potential amounts with
8472 // MPP enabled to give us a chance to apply penalties for more potential
8474 let mpp_features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
8475 let params = PaymentParameters::from_node_id(dst, 42)
8476 .with_bolt11_features(mpp_features).unwrap();
8477 let route_params = RouteParameters::from_payment_params_and_value(
8478 params.clone(), score_amt);
8479 let route_res = get_route(&payer, &route_params, &graph.read_only(),
8480 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
8481 &random_seed_bytes);
8482 if let Ok(route) = route_res {
8483 for path in route.paths {
8484 if seed & 0x80 == 0 {
8485 scorer.payment_path_successful(&path, Duration::ZERO);
8487 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
8488 scorer.payment_path_failed(&path, short_channel_id, Duration::ZERO);
8490 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8494 // If we couldn't find a path with a higer amount, reduce and try again.
8498 route_endpoints.push((first_hop, params, amt_msat));
8504 // Because we've changed channel scores, it's possible we'll take different routes to the
8505 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
8506 // requires a too-high CLTV delta.
8507 route_endpoints.retain(|(first_hop, params, amt_msat)| {
8508 let route_params = RouteParameters::from_payment_params_and_value(
8509 params.clone(), *amt_msat);
8510 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8511 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
8513 route_endpoints.truncate(route_count);
8514 assert_eq!(route_endpoints.len(), route_count);
8522 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8523 use crate::sign::{EntropySource, KeysManager};
8524 use crate::ln::channelmanager;
8525 use crate::ln::features::Bolt11InvoiceFeatures;
8526 use crate::routing::gossip::NetworkGraph;
8527 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
8528 use crate::util::config::UserConfig;
8529 use crate::util::logger::{Logger, Record};
8530 use crate::util::test_utils::TestLogger;
8532 use criterion::Criterion;
8534 struct DummyLogger {}
8535 impl Logger for DummyLogger {
8536 fn log(&self, _record: Record) {}
8539 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8540 let logger = TestLogger::new();
8541 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8542 let scorer = FixedPenaltyScorer::with_penalty(0);
8543 generate_routes(bench, &network_graph, scorer, &Default::default(),
8544 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8547 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8548 let logger = TestLogger::new();
8549 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8550 let scorer = FixedPenaltyScorer::with_penalty(0);
8551 generate_routes(bench, &network_graph, scorer, &Default::default(),
8552 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8553 "generate_mpp_routes_with_zero_penalty_scorer");
8556 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8557 let logger = TestLogger::new();
8558 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8559 let params = ProbabilisticScoringFeeParameters::default();
8560 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8561 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8562 "generate_routes_with_probabilistic_scorer");
8565 pub fn generate_mpp_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,
8571 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8572 "generate_mpp_routes_with_probabilistic_scorer");
8575 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8576 let logger = TestLogger::new();
8577 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8578 let params = ProbabilisticScoringFeeParameters::default();
8579 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8580 generate_routes(bench, &network_graph, scorer, ¶ms,
8581 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8582 "generate_large_mpp_routes_with_probabilistic_scorer");
8585 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8586 let logger = TestLogger::new();
8587 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8588 let mut params = ProbabilisticScoringFeeParameters::default();
8589 params.linear_success_probability = false;
8590 let scorer = ProbabilisticScorer::new(
8591 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8592 generate_routes(bench, &network_graph, scorer, ¶ms,
8593 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8594 "generate_routes_with_nonlinear_probabilistic_scorer");
8597 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8598 let logger = TestLogger::new();
8599 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8600 let mut params = ProbabilisticScoringFeeParameters::default();
8601 params.linear_success_probability = false;
8602 let scorer = ProbabilisticScorer::new(
8603 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8604 generate_routes(bench, &network_graph, scorer, ¶ms,
8605 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8606 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8609 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8610 let logger = TestLogger::new();
8611 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8612 let mut params = ProbabilisticScoringFeeParameters::default();
8613 params.linear_success_probability = false;
8614 let scorer = ProbabilisticScorer::new(
8615 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8616 generate_routes(bench, &network_graph, scorer, ¶ms,
8617 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8618 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8621 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8622 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8623 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8624 bench_name: &'static str,
8626 let payer = bench_utils::payer_pubkey();
8627 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8628 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8630 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8631 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8633 // ...then benchmark finding paths between the nodes we learned.
8635 bench.bench_function(bench_name, |b| b.iter(|| {
8636 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8637 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8638 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8639 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());