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};
14 use crate::blinded_path::{BlindedHop, BlindedPath, Direction, IntroductionNode};
15 use crate::blinded_path::message;
16 use crate::blinded_path::payment::{ForwardTlvs, PaymentConstraints, PaymentRelay, ReceiveTlvs, self};
17 use crate::ln::{PaymentHash, PaymentPreimage};
18 use crate::ln::channel_state::ChannelDetails;
19 use crate::ln::channelmanager::{PaymentId, MIN_FINAL_CLTV_EXPIRY_DELTA, RecipientOnionFields};
20 use crate::ln::features::{BlindedHopFeatures, Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
21 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
22 use crate::ln::onion_utils;
23 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice};
24 use crate::onion_message::messenger::{DefaultMessageRouter, Destination, MessageRouter, OnionMessagePath};
25 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
26 use crate::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp};
27 use crate::sign::EntropySource;
28 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
29 use crate::util::logger::{Level, Logger};
30 use crate::crypto::chacha20::ChaCha20;
33 use crate::prelude::*;
34 use alloc::collections::BinaryHeap;
38 /// A [`Router`] implemented using [`find_route`].
42 /// Implements [`MessageRouter`] by delegating to [`DefaultMessageRouter`]. See those docs for
43 /// privacy implications.
44 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> where
46 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
47 ES::Target: EntropySource,
54 message_router: DefaultMessageRouter<G, L, ES>,
57 impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref + Clone, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> DefaultRouter<G, L, ES, S, SP, Sc> where
59 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
60 ES::Target: EntropySource,
62 /// Creates a new router.
63 pub fn new(network_graph: G, logger: L, entropy_source: ES, scorer: S, score_params: SP) -> Self {
64 let message_router = DefaultMessageRouter::new(network_graph.clone(), entropy_source.clone());
65 Self { network_graph, logger, entropy_source, scorer, score_params, message_router }
69 impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> Router for DefaultRouter<G, L, ES, S, SP, Sc> where
71 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
72 ES::Target: EntropySource,
77 params: &RouteParameters,
78 first_hops: Option<&[&ChannelDetails]>,
79 inflight_htlcs: InFlightHtlcs
80 ) -> Result<Route, LightningError> {
81 let random_seed_bytes = self.entropy_source.get_secure_random_bytes();
83 payer, params, &self.network_graph, first_hops, &*self.logger,
84 &ScorerAccountingForInFlightHtlcs::new(self.scorer.read_lock(), &inflight_htlcs),
90 fn create_blinded_payment_paths<
91 T: secp256k1::Signing + secp256k1::Verification
93 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
94 amount_msats: u64, secp_ctx: &Secp256k1<T>
95 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
96 // Limit the number of blinded paths that are computed.
97 const MAX_PAYMENT_PATHS: usize = 3;
99 // Ensure peers have at least three channels so that it is more difficult to infer the
100 // recipient's node_id.
101 const MIN_PEER_CHANNELS: usize = 3;
103 let has_one_peer = first_hops
105 .map(|details| details.counterparty.node_id)
106 .map(|node_id| first_hops
109 .all(|details| details.counterparty.node_id == node_id)
113 let network_graph = self.network_graph.deref().read_only();
114 let is_recipient_announced =
115 network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient));
117 let paths = first_hops.into_iter()
118 .filter(|details| details.counterparty.features.supports_route_blinding())
119 .filter(|details| amount_msats <= details.inbound_capacity_msat)
120 .filter(|details| amount_msats >= details.inbound_htlc_minimum_msat.unwrap_or(0))
121 .filter(|details| amount_msats <= details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX))
122 .filter(|details| network_graph
123 .node(&NodeId::from_pubkey(&details.counterparty.node_id))
124 .map(|node_info| node_info.channels.len() >= MIN_PEER_CHANNELS)
125 // Allow payments directly with the only peer when unannounced.
126 .unwrap_or(!is_recipient_announced && has_one_peer)
128 .filter_map(|details| {
129 let short_channel_id = match details.get_inbound_payment_scid() {
130 Some(short_channel_id) => short_channel_id,
133 let payment_relay: PaymentRelay = match details.counterparty.forwarding_info {
134 Some(forwarding_info) => match forwarding_info.try_into() {
135 Ok(payment_relay) => payment_relay,
136 Err(()) => return None,
141 let cltv_expiry_delta = payment_relay.cltv_expiry_delta as u32;
142 let payment_constraints = PaymentConstraints {
143 max_cltv_expiry: tlvs.payment_constraints.max_cltv_expiry + cltv_expiry_delta,
144 htlc_minimum_msat: details.inbound_htlc_minimum_msat.unwrap_or(0),
146 Some(payment::ForwardNode {
151 features: BlindedHopFeatures::empty(),
153 node_id: details.counterparty.node_id,
154 htlc_maximum_msat: details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX),
157 .map(|forward_node| {
158 BlindedPath::new_for_payment(
159 &[forward_node], recipient, tlvs.clone(), u64::MAX, MIN_FINAL_CLTV_EXPIRY_DELTA,
160 &*self.entropy_source, secp_ctx
163 .take(MAX_PAYMENT_PATHS)
164 .collect::<Result<Vec<_>, _>>();
167 Ok(paths) if !paths.is_empty() => Ok(paths),
169 if network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient)) {
170 BlindedPath::one_hop_for_payment(
171 recipient, tlvs, MIN_FINAL_CLTV_EXPIRY_DELTA, &*self.entropy_source, secp_ctx
172 ).map(|path| vec![path])
181 impl< G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> MessageRouter for DefaultRouter<G, L, ES, S, SP, Sc> where
183 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
184 ES::Target: EntropySource,
187 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
188 ) -> Result<OnionMessagePath, ()> {
189 self.message_router.find_path(sender, peers, destination)
192 fn create_blinded_paths<
193 T: secp256k1::Signing + secp256k1::Verification
195 &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
196 ) -> Result<Vec<BlindedPath>, ()> {
197 self.message_router.create_blinded_paths(recipient, peers, secp_ctx)
200 fn create_compact_blinded_paths<
201 T: secp256k1::Signing + secp256k1::Verification
203 &self, recipient: PublicKey, peers: Vec<message::ForwardNode>, secp_ctx: &Secp256k1<T>,
204 ) -> Result<Vec<BlindedPath>, ()> {
205 self.message_router.create_compact_blinded_paths(recipient, peers, secp_ctx)
209 /// A trait defining behavior for routing a payment.
210 pub trait Router: MessageRouter {
211 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
213 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
214 /// and [`RouteParameters::final_value_msat`], respectively.
216 &self, payer: &PublicKey, route_params: &RouteParameters,
217 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
218 ) -> Result<Route, LightningError>;
220 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
222 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
223 /// and [`RouteParameters::final_value_msat`], respectively.
225 /// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
227 fn find_route_with_id(
228 &self, payer: &PublicKey, route_params: &RouteParameters,
229 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
230 _payment_hash: PaymentHash, _payment_id: PaymentId
231 ) -> Result<Route, LightningError> {
232 self.find_route(payer, route_params, first_hops, inflight_htlcs)
235 /// Creates [`BlindedPath`]s for payment to the `recipient` node. The channels in `first_hops`
236 /// are assumed to be with the `recipient`'s peers. The payment secret and any constraints are
238 fn create_blinded_payment_paths<
239 T: secp256k1::Signing + secp256k1::Verification
241 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
242 amount_msats: u64, secp_ctx: &Secp256k1<T>
243 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()>;
246 /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
248 /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
251 /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
252 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> where S::Target: ScoreLookUp {
254 // Maps a channel's short channel id and its direction to the liquidity used up.
255 inflight_htlcs: &'a InFlightHtlcs,
257 impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
258 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
259 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
260 ScorerAccountingForInFlightHtlcs {
267 impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
268 type ScoreParams = <S::Target as ScoreLookUp>::ScoreParams;
269 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
270 let target = match candidate.target() {
271 Some(target) => target,
272 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
274 let short_channel_id = match candidate.short_channel_id() {
275 Some(short_channel_id) => short_channel_id,
276 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
278 let source = candidate.source();
279 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
280 &source, &target, short_channel_id
282 let usage = ChannelUsage {
283 inflight_htlc_msat: usage.inflight_htlc_msat.saturating_add(used_liquidity),
287 self.scorer.channel_penalty_msat(candidate, usage, score_params)
289 self.scorer.channel_penalty_msat(candidate, usage, score_params)
294 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
295 /// in-use channel liquidity.
297 pub struct InFlightHtlcs(
298 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
299 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
300 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
302 HashMap<(u64, bool), u64>
306 /// Constructs an empty `InFlightHtlcs`.
307 pub fn new() -> Self { InFlightHtlcs(new_hash_map()) }
309 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
310 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
311 if path.hops.is_empty() { return };
313 let mut cumulative_msat = 0;
314 if let Some(tail) = &path.blinded_tail {
315 cumulative_msat += tail.final_value_msat;
318 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
319 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
320 // the router excludes the payer node. In the following lines, the payer's information is
321 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
322 // in our sliding window of two.
323 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
324 .map(|hop| hop.pubkey)
325 .chain(core::iter::once(payer_node_id));
327 // Taking the reversed vector from above, we zip it with just the reversed hops list to
328 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
329 // the total amount sent.
330 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
331 cumulative_msat += next_hop.fee_msat;
333 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
334 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
335 .or_insert(cumulative_msat);
339 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
341 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
343 .entry((channel_scid, source < target))
344 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
345 .or_insert(used_msat);
348 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
350 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
351 self.0.get(&(channel_scid, source < target)).map(|v| *v)
355 impl Writeable for InFlightHtlcs {
356 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
359 impl Readable for InFlightHtlcs {
360 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
361 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
362 Ok(Self(infight_map))
366 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
367 /// that leads to it.
368 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
369 pub struct RouteHop {
370 /// The node_id of the node at this hop.
371 pub pubkey: PublicKey,
372 /// The node_announcement features of the node at this hop. For the last hop, these may be
373 /// amended to match the features present in the invoice this node generated.
374 pub node_features: NodeFeatures,
375 /// The channel that should be used from the previous hop to reach this node.
376 pub short_channel_id: u64,
377 /// The channel_announcement features of the channel that should be used from the previous hop
378 /// to reach this node.
379 pub channel_features: ChannelFeatures,
380 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
381 /// If this is the last hop in [`Path::hops`]:
382 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
383 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
385 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
387 /// The CLTV delta added for this hop.
388 /// If this is the last hop in [`Path::hops`]:
389 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
390 /// * otherwise, this is the CLTV delta expected at the destination
392 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
393 pub cltv_expiry_delta: u32,
394 /// Indicates whether this hop is possibly announced in the public network graph.
396 /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
397 /// either know for sure it's announced in the public graph, or if any public channels exist
398 /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
399 /// the channel to be unannounced.
401 /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
402 pub maybe_announced_channel: bool,
405 impl_writeable_tlv_based!(RouteHop, {
406 (0, pubkey, required),
407 (1, maybe_announced_channel, (default_value, true)),
408 (2, node_features, required),
409 (4, short_channel_id, required),
410 (6, channel_features, required),
411 (8, fee_msat, required),
412 (10, cltv_expiry_delta, required),
415 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
416 /// their [`Bolt12Invoice`].
418 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
419 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
420 pub struct BlindedTail {
421 /// The hops of the [`BlindedPath`] provided by the recipient.
423 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
424 pub hops: Vec<BlindedHop>,
425 /// The blinding point of the [`BlindedPath`] provided by the recipient.
427 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
428 pub blinding_point: PublicKey,
429 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
430 /// inferring the destination. May be 0.
431 pub excess_final_cltv_expiry_delta: u32,
432 /// The total amount paid on this [`Path`], excluding the fees.
433 pub final_value_msat: u64,
436 impl_writeable_tlv_based!(BlindedTail, {
437 (0, hops, required_vec),
438 (2, blinding_point, required),
439 (4, excess_final_cltv_expiry_delta, required),
440 (6, final_value_msat, required),
443 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
444 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
445 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
447 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
448 pub hops: Vec<RouteHop>,
449 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
450 pub blinded_tail: Option<BlindedTail>,
454 /// Gets the fees for a given path, excluding any excess paid to the recipient.
455 pub fn fee_msat(&self) -> u64 {
456 match &self.blinded_tail {
457 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
459 // Do not count last hop of each path since that's the full value of the payment
460 self.hops.split_last().map_or(0,
461 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
466 /// Gets the total amount paid on this [`Path`], excluding the fees.
467 pub fn final_value_msat(&self) -> u64 {
468 match &self.blinded_tail {
469 Some(blinded_tail) => blinded_tail.final_value_msat,
470 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
474 /// Gets the final hop's CLTV expiry delta.
475 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
476 match &self.blinded_tail {
478 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
483 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
484 /// it can take multiple paths. Each path is composed of one or more hops through the network.
485 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
487 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
488 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
490 pub paths: Vec<Path>,
491 /// The `route_params` parameter passed to [`find_route`].
493 /// This is used by `ChannelManager` to track information which may be required for retries.
495 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
496 pub route_params: Option<RouteParameters>,
500 /// Returns the total amount of fees paid on this [`Route`].
502 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
503 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
504 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
506 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
507 pub fn get_total_fees(&self) -> u64 {
508 let overpaid_value_msat = self.route_params.as_ref()
509 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
510 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
513 /// Returns the total amount paid on this [`Route`], excluding the fees.
515 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
516 /// we had to reach the [`htlc_minimum_msat`] limits.
518 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
519 pub fn get_total_amount(&self) -> u64 {
520 self.paths.iter().map(|path| path.final_value_msat()).sum()
524 impl fmt::Display for Route {
525 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
526 log_route!(self).fmt(f)
530 const SERIALIZATION_VERSION: u8 = 1;
531 const MIN_SERIALIZATION_VERSION: u8 = 1;
533 impl Writeable for Route {
534 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
535 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
536 (self.paths.len() as u64).write(writer)?;
537 let mut blinded_tails = Vec::new();
538 for (idx, path) in self.paths.iter().enumerate() {
539 (path.hops.len() as u8).write(writer)?;
540 for hop in path.hops.iter() {
543 if let Some(blinded_tail) = &path.blinded_tail {
544 if blinded_tails.is_empty() {
545 blinded_tails = Vec::with_capacity(path.hops.len());
547 blinded_tails.push(None);
550 blinded_tails.push(Some(blinded_tail));
551 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
553 write_tlv_fields!(writer, {
554 // For compatibility with LDK versions prior to 0.0.117, we take the individual
555 // RouteParameters' fields and reconstruct them on read.
556 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
557 (2, blinded_tails, optional_vec),
558 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
559 (5, self.route_params.as_ref().and_then(|p| p.max_total_routing_fee_msat), option),
565 impl Readable for Route {
566 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
567 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
568 let path_count: u64 = Readable::read(reader)?;
569 if path_count == 0 { return Err(DecodeError::InvalidValue); }
570 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
571 let mut min_final_cltv_expiry_delta = u32::max_value();
572 for _ in 0..path_count {
573 let hop_count: u8 = Readable::read(reader)?;
574 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
575 for _ in 0..hop_count {
576 hops.push(Readable::read(reader)?);
578 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
579 min_final_cltv_expiry_delta =
580 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
581 paths.push(Path { hops, blinded_tail: None });
583 _init_and_read_len_prefixed_tlv_fields!(reader, {
584 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
585 (2, blinded_tails, optional_vec),
586 (3, final_value_msat, option),
587 (5, max_total_routing_fee_msat, option)
589 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
590 if blinded_tails.len() != 0 {
591 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
592 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
593 path.blinded_tail = blinded_tail_opt;
597 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
598 let route_params = match (payment_params, final_value_msat) {
599 (Some(payment_params), Some(final_value_msat)) => {
600 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
605 Ok(Route { paths, route_params })
609 /// Parameters needed to find a [`Route`].
611 /// Passed to [`find_route`] and [`build_route_from_hops`].
612 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
613 pub struct RouteParameters {
614 /// The parameters of the failed payment path.
615 pub payment_params: PaymentParameters,
617 /// The amount in msats sent on the failed payment path.
618 pub final_value_msat: u64,
620 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
622 /// This limit also applies to the total fees that may arise while retrying failed payment
625 /// Note that values below a few sats may result in some paths being spuriously ignored.
626 pub max_total_routing_fee_msat: Option<u64>,
629 impl RouteParameters {
630 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
632 /// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
633 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
634 Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
637 /// Sets the maximum number of hops that can be included in a payment path, based on the provided
638 /// [`RecipientOnionFields`] and blinded paths.
639 pub fn set_max_path_length(
640 &mut self, recipient_onion: &RecipientOnionFields, is_keysend: bool, best_block_height: u32
641 ) -> Result<(), ()> {
642 let keysend_preimage_opt = is_keysend.then(|| PaymentPreimage([42; 32]));
643 onion_utils::set_max_path_length(
644 self, recipient_onion, keysend_preimage_opt, best_block_height
649 impl Writeable for RouteParameters {
650 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
651 write_tlv_fields!(writer, {
652 (0, self.payment_params, required),
653 (1, self.max_total_routing_fee_msat, option),
654 (2, self.final_value_msat, required),
655 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
656 // `RouteParameters` directly. For compatibility, we write it here.
657 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
663 impl Readable for RouteParameters {
664 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
665 _init_and_read_len_prefixed_tlv_fields!(reader, {
666 (0, payment_params, (required: ReadableArgs, 0)),
667 (1, max_total_routing_fee_msat, option),
668 (2, final_value_msat, required),
669 (4, final_cltv_delta, option),
671 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
672 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
673 if final_cltv_expiry_delta == &0 {
674 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
679 final_value_msat: final_value_msat.0.unwrap(),
680 max_total_routing_fee_msat,
685 /// Maximum total CTLV difference we allow for a full payment path.
686 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
688 /// Maximum number of paths we allow an (MPP) payment to have.
689 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
690 // limits, but for now more than 10 paths likely carries too much one-path failure.
691 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
693 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
695 // The median hop CLTV expiry delta currently seen in the network.
696 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
698 /// Estimated maximum number of hops that can be included in a payment path. May be inaccurate if
699 /// payment metadata, custom TLVs, or blinded paths are included in the payment.
700 // During routing, we only consider paths shorter than our maximum length estimate.
701 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
702 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
703 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
705 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
706 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
707 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
708 // (payment_secret and total_msat) = 93 bytes for the final hop.
709 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
710 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
711 pub const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
713 /// Information used to route a payment.
714 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
715 pub struct PaymentParameters {
716 /// Information about the payee, such as their features and route hints for their channels.
719 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
720 pub expiry_time: Option<u64>,
722 /// The maximum total CLTV delta we accept for the route.
723 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
724 pub max_total_cltv_expiry_delta: u32,
726 /// The maximum number of paths that may be used by (MPP) payments.
727 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
728 pub max_path_count: u8,
730 /// The maximum number of [`Path::hops`] in any returned path.
731 /// Defaults to [`MAX_PATH_LENGTH_ESTIMATE`].
732 pub max_path_length: u8,
734 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
735 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
736 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
737 /// increasing failure probability for those paths.
739 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
740 /// restriction have been found. While paths which meet this criteria will be searched for, it
741 /// is ultimately up to the scorer to select them over other paths.
743 /// A value of 0 will allow payments up to and including a channel's total announced usable
744 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
747 pub max_channel_saturation_power_of_half: u8,
749 /// A list of SCIDs which this payment was previously attempted over and which caused the
750 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
752 pub previously_failed_channels: Vec<u64>,
754 /// A list of indices corresponding to blinded paths in [`Payee::Blinded::route_hints`] which this
755 /// payment was previously attempted over and which caused the payment to fail. Future attempts
756 /// for the same payment shouldn't be relayed through any of these blinded paths.
757 pub previously_failed_blinded_path_idxs: Vec<u64>,
760 impl Writeable for PaymentParameters {
761 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
762 let mut clear_hints = &vec![];
763 let mut blinded_hints = &vec![];
765 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
766 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
768 write_tlv_fields!(writer, {
769 (0, self.payee.node_id(), option),
770 (1, self.max_total_cltv_expiry_delta, required),
771 (2, self.payee.features(), option),
772 (3, self.max_path_count, required),
773 (4, *clear_hints, required_vec),
774 (5, self.max_channel_saturation_power_of_half, required),
775 (6, self.expiry_time, option),
776 (7, self.previously_failed_channels, required_vec),
777 (8, *blinded_hints, optional_vec),
778 (9, self.payee.final_cltv_expiry_delta(), option),
779 (11, self.previously_failed_blinded_path_idxs, required_vec),
780 (13, self.max_path_length, required),
786 impl ReadableArgs<u32> for PaymentParameters {
787 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
788 _init_and_read_len_prefixed_tlv_fields!(reader, {
789 (0, payee_pubkey, option),
790 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
791 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
792 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
793 (4, clear_route_hints, required_vec),
794 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
795 (6, expiry_time, option),
796 (7, previously_failed_channels, optional_vec),
797 (8, blinded_route_hints, optional_vec),
798 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
799 (11, previously_failed_blinded_path_idxs, optional_vec),
800 (13, max_path_length, (default_value, MAX_PATH_LENGTH_ESTIMATE)),
802 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
803 let payee = if blinded_route_hints.len() != 0 {
804 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
806 route_hints: blinded_route_hints,
807 features: features.and_then(|f: Features| f.bolt12()),
811 route_hints: clear_route_hints,
812 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
813 features: features.and_then(|f| f.bolt11()),
814 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
818 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
819 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
821 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
823 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
824 previously_failed_blinded_path_idxs: previously_failed_blinded_path_idxs.unwrap_or(Vec::new()),
825 max_path_length: _init_tlv_based_struct_field!(max_path_length, (default_value, unused)),
831 impl PaymentParameters {
832 /// Creates a payee with the node id of the given `pubkey`.
834 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
836 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
838 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
840 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
841 max_path_count: DEFAULT_MAX_PATH_COUNT,
842 max_path_length: MAX_PATH_LENGTH_ESTIMATE,
843 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
844 previously_failed_channels: Vec::new(),
845 previously_failed_blinded_path_idxs: Vec::new(),
849 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
851 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
854 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
855 /// whether your router will be allowed to find a multi-part route for this payment. If you
856 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
857 /// [`RecipientOnionFields::secret_only`].
859 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
860 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
861 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
862 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
863 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
866 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
867 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
868 /// [`PaymentParameters::expiry_time`].
869 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
870 Self::blinded(invoice.payment_paths().to_vec())
871 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
872 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
875 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
876 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
878 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
880 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
881 max_path_count: DEFAULT_MAX_PATH_COUNT,
882 max_path_length: MAX_PATH_LENGTH_ESTIMATE,
883 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
884 previously_failed_channels: Vec::new(),
885 previously_failed_blinded_path_idxs: Vec::new(),
889 /// Includes the payee's features. Errors if the parameters were not initialized with
890 /// [`PaymentParameters::from_bolt12_invoice`].
892 /// This is not exported to bindings users since bindings don't support move semantics
893 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
895 Payee::Clear { .. } => Err(()),
896 Payee::Blinded { route_hints, .. } =>
897 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
901 /// Includes the payee's features. Errors if the parameters were initialized with
902 /// [`PaymentParameters::from_bolt12_invoice`].
904 /// This is not exported to bindings users since bindings don't support move semantics
905 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
907 Payee::Blinded { .. } => Err(()),
908 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
910 payee: Payee::Clear {
911 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
917 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
918 /// [`PaymentParameters::from_bolt12_invoice`].
920 /// This is not exported to bindings users since bindings don't support move semantics
921 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
923 Payee::Blinded { .. } => Err(()),
924 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
926 payee: Payee::Clear {
927 route_hints, node_id, features, final_cltv_expiry_delta,
933 /// Includes a payment expiration in seconds relative to the UNIX epoch.
935 /// This is not exported to bindings users since bindings don't support move semantics
936 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
937 Self { expiry_time: Some(expiry_time), ..self }
940 /// Includes a limit for the total CLTV expiry delta which is considered during routing
942 /// This is not exported to bindings users since bindings don't support move semantics
943 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
944 Self { max_total_cltv_expiry_delta, ..self }
947 /// Includes a limit for the maximum number of payment paths that may be used.
949 /// This is not exported to bindings users since bindings don't support move semantics
950 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
951 Self { max_path_count, ..self }
954 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
955 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
957 /// This is not exported to bindings users since bindings don't support move semantics
958 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
959 Self { max_channel_saturation_power_of_half, ..self }
962 pub(crate) fn insert_previously_failed_blinded_path(&mut self, failed_blinded_tail: &BlindedTail) {
963 let mut found_blinded_tail = false;
964 for (idx, (_, path)) in self.payee.blinded_route_hints().iter().enumerate() {
965 if failed_blinded_tail.hops == path.blinded_hops &&
966 failed_blinded_tail.blinding_point == path.blinding_point
968 self.previously_failed_blinded_path_idxs.push(idx as u64);
969 found_blinded_tail = true;
972 debug_assert!(found_blinded_tail);
976 /// The recipient of a payment, differing based on whether they've hidden their identity with route
978 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
980 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
981 /// will be included in the final [`Route`].
983 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
985 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
986 /// Features supported by the payee.
988 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
990 features: Option<Bolt12InvoiceFeatures>,
992 /// The recipient included these route hints in their BOLT11 invoice.
994 /// The node id of the payee.
996 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
997 route_hints: Vec<RouteHint>,
998 /// Features supported by the payee.
1000 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
1001 /// does not contain any features.
1003 /// [`for_keysend`]: PaymentParameters::for_keysend
1004 features: Option<Bolt11InvoiceFeatures>,
1005 /// The minimum CLTV delta at the end of the route. This value must not be zero.
1006 final_cltv_expiry_delta: u32,
1011 fn node_id(&self) -> Option<PublicKey> {
1013 Self::Clear { node_id, .. } => Some(*node_id),
1017 fn node_features(&self) -> Option<NodeFeatures> {
1019 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
1020 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
1023 fn supports_basic_mpp(&self) -> bool {
1025 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
1026 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
1029 fn features(&self) -> Option<FeaturesRef> {
1031 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
1032 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
1035 fn final_cltv_expiry_delta(&self) -> Option<u32> {
1037 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
1041 pub(crate) fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
1043 Self::Blinded { route_hints, .. } => &route_hints[..],
1044 Self::Clear { .. } => &[]
1048 pub(crate) fn blinded_route_hints_mut(&mut self) -> &mut [(BlindedPayInfo, BlindedPath)] {
1050 Self::Blinded { route_hints, .. } => &mut route_hints[..],
1051 Self::Clear { .. } => &mut []
1055 fn unblinded_route_hints(&self) -> &[RouteHint] {
1057 Self::Blinded { .. } => &[],
1058 Self::Clear { route_hints, .. } => &route_hints[..]
1063 enum FeaturesRef<'a> {
1064 Bolt11(&'a Bolt11InvoiceFeatures),
1065 Bolt12(&'a Bolt12InvoiceFeatures),
1068 Bolt11(Bolt11InvoiceFeatures),
1069 Bolt12(Bolt12InvoiceFeatures),
1073 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
1075 Self::Bolt12(f) => Some(f),
1079 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
1081 Self::Bolt11(f) => Some(f),
1087 impl<'a> Writeable for FeaturesRef<'a> {
1088 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1090 Self::Bolt11(f) => Ok(f.write(w)?),
1091 Self::Bolt12(f) => Ok(f.write(w)?),
1096 impl ReadableArgs<bool> for Features {
1097 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
1098 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
1099 Ok(Self::Bolt12(Readable::read(reader)?))
1103 /// A list of hops along a payment path terminating with a channel to the recipient.
1104 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1105 pub struct RouteHint(pub Vec<RouteHintHop>);
1107 impl Writeable for RouteHint {
1108 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1109 (self.0.len() as u64).write(writer)?;
1110 for hop in self.0.iter() {
1117 impl Readable for RouteHint {
1118 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1119 let hop_count: u64 = Readable::read(reader)?;
1120 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
1121 for _ in 0..hop_count {
1122 hops.push(Readable::read(reader)?);
1128 /// A channel descriptor for a hop along a payment path.
1130 /// While this generally comes from BOLT 11's `r` field, this struct includes more fields than are
1131 /// available in BOLT 11. Thus, encoding and decoding this via `lightning-invoice` is lossy, as
1132 /// fields not supported in BOLT 11 will be stripped.
1133 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1134 pub struct RouteHintHop {
1135 /// The node_id of the non-target end of the route
1136 pub src_node_id: PublicKey,
1137 /// The short_channel_id of this channel
1138 pub short_channel_id: u64,
1139 /// The fees which must be paid to use this channel
1140 pub fees: RoutingFees,
1141 /// The difference in CLTV values between this node and the next node.
1142 pub cltv_expiry_delta: u16,
1143 /// The minimum value, in msat, which must be relayed to the next hop.
1144 pub htlc_minimum_msat: Option<u64>,
1145 /// The maximum value in msat available for routing with a single HTLC.
1146 pub htlc_maximum_msat: Option<u64>,
1149 impl_writeable_tlv_based!(RouteHintHop, {
1150 (0, src_node_id, required),
1151 (1, htlc_minimum_msat, option),
1152 (2, short_channel_id, required),
1153 (3, htlc_maximum_msat, option),
1154 (4, fees, required),
1155 (6, cltv_expiry_delta, required),
1158 #[derive(Eq, PartialEq)]
1159 #[repr(align(64))] // Force the size to 64 bytes
1160 struct RouteGraphNode {
1163 // The maximum value a yet-to-be-constructed payment path might flow through this node.
1164 // This value is upper-bounded by us by:
1165 // - how much is needed for a path being constructed
1166 // - how much value can channels following this node (up to the destination) can contribute,
1167 // considering their capacity and fees
1168 value_contribution_msat: u64,
1169 total_cltv_delta: u32,
1170 /// The number of hops walked up to this node.
1171 path_length_to_node: u8,
1174 impl cmp::Ord for RouteGraphNode {
1175 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
1176 other.score.cmp(&self.score).then_with(|| other.node_id.cmp(&self.node_id))
1180 impl cmp::PartialOrd for RouteGraphNode {
1181 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
1182 Some(self.cmp(other))
1186 // While RouteGraphNode can be laid out with fewer bytes, performance appears to be improved
1187 // substantially when it is laid out at exactly 64 bytes.
1189 // Thus, we use `#[repr(C)]` on the struct to force a suboptimal layout and check that it stays 64
1191 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1192 const _GRAPH_NODE_SMALL: usize = 64 - core::mem::size_of::<RouteGraphNode>();
1193 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1194 const _GRAPH_NODE_FIXED_SIZE: usize = core::mem::size_of::<RouteGraphNode>() - 64;
1196 /// A [`CandidateRouteHop::FirstHop`] entry.
1197 #[derive(Clone, Debug)]
1198 pub struct FirstHopCandidate<'a> {
1199 /// Channel details of the first hop
1201 /// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1202 /// has been funded and is able to pay), and accessor methods may panic otherwise.
1204 /// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1206 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1207 pub details: &'a ChannelDetails,
1208 /// The node id of the payer, which is also the source side of this candidate route hop.
1210 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1211 pub payer_node_id: &'a NodeId,
1214 /// A [`CandidateRouteHop::PublicHop`] entry.
1215 #[derive(Clone, Debug)]
1216 pub struct PublicHopCandidate<'a> {
1217 /// Information about the channel, including potentially its capacity and
1218 /// direction-specific information.
1220 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1221 pub info: DirectedChannelInfo<'a>,
1222 /// The short channel ID of the channel, i.e. the identifier by which we refer to this
1224 pub short_channel_id: u64,
1227 /// A [`CandidateRouteHop::PrivateHop`] entry.
1228 #[derive(Clone, Debug)]
1229 pub struct PrivateHopCandidate<'a> {
1230 /// Information about the private hop communicated via BOLT 11.
1232 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1233 pub hint: &'a RouteHintHop,
1234 /// Node id of the next hop in BOLT 11 route hint.
1236 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1237 pub target_node_id: &'a NodeId
1240 /// A [`CandidateRouteHop::Blinded`] entry.
1241 #[derive(Clone, Debug)]
1242 pub struct BlindedPathCandidate<'a> {
1243 /// The node id of the introduction node, resolved from either the [`NetworkGraph`] or first
1246 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1247 pub source_node_id: &'a NodeId,
1248 /// Information about the blinded path including the fee, HTLC amount limits, and
1249 /// cryptographic material required to build an HTLC through the given path.
1251 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1252 pub hint: &'a (BlindedPayInfo, BlindedPath),
1253 /// Index of the hint in the original list of blinded hints.
1255 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1256 /// a short channel ID for this hop.
1260 /// A [`CandidateRouteHop::OneHopBlinded`] entry.
1261 #[derive(Clone, Debug)]
1262 pub struct OneHopBlindedPathCandidate<'a> {
1263 /// The node id of the introduction node, resolved from either the [`NetworkGraph`] or first
1266 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1267 pub source_node_id: &'a NodeId,
1268 /// Information about the blinded path including the fee, HTLC amount limits, and
1269 /// cryptographic material required to build an HTLC terminating with the given path.
1271 /// Note that the [`BlindedPayInfo`] is ignored here.
1273 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1274 pub hint: &'a (BlindedPayInfo, BlindedPath),
1275 /// Index of the hint in the original list of blinded hints.
1277 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1278 /// a short channel ID for this hop.
1282 /// A wrapper around the various hop representations.
1284 /// Can be used to examine the properties of a hop,
1285 /// potentially to decide whether to include it in a route.
1286 #[derive(Clone, Debug)]
1287 pub enum CandidateRouteHop<'a> {
1288 /// A hop from the payer, where the outbound liquidity is known.
1289 FirstHop(FirstHopCandidate<'a>),
1290 /// A hop found in the [`ReadOnlyNetworkGraph`].
1291 PublicHop(PublicHopCandidate<'a>),
1292 /// A private hop communicated by the payee, generally via a BOLT 11 invoice.
1294 /// Because BOLT 11 route hints can take multiple hops to get to the destination, this may not
1295 /// terminate at the payee.
1296 PrivateHop(PrivateHopCandidate<'a>),
1297 /// A blinded path which starts with an introduction point and ultimately terminates with the
1300 /// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1301 /// `None` in this state.
1303 /// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1304 /// path, the full path is treated as a single [`CandidateRouteHop`].
1305 Blinded(BlindedPathCandidate<'a>),
1306 /// Similar to [`Self::Blinded`], but the path here only has one hop.
1308 /// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1309 /// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1310 /// payee's identity - it's the introduction point!
1312 /// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1313 /// to the hops *between* the introduction node and the destination.
1315 /// This primarily exists to track that we need to included a blinded path at the end of our
1316 /// [`Route`], even though it doesn't actually add an additional hop in the payment.
1317 OneHopBlinded(OneHopBlindedPathCandidate<'a>),
1320 impl<'a> CandidateRouteHop<'a> {
1321 /// Returns the short channel ID for this hop, if one is known.
1323 /// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1324 /// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1326 /// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1327 /// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1328 /// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1329 /// (which is always true for channels which are funded and ready for use).
1331 /// In other words, this should always return `Some` as long as the candidate hop is not a
1332 /// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1334 /// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1335 /// define a global namespace.
1337 fn short_channel_id(&self) -> Option<u64> {
1339 CandidateRouteHop::FirstHop(hop) => hop.details.get_outbound_payment_scid(),
1340 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1341 CandidateRouteHop::PrivateHop(hop) => Some(hop.hint.short_channel_id),
1342 CandidateRouteHop::Blinded(_) => None,
1343 CandidateRouteHop::OneHopBlinded(_) => None,
1347 /// Returns the globally unique short channel ID for this hop, if one is known.
1349 /// This only returns `Some` if the channel is public (either our own, or one we've learned
1350 /// from the public network graph), and thus the short channel ID we have for this channel is
1351 /// globally unique and identifies this channel in a global namespace.
1353 pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1355 CandidateRouteHop::FirstHop(hop) => if hop.details.is_public { hop.details.short_channel_id } else { None },
1356 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1357 CandidateRouteHop::PrivateHop(_) => None,
1358 CandidateRouteHop::Blinded(_) => None,
1359 CandidateRouteHop::OneHopBlinded(_) => None,
1363 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1364 fn features(&self) -> ChannelFeatures {
1366 CandidateRouteHop::FirstHop(hop) => hop.details.counterparty.features.to_context(),
1367 CandidateRouteHop::PublicHop(hop) => hop.info.channel().features.clone(),
1368 CandidateRouteHop::PrivateHop(_) => ChannelFeatures::empty(),
1369 CandidateRouteHop::Blinded(_) => ChannelFeatures::empty(),
1370 CandidateRouteHop::OneHopBlinded(_) => ChannelFeatures::empty(),
1374 /// Returns the required difference in HTLC CLTV expiry between the [`Self::source`] and the
1375 /// next-hop for an HTLC taking this hop.
1377 /// This is the time that the node(s) in this hop have to claim the HTLC on-chain if the
1378 /// next-hop goes on chain with a payment preimage.
1380 pub fn cltv_expiry_delta(&self) -> u32 {
1382 CandidateRouteHop::FirstHop(_) => 0,
1383 CandidateRouteHop::PublicHop(hop) => hop.info.direction().cltv_expiry_delta as u32,
1384 CandidateRouteHop::PrivateHop(hop) => hop.hint.cltv_expiry_delta as u32,
1385 CandidateRouteHop::Blinded(hop) => hop.hint.0.cltv_expiry_delta as u32,
1386 CandidateRouteHop::OneHopBlinded(_) => 0,
1390 /// Returns the minimum amount that can be sent over this hop, in millisatoshis.
1392 pub fn htlc_minimum_msat(&self) -> u64 {
1394 CandidateRouteHop::FirstHop(hop) => hop.details.next_outbound_htlc_minimum_msat,
1395 CandidateRouteHop::PublicHop(hop) => hop.info.direction().htlc_minimum_msat,
1396 CandidateRouteHop::PrivateHop(hop) => hop.hint.htlc_minimum_msat.unwrap_or(0),
1397 CandidateRouteHop::Blinded(hop) => hop.hint.0.htlc_minimum_msat,
1398 CandidateRouteHop::OneHopBlinded { .. } => 0,
1402 /// Returns the fees that must be paid to route an HTLC over this channel.
1404 pub fn fees(&self) -> RoutingFees {
1406 CandidateRouteHop::FirstHop(_) => RoutingFees {
1407 base_msat: 0, proportional_millionths: 0,
1409 CandidateRouteHop::PublicHop(hop) => hop.info.direction().fees,
1410 CandidateRouteHop::PrivateHop(hop) => hop.hint.fees,
1411 CandidateRouteHop::Blinded(hop) => {
1413 base_msat: hop.hint.0.fee_base_msat,
1414 proportional_millionths: hop.hint.0.fee_proportional_millionths
1417 CandidateRouteHop::OneHopBlinded(_) =>
1418 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1422 /// Fetch the effective capacity of this hop.
1424 /// Note that this may be somewhat expensive, so calls to this should be limited and results
1426 fn effective_capacity(&self) -> EffectiveCapacity {
1428 CandidateRouteHop::FirstHop(hop) => EffectiveCapacity::ExactLiquidity {
1429 liquidity_msat: hop.details.next_outbound_htlc_limit_msat,
1431 CandidateRouteHop::PublicHop(hop) => hop.info.effective_capacity(),
1432 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. }) =>
1433 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1434 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. }) =>
1435 EffectiveCapacity::Infinite,
1436 CandidateRouteHop::Blinded(hop) =>
1437 EffectiveCapacity::HintMaxHTLC { amount_msat: hop.hint.0.htlc_maximum_msat },
1438 CandidateRouteHop::OneHopBlinded(_) => EffectiveCapacity::Infinite,
1442 /// Returns an ID describing the given hop.
1444 /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1446 fn id(&self) -> CandidateHopId {
1448 CandidateRouteHop::Blinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1449 CandidateRouteHop::OneHopBlinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1450 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1453 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1455 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1461 fn blinded_hint_idx(&self) -> Option<usize> {
1463 Self::Blinded(BlindedPathCandidate { hint_idx, .. }) |
1464 Self::OneHopBlinded(OneHopBlindedPathCandidate { hint_idx, .. }) => {
1470 /// Returns the source node id of current hop.
1472 /// Source node id refers to the node forwarding the HTLC through this hop.
1474 /// For [`Self::FirstHop`] we return payer's node id.
1476 pub fn source(&self) -> NodeId {
1478 CandidateRouteHop::FirstHop(hop) => *hop.payer_node_id,
1479 CandidateRouteHop::PublicHop(hop) => *hop.info.source(),
1480 CandidateRouteHop::PrivateHop(hop) => hop.hint.src_node_id.into(),
1481 CandidateRouteHop::Blinded(hop) => *hop.source_node_id,
1482 CandidateRouteHop::OneHopBlinded(hop) => *hop.source_node_id,
1485 /// Returns the target node id of this hop, if known.
1487 /// Target node id refers to the node receiving the HTLC after this hop.
1489 /// For [`Self::Blinded`] we return `None` because the ultimate destination after the blinded
1490 /// path is unknown.
1492 /// For [`Self::OneHopBlinded`] we return `None` because the target is the same as the source,
1493 /// and such a return value would be somewhat nonsensical.
1495 pub fn target(&self) -> Option<NodeId> {
1497 CandidateRouteHop::FirstHop(hop) => Some(hop.details.counterparty.node_id.into()),
1498 CandidateRouteHop::PublicHop(hop) => Some(*hop.info.target()),
1499 CandidateRouteHop::PrivateHop(hop) => Some(*hop.target_node_id),
1500 CandidateRouteHop::Blinded(_) => None,
1501 CandidateRouteHop::OneHopBlinded(_) => None,
1506 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1508 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1510 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1511 /// isn't guaranteed to be unique at all.
1513 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1514 /// difficult-to-use API.
1515 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1516 enum CandidateHopId {
1517 /// Contains (scid, src_node_id < target_node_id)
1519 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1524 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1525 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1527 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1528 EffectiveCapacity::Infinite => u64::max_value(),
1529 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1530 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1531 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1532 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1533 // expected to have been generated from up-to-date capacity information.
1534 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1535 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1536 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1540 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1541 -> bool where I1::Item: PartialEq<I2::Item> {
1543 let a = iter_a.next();
1544 let b = iter_b.next();
1545 if a.is_none() && b.is_none() { return true; }
1546 if a.is_none() || b.is_none() { return false; }
1547 if a.unwrap().ne(&b.unwrap()) { return false; }
1551 /// It's useful to keep track of the hops associated with the fees required to use them,
1552 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1553 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1554 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1556 #[repr(C)] // Force fields to appear in the order we define them.
1557 struct PathBuildingHop<'a> {
1558 candidate: CandidateRouteHop<'a>,
1559 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1560 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1561 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1562 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1563 /// avoid processing them again.
1564 was_processed: bool,
1565 /// Used to compare channels when choosing the for routing.
1566 /// Includes paying for the use of a hop and the following hops, as well as
1567 /// an estimated cost of reaching this hop.
1568 /// Might get stale when fees are recomputed. Primarily for internal use.
1569 total_fee_msat: u64,
1570 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1571 /// walk and may be invalid thereafter.
1572 path_htlc_minimum_msat: u64,
1573 /// All penalties incurred from this channel on the way to the destination, as calculated using
1574 /// channel scoring.
1575 path_penalty_msat: u64,
1577 // The last 16 bytes are on the next cache line by default in glibc's malloc. Thus, we should
1578 // only place fields which are not hot there. Luckily, the next three fields are only read if
1579 // we end up on the selected path, and only in the final path layout phase, so we don't care
1580 // too much if reading them is slow.
1584 /// All the fees paid *after* this channel on the way to the destination
1585 next_hops_fee_msat: u64,
1586 /// Fee paid for the use of the current channel (see candidate.fees()).
1587 /// The value will be actually deducted from the counterparty balance on the previous link.
1588 hop_use_fee_msat: u64,
1590 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1591 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1592 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1593 // value_contribution_msat, which requires tracking it here. See comments below where it is
1594 // used for more info.
1595 value_contribution_msat: u64,
1598 // Checks that the entries in the `find_route` `dist` map fit in (exactly) two standard x86-64
1599 // cache lines. Sadly, they're not guaranteed to actually lie on a cache line (and in fact,
1600 // generally won't, because at least glibc's malloc will align to a nice, big, round
1601 // boundary...plus 16), but at least it will reduce the amount of data we'll need to load.
1603 // Note that these assertions only pass on somewhat recent rustc, and thus are gated on the
1606 const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::<(NodeId, PathBuildingHop)>();
1608 const _NODE_MAP_SIZE_EXACTLY_CACHE_LINES: usize = core::mem::size_of::<(NodeId, PathBuildingHop)>() - 128;
1610 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1611 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1612 let mut debug_struct = f.debug_struct("PathBuildingHop");
1614 .field("node_id", &self.candidate.target())
1615 .field("short_channel_id", &self.candidate.short_channel_id())
1616 .field("total_fee_msat", &self.total_fee_msat)
1617 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1618 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1619 .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)))
1620 .field("path_penalty_msat", &self.path_penalty_msat)
1621 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1622 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1623 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1624 let debug_struct = debug_struct
1625 .field("value_contribution_msat", &self.value_contribution_msat);
1626 debug_struct.finish()
1630 // Instantiated with a list of hops with correct data in them collected during path finding,
1631 // an instance of this struct should be further modified only via given methods.
1633 struct PaymentPath<'a> {
1634 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1637 impl<'a> PaymentPath<'a> {
1638 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1639 fn get_value_msat(&self) -> u64 {
1640 self.hops.last().unwrap().0.fee_msat
1643 fn get_path_penalty_msat(&self) -> u64 {
1644 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1647 fn get_total_fee_paid_msat(&self) -> u64 {
1648 if self.hops.len() < 1 {
1652 // Can't use next_hops_fee_msat because it gets outdated.
1653 for (i, (hop, _)) in self.hops.iter().enumerate() {
1654 if i != self.hops.len() - 1 {
1655 result += hop.fee_msat;
1661 fn get_cost_msat(&self) -> u64 {
1662 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1665 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1666 // to change fees may result in an inconsistency.
1668 // Sometimes we call this function right after constructing a path which is inconsistent in
1669 // that it the value being transferred has decreased while we were doing path finding, leading
1670 // to the fees being paid not lining up with the actual limits.
1672 // Note that this function is not aware of the available_liquidity limit, and thus does not
1673 // support increasing the value being transferred beyond what was selected during the initial
1676 // Returns the amount that this path contributes to the total payment value, which may be greater
1677 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1678 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1679 let mut extra_contribution_msat = 0;
1680 let mut total_fee_paid_msat = 0 as u64;
1681 for i in (0..self.hops.len()).rev() {
1682 let last_hop = i == self.hops.len() - 1;
1684 // For non-last-hop, this value will represent the fees paid on the current hop. It
1685 // will consist of the fees for the use of the next hop, and extra fees to match
1686 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1687 let mut cur_hop_fees_msat = 0;
1689 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1692 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1693 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1694 cur_hop.path_penalty_msat += extra_contribution_msat;
1695 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1696 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1697 // set it too high just to maliciously take more fees by exploiting this
1698 // match htlc_minimum_msat logic.
1699 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1700 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1701 // Note that there is a risk that *previous hops* (those closer to us, as we go
1702 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1704 // This might make us end up with a broken route, although this should be super-rare
1705 // in practice, both because of how healthy channels look like, and how we pick
1706 // channels in add_entry.
1707 // Also, this can't be exploited more heavily than *announce a free path and fail
1709 cur_hop_transferred_amount_msat += extra_fees_msat;
1711 // We remember and return the extra fees on the final hop to allow accounting for
1712 // them in the path's value contribution.
1714 extra_contribution_msat = extra_fees_msat;
1716 total_fee_paid_msat += extra_fees_msat;
1717 cur_hop_fees_msat += extra_fees_msat;
1722 // Final hop is a special case: it usually has just value_msat (by design), but also
1723 // it still could overpay for the htlc_minimum_msat.
1724 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1726 // Propagate updated fees for the use of the channels to one hop back, where they
1727 // will be actually paid (fee_msat). The last hop is handled above separately.
1728 cur_hop.fee_msat = cur_hop_fees_msat;
1731 // Fee for the use of the current hop which will be deducted on the previous hop.
1732 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1733 // this channel is free for us.
1735 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1736 cur_hop.hop_use_fee_msat = new_fee;
1737 total_fee_paid_msat += new_fee;
1739 // It should not be possible because this function is called only to reduce the
1740 // value. In that case, compute_fee was already called with the same fees for
1741 // larger amount and there was no overflow.
1746 value_msat + extra_contribution_msat
1751 /// Calculate the fees required to route the given amount over a channel with the given fees.
1752 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1753 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1754 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1758 /// Calculate the fees required to route the given amount over a channel with the given fees,
1759 /// saturating to [`u64::max_value`].
1760 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1761 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1762 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1763 .saturating_add(channel_fees.base_msat as u64)
1766 /// The default `features` we assume for a node in a route, when no `features` are known about that
1769 /// Default features are:
1770 /// * variable_length_onion_optional
1771 fn default_node_features() -> NodeFeatures {
1772 let mut features = NodeFeatures::empty();
1773 features.set_variable_length_onion_optional();
1777 struct LoggedPayeePubkey(Option<PublicKey>);
1778 impl fmt::Display for LoggedPayeePubkey {
1779 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1782 "payee node id ".fmt(f)?;
1786 "blinded payee".fmt(f)
1792 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1793 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1794 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1796 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1797 "blinded route hint with introduction node ".fmt(f)?;
1798 match &hint.1.introduction_node {
1799 IntroductionNode::NodeId(pubkey) => write!(f, "id {}", pubkey)?,
1800 IntroductionNode::DirectedShortChannelId(direction, scid) => {
1802 Direction::NodeOne => {
1803 write!(f, "one on channel with SCID {}", scid)?;
1805 Direction::NodeTwo => {
1806 write!(f, "two on channel with SCID {}", scid)?;
1811 " and blinding point ".fmt(f)?;
1812 hint.1.blinding_point.fmt(f)
1814 CandidateRouteHop::FirstHop(_) => {
1815 "first hop with SCID ".fmt(f)?;
1816 self.0.short_channel_id().unwrap().fmt(f)
1818 CandidateRouteHop::PrivateHop(_) => {
1819 "route hint with SCID ".fmt(f)?;
1820 self.0.short_channel_id().unwrap().fmt(f)
1824 self.0.short_channel_id().unwrap().fmt(f)
1831 fn sort_first_hop_channels(
1832 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1833 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1835 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1836 // most like to use.
1838 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1839 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1842 // Second, because simply always sorting in descending order would always use our largest
1843 // available outbound capacity, needlessly fragmenting our available channel capacities,
1844 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1845 // which have enough, but not too much, capacity for the payment.
1847 // Available outbound balances factor in liquidity already reserved for previously found paths.
1848 channels.sort_unstable_by(|chan_a, chan_b| {
1849 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1850 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1851 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1852 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1853 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1854 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1855 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1856 // Sort in descending order
1857 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1859 // Sort in ascending order
1860 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1865 /// Finds a route from us (payer) to the given target node (payee).
1867 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1868 /// in the given [`RouteParameters::payment_params`].
1869 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1871 /// Private routing paths between a public node and the target may be included in the `payee` field
1872 /// of [`RouteParameters::payment_params`].
1874 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1875 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1876 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1878 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1879 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1880 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1884 /// Panics if first_hops contains channels without `short_channel_id`s;
1885 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1887 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1888 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1889 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1890 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1891 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1892 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1893 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1894 ) -> Result<Route, LightningError>
1895 where L::Target: Logger, GL::Target: Logger {
1896 let graph_lock = network_graph.read_only();
1897 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1898 scorer, score_params, random_seed_bytes)?;
1899 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1903 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1904 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1905 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1906 _random_seed_bytes: &[u8; 32]
1907 ) -> Result<Route, LightningError>
1908 where L::Target: Logger {
1910 let payment_params = &route_params.payment_params;
1911 let max_path_length = core::cmp::min(payment_params.max_path_length, MAX_PATH_LENGTH_ESTIMATE);
1912 let final_value_msat = route_params.final_value_msat;
1913 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1914 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1915 // so use a dummy id for this in the blinded case.
1916 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1917 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1918 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1919 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1920 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1922 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1923 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1925 if our_node_id == maybe_dummy_payee_node_id {
1926 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1929 if final_value_msat > MAX_VALUE_MSAT {
1930 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1933 if final_value_msat == 0 {
1934 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1937 let introduction_node_id_cache = payment_params.payee.blinded_route_hints().iter()
1938 .map(|(_, path)| path.public_introduction_node_id(network_graph))
1939 .collect::<Vec<_>>();
1940 match &payment_params.payee {
1941 Payee::Clear { route_hints, node_id, .. } => {
1942 for route in route_hints.iter() {
1943 for hop in &route.0 {
1944 if hop.src_node_id == *node_id {
1945 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1950 Payee::Blinded { route_hints, .. } => {
1951 if introduction_node_id_cache.iter().all(|introduction_node_id| *introduction_node_id == Some(&our_node_id)) {
1952 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});
1954 for ((_, blinded_path), introduction_node_id) in route_hints.iter().zip(introduction_node_id_cache.iter()) {
1955 if blinded_path.blinded_hops.len() == 0 {
1956 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1957 } else if *introduction_node_id == Some(&our_node_id) {
1958 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1959 } else if blinded_path.blinded_hops.len() == 1 &&
1961 .iter().zip(introduction_node_id_cache.iter())
1962 .filter(|((_, p), _)| p.blinded_hops.len() == 1)
1963 .any(|(_, p_introduction_node_id)| p_introduction_node_id != introduction_node_id)
1965 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1970 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1971 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1972 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});
1975 // The general routing idea is the following:
1976 // 1. Fill first/last hops communicated by the caller.
1977 // 2. Attempt to construct a path from payer to payee for transferring
1978 // any ~sufficient (described later) value.
1979 // If succeed, remember which channels were used and how much liquidity they have available,
1980 // so that future paths don't rely on the same liquidity.
1981 // 3. Proceed to the next step if:
1982 // - we hit the recommended target value;
1983 // - OR if we could not construct a new path. Any next attempt will fail too.
1984 // Otherwise, repeat step 2.
1985 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1986 // (not recommended value).
1987 // 5. If yes, proceed. If not, fail routing.
1988 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1989 // transferred up to the transfer target value.
1990 // 7. Reduce the value of the last path until we are sending only the target value.
1991 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1992 // them so that we're not sending two HTLCs along the same path.
1994 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1995 // distance from the payee
1997 // We are not a faithful Dijkstra's implementation because we can change values which impact
1998 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1999 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
2000 // the value we are currently attempting to send over a path, we simply reduce the value being
2001 // sent along the path for any hops after that channel. This may imply that later fees (which
2002 // we've already tabulated) are lower because a smaller value is passing through the channels
2003 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
2004 // channels which were selected earlier (and which may still be used for other paths without a
2005 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
2008 // One potentially problematic case for this algorithm would be if there are many
2009 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
2010 // graph walking), we may never find a path which is not liquidity-limited and has lower
2011 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
2012 // Because we only consider paths with at least 5% of the total value being sent, the damage
2013 // from such a case should be limited, however this could be further reduced in the future by
2014 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
2015 // limits for the purposes of fee calculation.
2017 // Alternatively, we could store more detailed path information in the heap (targets, below)
2018 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
2019 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
2020 // and practically (as we would need to store dynamically-allocated path information in heap
2021 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
2022 // results of such an algorithm would likely be biased towards lower-value paths.
2024 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
2025 // outside of our current search value, running a path search more times to gather candidate
2026 // paths at different values. While this may be acceptable, further path searches may increase
2027 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
2028 // graph for candidate paths, calculating the maximum value which can realistically be sent at
2029 // the same time, remaining generic across different payment values.
2031 let network_channels = network_graph.channels();
2032 let network_nodes = network_graph.nodes();
2034 if payment_params.max_path_count == 0 {
2035 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
2038 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
2039 // it. If the payee supports it they're supposed to include it in the invoice, so that should
2041 let allow_mpp = if payment_params.max_path_count == 1 {
2043 } else if payment_params.payee.supports_basic_mpp() {
2045 } else if let Some(payee) = payee_node_id_opt {
2046 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
2047 |info| info.features().supports_basic_mpp()))
2050 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
2052 let first_hop_count = first_hops.map(|hops| hops.len()).unwrap_or(0);
2053 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph of {} nodes and {} channels with a fee limit of {} msat",
2054 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
2055 if allow_mpp { "with" } else { "without" },
2056 first_hop_count, if first_hops.is_some() { "" } else { "not " },
2057 network_graph.nodes().len(), network_graph.channels().len(),
2058 max_total_routing_fee_msat);
2060 if first_hop_count < 10 {
2061 if let Some(hops) = first_hops {
2065 " First hop through {}/{} can send between {}msat and {}msat (inclusive).",
2066 hop.counterparty.node_id,
2067 hop.get_outbound_payment_scid().unwrap_or(0),
2068 hop.next_outbound_htlc_minimum_msat,
2069 hop.next_outbound_htlc_limit_msat
2076 // Prepare the data we'll use for payee-to-payer search by
2077 // inserting first hops suggested by the caller as targets.
2078 // Our search will then attempt to reach them while traversing from the payee node.
2079 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
2080 hash_map_with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
2081 if let Some(hops) = first_hops {
2083 if chan.get_outbound_payment_scid().is_none() {
2084 panic!("first_hops should be filled in with usable channels, not pending ones");
2086 if chan.counterparty.node_id == *our_node_pubkey {
2087 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
2090 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
2091 .or_insert(Vec::new())
2094 if first_hop_targets.is_empty() {
2095 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
2099 let mut private_hop_key_cache = hash_map_with_capacity(
2100 payment_params.payee.unblinded_route_hints().iter().map(|path| path.0.len()).sum()
2103 // Because we store references to private hop node_ids in `dist`, below, we need them to exist
2104 // (as `NodeId`, not `PublicKey`) for the lifetime of `dist`. Thus, we calculate all the keys
2105 // we'll need here and simply fetch them when routing.
2106 private_hop_key_cache.insert(maybe_dummy_payee_pk, NodeId::from_pubkey(&maybe_dummy_payee_pk));
2107 for route in payment_params.payee.unblinded_route_hints().iter() {
2108 for hop in route.0.iter() {
2109 private_hop_key_cache.insert(hop.src_node_id, NodeId::from_pubkey(&hop.src_node_id));
2113 // The main heap containing all candidate next-hops sorted by their score (max(fee,
2114 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
2115 // adding duplicate entries when we find a better path to a given node.
2116 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
2118 // Map from node_id to information about the best current path to that node, including feerate
2120 let mut dist: HashMap<NodeId, PathBuildingHop> = hash_map_with_capacity(network_nodes.len());
2122 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
2123 // indicating that we may wish to try again with a higher value, potentially paying to meet an
2124 // htlc_minimum with extra fees while still finding a cheaper path.
2125 let mut hit_minimum_limit;
2127 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
2128 // We start with a path_value of the exact amount we want, and if that generates a route we may
2129 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
2130 // amount we want in total across paths, selecting the best subset at the end.
2131 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
2132 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
2133 let mut path_value_msat = final_value_msat;
2135 // Routing Fragmentation Mitigation heuristic:
2137 // Routing fragmentation across many payment paths increases the overall routing
2138 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
2139 // Taking too many smaller paths also increases the chance of payment failure.
2140 // Thus to avoid this effect, we require from our collected links to provide
2141 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
2142 // This requirement is currently set to be 1/max_path_count of the payment
2143 // value to ensure we only ever return routes that do not violate this limit.
2144 let minimal_value_contribution_msat: u64 = if allow_mpp {
2145 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
2150 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
2151 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
2152 // drop the requirement by setting this to 0.
2153 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
2155 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
2156 // determine if the channel can be used by additional MPP paths or to inform path finding
2157 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
2158 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
2160 let mut used_liquidities: HashMap<CandidateHopId, u64> =
2161 hash_map_with_capacity(network_nodes.len());
2163 // Keeping track of how much value we already collected across other paths. Helps to decide
2164 // when we want to stop looking for new paths.
2165 let mut already_collected_value_msat = 0;
2167 for (_, channels) in first_hop_targets.iter_mut() {
2168 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
2172 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
2173 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
2175 // Remember how many candidates we ignored to allow for some logging afterwards.
2176 let mut num_ignored_value_contribution: u32 = 0;
2177 let mut num_ignored_path_length_limit: u32 = 0;
2178 let mut num_ignored_cltv_delta_limit: u32 = 0;
2179 let mut num_ignored_previously_failed: u32 = 0;
2180 let mut num_ignored_total_fee_limit: u32 = 0;
2181 let mut num_ignored_avoid_overpayment: u32 = 0;
2182 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
2184 macro_rules! add_entry {
2185 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
2186 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
2187 // since that value has to be transferred over this channel.
2188 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
2189 ( $candidate: expr, $next_hops_fee_msat: expr,
2190 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
2191 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
2192 // We "return" whether we updated the path at the end, and how much we can route via
2193 // this channel, via this:
2194 let mut hop_contribution_amt_msat = None;
2195 // Channels to self should not be used. This is more of belt-and-suspenders, because in
2196 // practice these cases should be caught earlier:
2197 // - for regular channels at channel announcement (TODO)
2198 // - for first and last hops early in get_route
2199 let src_node_id = $candidate.source();
2200 if Some(src_node_id) != $candidate.target() {
2201 let scid_opt = $candidate.short_channel_id();
2202 let effective_capacity = $candidate.effective_capacity();
2203 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
2205 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
2206 // It may be misleading because we might later choose to reduce the value transferred
2207 // over these channels, and the channel which was insufficient might become sufficient.
2208 // Worst case: we drop a good channel here because it can't cover the high following
2209 // fees caused by one expensive channel, but then this channel could have been used
2210 // if the amount being transferred over this path is lower.
2211 // We do this for now, but this is a subject for removal.
2212 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
2213 let used_liquidity_msat = used_liquidities
2214 .get(&$candidate.id())
2215 .map_or(0, |used_liquidity_msat| {
2216 available_value_contribution_msat = available_value_contribution_msat
2217 .saturating_sub(*used_liquidity_msat);
2218 *used_liquidity_msat
2221 // Verify the liquidity offered by this channel complies to the minimal contribution.
2222 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
2223 // Do not consider candidate hops that would exceed the maximum path length.
2224 let path_length_to_node = $next_hops_path_length
2225 + if $candidate.blinded_hint_idx().is_some() { 0 } else { 1 };
2226 let exceeds_max_path_length = path_length_to_node > max_path_length;
2228 // Do not consider candidates that exceed the maximum total cltv expiry limit.
2229 // In order to already account for some of the privacy enhancing random CLTV
2230 // expiry delta offset we add on top later, we subtract a rough estimate
2231 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
2232 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
2233 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
2234 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
2235 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
2236 .saturating_add($candidate.cltv_expiry_delta());
2237 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
2239 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
2240 // Includes paying fees for the use of the following channels.
2241 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
2242 Some(result) => result,
2243 // Can't overflow due to how the values were computed right above.
2244 None => unreachable!(),
2246 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2247 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
2248 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
2250 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2251 let may_overpay_to_meet_path_minimum_msat =
2252 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
2253 recommended_value_msat >= $candidate.htlc_minimum_msat()) ||
2254 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
2255 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
2257 let payment_failed_on_this_channel = match scid_opt {
2258 Some(scid) => payment_params.previously_failed_channels.contains(&scid),
2259 None => match $candidate.blinded_hint_idx() {
2261 payment_params.previously_failed_blinded_path_idxs.contains(&(idx as u64))
2267 let (should_log_candidate, first_hop_details) = match $candidate {
2268 CandidateRouteHop::FirstHop(hop) => (true, Some(hop.details)),
2269 CandidateRouteHop::PrivateHop(_) => (true, None),
2270 CandidateRouteHop::Blinded(_) => (true, None),
2271 CandidateRouteHop::OneHopBlinded(_) => (true, None),
2275 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
2276 // bother considering this channel. If retrying with recommended_value_msat may
2277 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
2278 // around again with a higher amount.
2279 if !contributes_sufficient_value {
2280 if should_log_candidate {
2281 log_trace!(logger, "Ignoring {} due to insufficient value contribution (channel max {:?}).",
2282 LoggedCandidateHop(&$candidate),
2283 effective_capacity);
2285 num_ignored_value_contribution += 1;
2286 } else if exceeds_max_path_length {
2287 if should_log_candidate {
2288 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
2290 num_ignored_path_length_limit += 1;
2291 } else if exceeds_cltv_delta_limit {
2292 if should_log_candidate {
2293 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
2295 if let Some(_) = first_hop_details {
2297 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
2298 hop_total_cltv_delta,
2299 max_total_cltv_expiry_delta,
2303 num_ignored_cltv_delta_limit += 1;
2304 } else if payment_failed_on_this_channel {
2305 if should_log_candidate {
2306 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
2308 num_ignored_previously_failed += 1;
2309 } else if may_overpay_to_meet_path_minimum_msat {
2310 if should_log_candidate {
2312 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit ({}).",
2313 LoggedCandidateHop(&$candidate), $candidate.htlc_minimum_msat());
2315 num_ignored_avoid_overpayment += 1;
2316 hit_minimum_limit = true;
2317 } else if over_path_minimum_msat {
2318 // Note that low contribution here (limited by available_liquidity_msat)
2319 // might violate htlc_minimum_msat on the hops which are next along the
2320 // payment path (upstream to the payee). To avoid that, we recompute
2321 // path fees knowing the final path contribution after constructing it.
2322 let curr_min = cmp::max(
2323 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
2325 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
2326 .saturating_add(curr_min);
2327 let hm_entry = dist.entry(src_node_id);
2328 let old_entry = hm_entry.or_insert_with(|| {
2329 // If there was previously no known way to access the source node
2330 // (recall it goes payee-to-payer) of short_channel_id, first add a
2331 // semi-dummy record just to compute the fees to reach the source node.
2332 // This will affect our decision on selecting short_channel_id
2333 // as a way to reach the $candidate.target() node.
2335 candidate: $candidate.clone(),
2337 next_hops_fee_msat: u64::max_value(),
2338 hop_use_fee_msat: u64::max_value(),
2339 total_fee_msat: u64::max_value(),
2340 path_htlc_minimum_msat,
2341 path_penalty_msat: u64::max_value(),
2342 was_processed: false,
2343 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2344 value_contribution_msat,
2348 #[allow(unused_mut)] // We only use the mut in cfg(test)
2349 let mut should_process = !old_entry.was_processed;
2350 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2352 // In test/fuzzing builds, we do extra checks to make sure the skipping
2353 // of already-seen nodes only happens in cases we expect (see below).
2354 if !should_process { should_process = true; }
2358 let mut hop_use_fee_msat = 0;
2359 let mut total_fee_msat: u64 = $next_hops_fee_msat;
2361 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2362 // will have the same effective-fee
2363 if src_node_id != our_node_id {
2364 // Note that `u64::max_value` means we'll always fail the
2365 // `old_entry.total_fee_msat > total_fee_msat` check below
2366 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
2367 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2370 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2371 if total_fee_msat > max_total_routing_fee_msat {
2372 if should_log_candidate {
2373 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2375 if let Some(_) = first_hop_details {
2377 "First hop candidate routing fee: {}. Limit: {}",
2379 max_total_routing_fee_msat,
2383 num_ignored_total_fee_limit += 1;
2385 let channel_usage = ChannelUsage {
2386 amount_msat: amount_to_transfer_over_msat,
2387 inflight_htlc_msat: used_liquidity_msat,
2390 let channel_penalty_msat =
2391 scorer.channel_penalty_msat($candidate,
2394 let path_penalty_msat = $next_hops_path_penalty_msat
2395 .saturating_add(channel_penalty_msat);
2397 // Update the way of reaching $candidate.source()
2398 // with the given short_channel_id (from $candidate.target()),
2399 // if this way is cheaper than the already known
2400 // (considering the cost to "reach" this channel from the route destination,
2401 // the cost of using this channel,
2402 // and the cost of routing to the source node of this channel).
2403 // Also, consider that htlc_minimum_msat_difference, because we might end up
2404 // paying it. Consider the following exploit:
2405 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2406 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2407 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2408 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2410 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2411 // but it may require additional tracking - we don't want to double-count
2412 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2413 // can't use something that may decrease on future hops.
2414 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2415 .saturating_add(old_entry.path_penalty_msat);
2416 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2417 .saturating_add(path_penalty_msat);
2419 if !old_entry.was_processed && new_cost < old_cost {
2420 let new_graph_node = RouteGraphNode {
2421 node_id: src_node_id,
2422 score: cmp::max(total_fee_msat, path_htlc_minimum_msat).saturating_add(path_penalty_msat),
2423 total_cltv_delta: hop_total_cltv_delta,
2424 value_contribution_msat,
2425 path_length_to_node,
2427 targets.push(new_graph_node);
2428 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2429 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2430 old_entry.total_fee_msat = total_fee_msat;
2431 old_entry.candidate = $candidate.clone();
2432 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2433 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2434 old_entry.path_penalty_msat = path_penalty_msat;
2435 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2437 old_entry.value_contribution_msat = value_contribution_msat;
2439 hop_contribution_amt_msat = Some(value_contribution_msat);
2440 } else if old_entry.was_processed && new_cost < old_cost {
2441 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2443 // If we're skipping processing a node which was previously
2444 // processed even though we found another path to it with a
2445 // cheaper fee, check that it was because the second path we
2446 // found (which we are processing now) has a lower value
2447 // contribution due to an HTLC minimum limit.
2449 // e.g. take a graph with two paths from node 1 to node 2, one
2450 // through channel A, and one through channel B. Channel A and
2451 // B are both in the to-process heap, with their scores set by
2452 // a higher htlc_minimum than fee.
2453 // Channel A is processed first, and the channels onwards from
2454 // node 1 are added to the to-process heap. Thereafter, we pop
2455 // Channel B off of the heap, note that it has a much more
2456 // restrictive htlc_maximum_msat, and recalculate the fees for
2457 // all of node 1's channels using the new, reduced, amount.
2459 // This would be bogus - we'd be selecting a higher-fee path
2460 // with a lower htlc_maximum_msat instead of the one we'd
2461 // already decided to use.
2462 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2464 value_contribution_msat + path_penalty_msat <
2465 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2472 if should_log_candidate {
2474 "Ignoring {} due to its htlc_minimum_msat limit.",
2475 LoggedCandidateHop(&$candidate));
2477 if let Some(details) = first_hop_details {
2479 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2480 details.next_outbound_htlc_minimum_msat,
2484 num_ignored_htlc_minimum_msat_limit += 1;
2488 hop_contribution_amt_msat
2492 let default_node_features = default_node_features();
2494 // Find ways (channels with destination) to reach a given node and store them
2495 // in the corresponding data structures (routing graph etc).
2496 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2497 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2498 // This data can later be helpful to optimize routing (pay lower fees).
2499 macro_rules! add_entries_to_cheapest_to_target_node {
2500 ( $node: expr, $node_id: expr, $next_hops_value_contribution: expr,
2501 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2502 let fee_to_target_msat;
2503 let next_hops_path_htlc_minimum_msat;
2504 let next_hops_path_penalty_msat;
2505 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
2506 let was_processed = elem.was_processed;
2507 elem.was_processed = true;
2508 fee_to_target_msat = elem.total_fee_msat;
2509 next_hops_path_htlc_minimum_msat = elem.path_htlc_minimum_msat;
2510 next_hops_path_penalty_msat = elem.path_penalty_msat;
2513 // Entries are added to dist in add_entry!() when there is a channel from a node.
2514 // Because there are no channels from payee, it will not have a dist entry at this point.
2515 // If we're processing any other node, it is always be the result of a channel from it.
2516 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2517 fee_to_target_msat = 0;
2518 next_hops_path_htlc_minimum_msat = 0;
2519 next_hops_path_penalty_msat = 0;
2524 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
2525 for details in first_channels {
2526 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2527 details, payer_node_id: &our_node_id,
2529 add_entry!(&candidate, fee_to_target_msat,
2530 $next_hops_value_contribution,
2531 next_hops_path_htlc_minimum_msat, next_hops_path_penalty_msat,
2532 $next_hops_cltv_delta, $next_hops_path_length);
2536 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2537 &node_info.features()
2539 &default_node_features
2542 if !features.requires_unknown_bits() {
2543 for chan_id in $node.channels.iter() {
2544 let chan = network_channels.get(chan_id).unwrap();
2545 if !chan.features.requires_unknown_bits() {
2546 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2547 if first_hops.is_none() || *source != our_node_id {
2548 if directed_channel.direction().enabled {
2549 let candidate = CandidateRouteHop::PublicHop(PublicHopCandidate {
2550 info: directed_channel,
2551 short_channel_id: *chan_id,
2553 add_entry!(&candidate,
2555 $next_hops_value_contribution,
2556 next_hops_path_htlc_minimum_msat,
2557 next_hops_path_penalty_msat,
2558 $next_hops_cltv_delta, $next_hops_path_length);
2569 let mut payment_paths = Vec::<PaymentPath>::new();
2571 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2572 'paths_collection: loop {
2573 // For every new path, start from scratch, except for used_liquidities, which
2574 // helps to avoid reusing previously selected paths in future iterations.
2577 hit_minimum_limit = false;
2579 // If first hop is a private channel and the only way to reach the payee, this is the only
2580 // place where it could be added.
2581 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2582 for details in first_channels {
2583 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2584 details, payer_node_id: &our_node_id,
2586 let added = add_entry!(&candidate, 0, path_value_msat,
2587 0, 0u64, 0, 0).is_some();
2588 log_trace!(logger, "{} direct route to payee via {}",
2589 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2593 // Add the payee as a target, so that the payee-to-payer
2594 // search algorithm knows what to start with.
2595 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2596 // The payee is not in our network graph, so nothing to add here.
2597 // There is still a chance of reaching them via last_hops though,
2598 // so don't yet fail the payment here.
2599 // If not, targets.pop() will not even let us enter the loop in step 2.
2602 add_entries_to_cheapest_to_target_node!(node, payee, path_value_msat, 0, 0);
2607 // If a caller provided us with last hops, add them to routing targets. Since this happens
2608 // earlier than general path finding, they will be somewhat prioritized, although currently
2609 // it matters only if the fees are exactly the same.
2610 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2611 // Only add the hops in this route to our candidate set if either
2612 // we have a direct channel to the first hop or the first hop is
2613 // in the regular network graph.
2614 let source_node_id = match introduction_node_id_cache[hint_idx] {
2615 Some(node_id) => node_id,
2616 None => match &hint.1.introduction_node {
2617 IntroductionNode::NodeId(pubkey) => {
2618 let node_id = NodeId::from_pubkey(&pubkey);
2619 match first_hop_targets.get_key_value(&node_id).map(|(key, _)| key) {
2620 Some(node_id) => node_id,
2624 IntroductionNode::DirectedShortChannelId(direction, scid) => {
2625 let first_hop = first_hop_targets.iter().find(|(_, channels)|
2628 .any(|details| Some(*scid) == details.get_outbound_payment_scid())
2631 Some((counterparty_node_id, _)) => {
2632 direction.select_node_id(&our_node_id, counterparty_node_id)
2639 if our_node_id == *source_node_id { continue }
2640 let candidate = if hint.1.blinded_hops.len() == 1 {
2641 CandidateRouteHop::OneHopBlinded(
2642 OneHopBlindedPathCandidate { source_node_id, hint, hint_idx }
2645 CandidateRouteHop::Blinded(BlindedPathCandidate { source_node_id, hint, hint_idx })
2647 let mut path_contribution_msat = path_value_msat;
2648 if let Some(hop_used_msat) = add_entry!(&candidate,
2649 0, path_contribution_msat, 0, 0_u64, 0, 0)
2651 path_contribution_msat = hop_used_msat;
2653 if let Some(first_channels) = first_hop_targets.get(source_node_id) {
2654 let mut first_channels = first_channels.clone();
2655 sort_first_hop_channels(
2656 &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2658 for details in first_channels {
2659 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2660 details, payer_node_id: &our_node_id,
2662 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2666 let path_min = candidate.htlc_minimum_msat().saturating_add(
2667 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2668 add_entry!(&first_hop_candidate, blinded_path_fee, path_contribution_msat, path_min,
2669 0_u64, candidate.cltv_expiry_delta(), 0);
2673 for route in payment_params.payee.unblinded_route_hints().iter()
2674 .filter(|route| !route.0.is_empty())
2676 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2677 let first_hop_src_is_reachable =
2678 // Only add the hops in this route to our candidate set if either we are part of
2679 // the first hop, we have a direct channel to the first hop, or the first hop is in
2680 // the regular network graph.
2681 our_node_id == first_hop_src_id ||
2682 first_hop_targets.get(&first_hop_src_id).is_some() ||
2683 network_nodes.get(&first_hop_src_id).is_some();
2684 if first_hop_src_is_reachable {
2685 // We start building the path from reverse, i.e., from payee
2686 // to the first RouteHintHop in the path.
2687 let hop_iter = route.0.iter().rev();
2688 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2689 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2690 let mut hop_used = true;
2691 let mut aggregate_next_hops_fee_msat: u64 = 0;
2692 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2693 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2694 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2695 let mut aggregate_next_hops_path_length: u8 = 0;
2696 let mut aggregate_path_contribution_msat = path_value_msat;
2698 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2699 let target = private_hop_key_cache.get(prev_hop_id).unwrap();
2701 if let Some(first_channels) = first_hop_targets.get(target) {
2702 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2703 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2704 hop.short_channel_id);
2709 let candidate = network_channels
2710 .get(&hop.short_channel_id)
2711 .and_then(|channel| channel.as_directed_to(target))
2712 .map(|(info, _)| CandidateRouteHop::PublicHop(PublicHopCandidate {
2714 short_channel_id: hop.short_channel_id,
2716 .unwrap_or_else(|| CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: hop, target_node_id: target }));
2718 if let Some(hop_used_msat) = add_entry!(&candidate,
2719 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2720 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2721 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2723 aggregate_path_contribution_msat = hop_used_msat;
2725 // If this hop was not used then there is no use checking the preceding
2726 // hops in the RouteHint. We can break by just searching for a direct
2727 // channel between last checked hop and first_hop_targets.
2731 let used_liquidity_msat = used_liquidities
2732 .get(&candidate.id()).copied()
2734 let channel_usage = ChannelUsage {
2735 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2736 inflight_htlc_msat: used_liquidity_msat,
2737 effective_capacity: candidate.effective_capacity(),
2739 let channel_penalty_msat = scorer.channel_penalty_msat(
2740 &candidate, channel_usage, score_params
2742 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2743 .saturating_add(channel_penalty_msat);
2745 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2746 .saturating_add(hop.cltv_expiry_delta as u32);
2748 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2751 // Searching for a direct channel between last checked hop and first_hop_targets
2752 if let Some(first_channels) = first_hop_targets.get(target) {
2753 let mut first_channels = first_channels.clone();
2754 sort_first_hop_channels(
2755 &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2757 for details in first_channels {
2758 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2759 details, payer_node_id: &our_node_id,
2761 add_entry!(&first_hop_candidate,
2762 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2763 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2764 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2772 // In the next values of the iterator, the aggregate fees already reflects
2773 // the sum of value sent from payer (final_value_msat) and routing fees
2774 // for the last node in the RouteHint. We need to just add the fees to
2775 // route through the current node so that the preceding node (next iteration)
2777 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2778 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2779 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2781 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2782 // this route hint's source node to forward said min over this channel.
2783 aggregate_next_hops_path_htlc_minimum_msat = {
2784 let curr_htlc_min = cmp::max(
2785 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2787 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2788 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2791 if idx == route.0.len() - 1 {
2792 // The last hop in this iterator is the first hop in
2793 // overall RouteHint.
2794 // If this hop connects to a node with which we have a direct channel,
2795 // ignore the network graph and, if the last hop was added, add our
2796 // direct channel to the candidate set.
2798 // Note that we *must* check if the last hop was added as `add_entry`
2799 // always assumes that the third argument is a node to which we have a
2801 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
2802 let mut first_channels = first_channels.clone();
2803 sort_first_hop_channels(
2804 &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2806 for details in first_channels {
2807 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2808 details, payer_node_id: &our_node_id,
2810 add_entry!(&first_hop_candidate,
2811 aggregate_next_hops_fee_msat,
2812 aggregate_path_contribution_msat,
2813 aggregate_next_hops_path_htlc_minimum_msat,
2814 aggregate_next_hops_path_penalty_msat,
2815 aggregate_next_hops_cltv_delta,
2816 aggregate_next_hops_path_length);
2824 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2826 // At this point, targets are filled with the data from first and
2827 // last hops communicated by the caller, and the payment receiver.
2828 let mut found_new_path = false;
2831 // If this loop terminates due the exhaustion of targets, two situations are possible:
2832 // - not enough outgoing liquidity:
2833 // 0 < already_collected_value_msat < final_value_msat
2834 // - enough outgoing liquidity:
2835 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2836 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2837 // paths_collection will be stopped because found_new_path==false.
2838 // This is not necessarily a routing failure.
2839 'path_construction: while let Some(RouteGraphNode { node_id, total_cltv_delta, mut value_contribution_msat, path_length_to_node, .. }) = targets.pop() {
2841 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2842 // traversing the graph and arrange the path out of what we found.
2843 if node_id == our_node_id {
2844 let mut new_entry = dist.remove(&our_node_id).unwrap();
2845 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2848 let mut features_set = false;
2849 let target = ordered_hops.last().unwrap().0.candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2850 if let Some(first_channels) = first_hop_targets.get(&target) {
2851 for details in first_channels {
2852 if let CandidateRouteHop::FirstHop(FirstHopCandidate { details: last_hop_details, .. })
2853 = ordered_hops.last().unwrap().0.candidate
2855 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2856 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2857 features_set = true;
2864 if let Some(node) = network_nodes.get(&target) {
2865 if let Some(node_info) = node.announcement_info.as_ref() {
2866 ordered_hops.last_mut().unwrap().1 = node_info.features().clone();
2868 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2871 // We can fill in features for everything except hops which were
2872 // provided via the invoice we're paying. We could guess based on the
2873 // recipient's features but for now we simply avoid guessing at all.
2877 // Means we successfully traversed from the payer to the payee, now
2878 // save this path for the payment route. Also, update the liquidity
2879 // remaining on the used hops, so that we take them into account
2880 // while looking for more paths.
2881 if target == maybe_dummy_payee_node_id {
2885 new_entry = match dist.remove(&target) {
2886 Some(payment_hop) => payment_hop,
2887 // We can't arrive at None because, if we ever add an entry to targets,
2888 // we also fill in the entry in dist (see add_entry!).
2889 None => unreachable!(),
2891 // We "propagate" the fees one hop backward (topologically) here,
2892 // so that fees paid for a HTLC forwarding on the current channel are
2893 // associated with the previous channel (where they will be subtracted).
2894 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2895 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2897 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2898 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2900 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2901 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2903 let mut payment_path = PaymentPath {hops: ordered_hops};
2905 // We could have possibly constructed a slightly inconsistent path: since we reduce
2906 // value being transferred along the way, we could have violated htlc_minimum_msat
2907 // on some channels we already passed (assuming dest->source direction). Here, we
2908 // recompute the fees again, so that if that's the case, we match the currently
2909 // underpaid htlc_minimum_msat with fees.
2910 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2911 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2912 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2914 // Since a path allows to transfer as much value as
2915 // the smallest channel it has ("bottleneck"), we should recompute
2916 // the fees so sender HTLC don't overpay fees when traversing
2917 // larger channels than the bottleneck. This may happen because
2918 // when we were selecting those channels we were not aware how much value
2919 // this path will transfer, and the relative fee for them
2920 // might have been computed considering a larger value.
2921 // Remember that we used these channels so that we don't rely
2922 // on the same liquidity in future paths.
2923 let mut prevented_redundant_path_selection = false;
2924 for (hop, _) in payment_path.hops.iter() {
2925 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2926 let used_liquidity_msat = used_liquidities
2927 .entry(hop.candidate.id())
2928 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2929 .or_insert(spent_on_hop_msat);
2930 let hop_capacity = hop.candidate.effective_capacity();
2931 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2932 if *used_liquidity_msat == hop_max_msat {
2933 // If this path used all of this channel's available liquidity, we know
2934 // this path will not be selected again in the next loop iteration.
2935 prevented_redundant_path_selection = true;
2937 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2939 if !prevented_redundant_path_selection {
2940 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2941 // we'll probably end up picking the same path again on the next iteration.
2942 // Decrease the available liquidity of a hop in the middle of the path.
2943 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2944 let exhausted = u64::max_value();
2946 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2947 LoggedCandidateHop(victim_candidate));
2948 if let Some(scid) = victim_candidate.short_channel_id() {
2949 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2950 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2954 // Track the total amount all our collected paths allow to send so that we know
2955 // when to stop looking for more paths
2956 already_collected_value_msat += value_contribution_msat;
2958 payment_paths.push(payment_path);
2959 found_new_path = true;
2960 break 'path_construction;
2963 // If we found a path back to the payee, we shouldn't try to process it again. This is
2964 // the equivalent of the `elem.was_processed` check in
2965 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2966 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2968 // Otherwise, since the current target node is not us,
2969 // keep "unrolling" the payment graph from payee to payer by
2970 // finding a way to reach the current target from the payer side.
2971 match network_nodes.get(&node_id) {
2974 add_entries_to_cheapest_to_target_node!(node, node_id,
2975 value_contribution_msat,
2976 total_cltv_delta, path_length_to_node);
2982 if !found_new_path && channel_saturation_pow_half != 0 {
2983 channel_saturation_pow_half = 0;
2984 continue 'paths_collection;
2986 // If we don't support MPP, no use trying to gather more value ever.
2987 break 'paths_collection;
2991 // Stop either when the recommended value is reached or if no new path was found in this
2993 // In the latter case, making another path finding attempt won't help,
2994 // because we deterministically terminated the search due to low liquidity.
2995 if !found_new_path && channel_saturation_pow_half != 0 {
2996 channel_saturation_pow_half = 0;
2997 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2998 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
2999 path_value_msat = recommended_value_msat;
3000 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
3001 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
3002 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
3003 break 'paths_collection;
3004 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
3005 // Further, if this was our first walk of the graph, and we weren't limited by an
3006 // htlc_minimum_msat, return immediately because this path should suffice. If we were
3007 // limited by an htlc_minimum_msat value, find another path with a higher value,
3008 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
3009 // still keeping a lower total fee than this path.
3010 if !hit_minimum_limit {
3011 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
3012 break 'paths_collection;
3014 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.");
3015 path_value_msat = recommended_value_msat;
3019 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
3020 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
3021 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
3022 num_ignored_total_fee_limit;
3023 if num_ignored_total > 0 {
3025 "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.",
3026 num_ignored_value_contribution, num_ignored_path_length_limit,
3027 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
3028 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
3029 num_ignored_total_fee_limit, num_ignored_total);
3033 if payment_paths.len() == 0 {
3034 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
3037 if already_collected_value_msat < final_value_msat {
3038 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
3042 let mut selected_route = payment_paths;
3044 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
3045 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
3047 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
3048 // the value they contribute towards the payment amount.
3049 // We sort in descending order as we will remove from the front in `retain`, next.
3050 selected_route.sort_unstable_by(|a, b|
3051 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
3052 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
3055 // We should make sure that at least 1 path left.
3056 let mut paths_left = selected_route.len();
3057 selected_route.retain(|path| {
3058 if paths_left == 1 {
3061 let path_value_msat = path.get_value_msat();
3062 if path_value_msat <= overpaid_value_msat {
3063 overpaid_value_msat -= path_value_msat;
3069 debug_assert!(selected_route.len() > 0);
3071 if overpaid_value_msat != 0 {
3073 // Now, subtract the remaining overpaid value from the most-expensive path.
3074 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
3075 // so that the sender pays less fees overall. And also htlc_minimum_msat.
3076 selected_route.sort_unstable_by(|a, b| {
3077 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3078 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3079 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
3081 let expensive_payment_path = selected_route.first_mut().unwrap();
3083 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
3084 // can't go negative.
3085 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
3086 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
3090 // Sort by the path itself and combine redundant paths.
3091 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
3092 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
3094 selected_route.sort_unstable_by_key(|path| {
3095 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
3096 debug_assert!(path.hops.len() <= key.len());
3097 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
3102 for idx in 0..(selected_route.len() - 1) {
3103 if idx + 1 >= selected_route.len() { break; }
3104 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
3105 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
3106 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
3107 selected_route[idx].update_value_and_recompute_fees(new_value);
3108 selected_route.remove(idx + 1);
3112 let mut paths = Vec::new();
3113 for payment_path in selected_route {
3114 let mut hops = Vec::with_capacity(payment_path.hops.len());
3115 for (hop, node_features) in payment_path.hops.iter()
3116 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
3118 let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
3119 let maybe_announced_channel = if let CandidateRouteHop::PublicHop(_) = hop.candidate {
3120 // If we sourced the hop from the graph we're sure the target node is announced.
3122 } else if let CandidateRouteHop::FirstHop(first_hop) = &hop.candidate {
3123 // If this is a first hop we also know if it's announced.
3124 first_hop.details.is_public
3126 // If we sourced it any other way, we double-check the network graph to see if
3127 // there are announced channels between the endpoints. If so, the hop might be
3128 // referring to any of the announced channels, as its `short_channel_id` might be
3129 // an alias, in which case we don't take any chances here.
3130 network_graph.node(&target).map_or(false, |hop_node|
3131 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
3132 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
3136 hops.push(RouteHop {
3137 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
3138 node_features: node_features.clone(),
3139 short_channel_id: hop.candidate.short_channel_id().unwrap(),
3140 channel_features: hop.candidate.features(),
3141 fee_msat: hop.fee_msat,
3142 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
3143 maybe_announced_channel,
3146 let mut final_cltv_delta = final_cltv_expiry_delta;
3147 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
3148 if let Some(blinded_path) = h.candidate.blinded_path() {
3149 final_cltv_delta = h.candidate.cltv_expiry_delta();
3151 hops: blinded_path.blinded_hops.clone(),
3152 blinding_point: blinded_path.blinding_point,
3153 excess_final_cltv_expiry_delta: 0,
3154 final_value_msat: h.fee_msat,
3158 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
3159 // applicable for the previous hop.
3160 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
3161 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
3164 paths.push(Path { hops, blinded_tail });
3166 // Make sure we would never create a route with more paths than we allow.
3167 debug_assert!(paths.len() <= payment_params.max_path_count.into());
3169 if let Some(node_features) = payment_params.payee.node_features() {
3170 for path in paths.iter_mut() {
3171 path.hops.last_mut().unwrap().node_features = node_features.clone();
3175 let route = Route { paths, route_params: Some(route_params.clone()) };
3177 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
3178 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
3179 if route.get_total_fees() > max_total_routing_fee_msat {
3180 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
3181 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
3185 log_info!(logger, "Got route: {}", log_route!(route));
3189 // When an adversarial intermediary node observes a payment, it may be able to infer its
3190 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
3191 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
3192 // payment path by adding a randomized 'shadow route' offset to the final hop.
3193 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
3194 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
3196 let network_channels = network_graph.channels();
3197 let network_nodes = network_graph.nodes();
3199 for path in route.paths.iter_mut() {
3200 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
3202 // Remember the last three nodes of the random walk and avoid looping back on them.
3203 // Init with the last three nodes from the actual path, if possible.
3204 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
3205 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
3206 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
3208 // Choose the last publicly known node as the starting point for the random walk.
3209 let mut cur_hop: Option<NodeId> = None;
3210 let mut path_nonce = [0u8; 12];
3211 if let Some(starting_hop) = path.hops.iter().rev()
3212 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
3213 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
3214 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
3217 // Init PRNG with the path-dependant nonce, which is static for private paths.
3218 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
3219 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
3221 // Pick a random path length in [1 .. 3]
3222 prng.process_in_place(&mut random_path_bytes);
3223 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
3225 for random_hop in 0..random_walk_length {
3226 // If we don't find a suitable offset in the public network graph, we default to
3227 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3228 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
3230 if let Some(cur_node_id) = cur_hop {
3231 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
3232 // Randomly choose the next unvisited hop.
3233 prng.process_in_place(&mut random_path_bytes);
3234 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
3235 .checked_rem(cur_node.channels.len())
3236 .and_then(|index| cur_node.channels.get(index))
3237 .and_then(|id| network_channels.get(id)) {
3238 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
3239 if !nodes_to_avoid.iter().any(|x| x == next_id) {
3240 nodes_to_avoid[random_hop] = *next_id;
3241 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
3242 cur_hop = Some(*next_id);
3249 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
3250 .checked_add(random_hop_offset)
3251 .unwrap_or(shadow_ctlv_expiry_delta_offset);
3254 // Limit the total offset to reduce the worst-case locked liquidity timevalue
3255 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
3256 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
3258 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
3259 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3260 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
3261 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
3262 max_path_offset = cmp::max(
3263 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
3264 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
3265 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
3267 // Add 'shadow' CLTV offset to the final hop
3268 if let Some(tail) = path.blinded_tail.as_mut() {
3269 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
3270 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
3272 if let Some(last_hop) = path.hops.last_mut() {
3273 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
3274 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
3279 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
3280 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
3282 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
3283 pub fn build_route_from_hops<L: Deref, GL: Deref>(
3284 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3285 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
3286 ) -> Result<Route, LightningError>
3287 where L::Target: Logger, GL::Target: Logger {
3288 let graph_lock = network_graph.read_only();
3289 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
3290 &graph_lock, logger, random_seed_bytes)?;
3291 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
3295 fn build_route_from_hops_internal<L: Deref>(
3296 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3297 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
3298 ) -> Result<Route, LightningError> where L::Target: Logger {
3301 our_node_id: NodeId,
3302 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
3305 impl ScoreLookUp for HopScorer {
3306 type ScoreParams = ();
3307 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
3308 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
3310 let mut cur_id = self.our_node_id;
3311 for i in 0..self.hop_ids.len() {
3312 if let Some(next_id) = self.hop_ids[i] {
3313 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
3325 impl<'a> Writeable for HopScorer {
3327 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
3332 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
3333 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
3336 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
3337 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
3338 for i in 0..hops.len() {
3339 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
3342 let scorer = HopScorer { our_node_id, hop_ids };
3344 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
3349 use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode};
3350 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
3351 use crate::routing::utxo::UtxoResult;
3352 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
3353 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
3354 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop, PublicHopCandidate};
3355 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
3356 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
3357 use crate::chain::transaction::OutPoint;
3358 use crate::ln::channel_state::{ChannelCounterparty, ChannelDetails, ChannelShutdownState};
3359 use crate::ln::types::ChannelId;
3360 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
3361 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
3362 use crate::ln::channelmanager;
3363 use crate::offers::invoice::BlindedPayInfo;
3364 use crate::util::config::UserConfig;
3365 use crate::util::test_utils as ln_test_utils;
3366 use crate::crypto::chacha20::ChaCha20;
3367 use crate::util::ser::{Readable, Writeable};
3369 use crate::util::ser::Writer;
3371 use bitcoin::amount::Amount;
3372 use bitcoin::hashes::Hash;
3373 use bitcoin::network::Network;
3374 use bitcoin::blockdata::constants::ChainHash;
3375 use bitcoin::blockdata::script::Builder;
3376 use bitcoin::blockdata::opcodes;
3377 use bitcoin::blockdata::transaction::TxOut;
3378 use bitcoin::hashes::hex::FromHex;
3379 use bitcoin::secp256k1::{PublicKey,SecretKey};
3380 use bitcoin::secp256k1::Secp256k1;
3382 use crate::io::Cursor;
3383 use crate::prelude::*;
3384 use crate::sync::Arc;
3386 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3387 features: InitFeatures, outbound_capacity_msat: u64) -> ChannelDetails {
3389 channel_id: ChannelId::new_zero(),
3390 counterparty: ChannelCounterparty {
3393 unspendable_punishment_reserve: 0,
3394 forwarding_info: None,
3395 outbound_htlc_minimum_msat: None,
3396 outbound_htlc_maximum_msat: None,
3398 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3401 outbound_scid_alias: None,
3402 inbound_scid_alias: None,
3403 channel_value_satoshis: 0,
3406 outbound_capacity_msat,
3407 next_outbound_htlc_limit_msat: outbound_capacity_msat,
3408 next_outbound_htlc_minimum_msat: 0,
3409 inbound_capacity_msat: 42,
3410 unspendable_punishment_reserve: None,
3411 confirmations_required: None,
3412 confirmations: None,
3413 force_close_spend_delay: None,
3414 is_outbound: true, is_channel_ready: true,
3415 is_usable: true, is_public: true,
3416 inbound_htlc_minimum_msat: None,
3417 inbound_htlc_maximum_msat: None,
3419 feerate_sat_per_1000_weight: None,
3420 channel_shutdown_state: Some(ChannelShutdownState::NotShuttingDown),
3421 pending_inbound_htlcs: Vec::new(),
3422 pending_outbound_htlcs: Vec::new(),
3427 fn simple_route_test() {
3428 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3429 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3430 let mut payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3431 let scorer = ln_test_utils::TestScorer::new();
3432 let random_seed_bytes = [42; 32];
3434 // Simple route to 2 via 1
3436 let route_params = RouteParameters::from_payment_params_and_value(
3437 payment_params.clone(), 0);
3438 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3439 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3440 &Default::default(), &random_seed_bytes) {
3441 assert_eq!(err, "Cannot send a payment of 0 msat");
3442 } else { panic!(); }
3444 payment_params.max_path_length = 2;
3445 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3446 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3447 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3448 assert_eq!(route.paths[0].hops.len(), 2);
3450 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3451 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3452 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3453 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3454 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3455 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3457 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3458 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3459 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3460 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3461 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3462 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3464 route_params.payment_params.max_path_length = 1;
3465 get_route(&our_id, &route_params, &network_graph.read_only(), None,
3466 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap_err();
3470 fn invalid_first_hop_test() {
3471 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3472 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3473 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3474 let scorer = ln_test_utils::TestScorer::new();
3475 let random_seed_bytes = [42; 32];
3477 // Simple route to 2 via 1
3479 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3481 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3482 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3483 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3484 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3485 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3486 } else { panic!(); }
3488 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3489 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3490 assert_eq!(route.paths[0].hops.len(), 2);
3494 fn htlc_minimum_test() {
3495 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3496 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3497 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3498 let scorer = ln_test_utils::TestScorer::new();
3499 let random_seed_bytes = [42; 32];
3501 // Simple route to 2 via 1
3503 // Disable other paths
3504 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3505 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3506 short_channel_id: 12,
3508 flags: 2, // to disable
3509 cltv_expiry_delta: 0,
3510 htlc_minimum_msat: 0,
3511 htlc_maximum_msat: MAX_VALUE_MSAT,
3513 fee_proportional_millionths: 0,
3514 excess_data: Vec::new()
3516 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3517 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3518 short_channel_id: 3,
3520 flags: 2, // to disable
3521 cltv_expiry_delta: 0,
3522 htlc_minimum_msat: 0,
3523 htlc_maximum_msat: MAX_VALUE_MSAT,
3525 fee_proportional_millionths: 0,
3526 excess_data: Vec::new()
3528 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3529 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3530 short_channel_id: 13,
3532 flags: 2, // to disable
3533 cltv_expiry_delta: 0,
3534 htlc_minimum_msat: 0,
3535 htlc_maximum_msat: MAX_VALUE_MSAT,
3537 fee_proportional_millionths: 0,
3538 excess_data: Vec::new()
3540 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3541 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3542 short_channel_id: 6,
3544 flags: 2, // to disable
3545 cltv_expiry_delta: 0,
3546 htlc_minimum_msat: 0,
3547 htlc_maximum_msat: MAX_VALUE_MSAT,
3549 fee_proportional_millionths: 0,
3550 excess_data: Vec::new()
3552 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3553 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3554 short_channel_id: 7,
3556 flags: 2, // to disable
3557 cltv_expiry_delta: 0,
3558 htlc_minimum_msat: 0,
3559 htlc_maximum_msat: MAX_VALUE_MSAT,
3561 fee_proportional_millionths: 0,
3562 excess_data: Vec::new()
3565 // Check against amount_to_transfer_over_msat.
3566 // Set minimal HTLC of 200_000_000 msat.
3567 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3568 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3569 short_channel_id: 2,
3572 cltv_expiry_delta: 0,
3573 htlc_minimum_msat: 200_000_000,
3574 htlc_maximum_msat: MAX_VALUE_MSAT,
3576 fee_proportional_millionths: 0,
3577 excess_data: Vec::new()
3580 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3582 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3583 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3584 short_channel_id: 4,
3587 cltv_expiry_delta: 0,
3588 htlc_minimum_msat: 0,
3589 htlc_maximum_msat: 199_999_999,
3591 fee_proportional_millionths: 0,
3592 excess_data: Vec::new()
3595 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3596 let route_params = RouteParameters::from_payment_params_and_value(
3597 payment_params, 199_999_999);
3598 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3599 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3600 &Default::default(), &random_seed_bytes) {
3601 assert_eq!(err, "Failed to find a path to the given destination");
3602 } else { panic!(); }
3604 // Lift the restriction on the first hop.
3605 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3606 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3607 short_channel_id: 2,
3610 cltv_expiry_delta: 0,
3611 htlc_minimum_msat: 0,
3612 htlc_maximum_msat: MAX_VALUE_MSAT,
3614 fee_proportional_millionths: 0,
3615 excess_data: Vec::new()
3618 // A payment above the minimum should pass
3619 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3620 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3621 assert_eq!(route.paths[0].hops.len(), 2);
3625 fn htlc_minimum_overpay_test() {
3626 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3627 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3628 let config = UserConfig::default();
3629 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3630 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3632 let scorer = ln_test_utils::TestScorer::new();
3633 let random_seed_bytes = [42; 32];
3635 // A route to node#2 via two paths.
3636 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3637 // Thus, they can't send 60 without overpaying.
3638 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3639 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3640 short_channel_id: 2,
3643 cltv_expiry_delta: 0,
3644 htlc_minimum_msat: 35_000,
3645 htlc_maximum_msat: 40_000,
3647 fee_proportional_millionths: 0,
3648 excess_data: Vec::new()
3650 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3651 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3652 short_channel_id: 12,
3655 cltv_expiry_delta: 0,
3656 htlc_minimum_msat: 35_000,
3657 htlc_maximum_msat: 40_000,
3659 fee_proportional_millionths: 0,
3660 excess_data: Vec::new()
3664 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3665 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3666 short_channel_id: 13,
3669 cltv_expiry_delta: 0,
3670 htlc_minimum_msat: 0,
3671 htlc_maximum_msat: MAX_VALUE_MSAT,
3673 fee_proportional_millionths: 0,
3674 excess_data: Vec::new()
3676 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3677 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3678 short_channel_id: 4,
3681 cltv_expiry_delta: 0,
3682 htlc_minimum_msat: 0,
3683 htlc_maximum_msat: MAX_VALUE_MSAT,
3685 fee_proportional_millionths: 0,
3686 excess_data: Vec::new()
3689 // Disable other paths
3690 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3691 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3692 short_channel_id: 1,
3694 flags: 2, // to disable
3695 cltv_expiry_delta: 0,
3696 htlc_minimum_msat: 0,
3697 htlc_maximum_msat: MAX_VALUE_MSAT,
3699 fee_proportional_millionths: 0,
3700 excess_data: Vec::new()
3703 let mut route_params = RouteParameters::from_payment_params_and_value(
3704 payment_params.clone(), 60_000);
3705 route_params.max_total_routing_fee_msat = Some(15_000);
3706 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3707 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3708 // Overpay fees to hit htlc_minimum_msat.
3709 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3710 // TODO: this could be better balanced to overpay 10k and not 15k.
3711 assert_eq!(overpaid_fees, 15_000);
3713 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3714 // while taking even more fee to match htlc_minimum_msat.
3715 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3716 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3717 short_channel_id: 12,
3720 cltv_expiry_delta: 0,
3721 htlc_minimum_msat: 65_000,
3722 htlc_maximum_msat: 80_000,
3724 fee_proportional_millionths: 0,
3725 excess_data: Vec::new()
3727 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3728 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3729 short_channel_id: 2,
3732 cltv_expiry_delta: 0,
3733 htlc_minimum_msat: 0,
3734 htlc_maximum_msat: MAX_VALUE_MSAT,
3736 fee_proportional_millionths: 0,
3737 excess_data: Vec::new()
3739 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3740 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3741 short_channel_id: 4,
3744 cltv_expiry_delta: 0,
3745 htlc_minimum_msat: 0,
3746 htlc_maximum_msat: MAX_VALUE_MSAT,
3748 fee_proportional_millionths: 100_000,
3749 excess_data: Vec::new()
3752 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3753 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3754 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3755 assert_eq!(route.paths.len(), 1);
3756 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3757 let fees = route.paths[0].hops[0].fee_msat;
3758 assert_eq!(fees, 5_000);
3760 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3761 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3762 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3763 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3764 // the other channel.
3765 assert_eq!(route.paths.len(), 1);
3766 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3767 let fees = route.paths[0].hops[0].fee_msat;
3768 assert_eq!(fees, 5_000);
3772 fn htlc_minimum_recipient_overpay_test() {
3773 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3774 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3775 let config = UserConfig::default();
3776 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3777 let scorer = ln_test_utils::TestScorer::new();
3778 let random_seed_bytes = [42; 32];
3780 // Route to node2 over a single path which requires overpaying the recipient themselves.
3782 // First disable all paths except the us -> node1 -> node2 path
3783 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3784 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3785 short_channel_id: 13,
3788 cltv_expiry_delta: 0,
3789 htlc_minimum_msat: 0,
3790 htlc_maximum_msat: 0,
3792 fee_proportional_millionths: 0,
3793 excess_data: Vec::new()
3796 // Set channel 4 to free but with a high htlc_minimum_msat
3797 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3798 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3799 short_channel_id: 4,
3802 cltv_expiry_delta: 0,
3803 htlc_minimum_msat: 15_000,
3804 htlc_maximum_msat: MAX_VALUE_MSAT,
3806 fee_proportional_millionths: 0,
3807 excess_data: Vec::new()
3810 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3811 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3812 // what we try to find a route for, so this test only just happens to work out to exactly
3814 let mut route_params = RouteParameters::from_payment_params_and_value(
3815 payment_params.clone(), 5_000);
3816 route_params.max_total_routing_fee_msat = Some(9_999);
3817 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3818 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3819 &Default::default(), &random_seed_bytes) {
3820 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3821 } else { panic!(); }
3823 let mut route_params = RouteParameters::from_payment_params_and_value(
3824 payment_params.clone(), 5_000);
3825 route_params.max_total_routing_fee_msat = Some(10_000);
3826 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3827 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3828 assert_eq!(route.get_total_fees(), 10_000);
3832 fn disable_channels_test() {
3833 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3834 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3835 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3836 let scorer = ln_test_utils::TestScorer::new();
3837 let random_seed_bytes = [42; 32];
3839 // // Disable channels 4 and 12 by flags=2
3840 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3841 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3842 short_channel_id: 4,
3844 flags: 2, // to disable
3845 cltv_expiry_delta: 0,
3846 htlc_minimum_msat: 0,
3847 htlc_maximum_msat: MAX_VALUE_MSAT,
3849 fee_proportional_millionths: 0,
3850 excess_data: Vec::new()
3852 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3853 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3854 short_channel_id: 12,
3856 flags: 2, // to disable
3857 cltv_expiry_delta: 0,
3858 htlc_minimum_msat: 0,
3859 htlc_maximum_msat: MAX_VALUE_MSAT,
3861 fee_proportional_millionths: 0,
3862 excess_data: Vec::new()
3865 // If all the channels require some features we don't understand, route should fail
3866 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3867 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3868 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3869 &Default::default(), &random_seed_bytes) {
3870 assert_eq!(err, "Failed to find a path to the given destination");
3871 } else { panic!(); }
3873 // If we specify a channel to node7, that overrides our local channel view and that gets used
3874 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3875 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3876 route_params.payment_params.max_path_length = 2;
3877 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3878 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3879 &Default::default(), &random_seed_bytes).unwrap();
3880 assert_eq!(route.paths[0].hops.len(), 2);
3882 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3883 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3884 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3885 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3886 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3887 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3889 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3890 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3891 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3892 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3893 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3894 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3898 fn disable_node_test() {
3899 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3900 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3901 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3902 let scorer = ln_test_utils::TestScorer::new();
3903 let random_seed_bytes = [42; 32];
3905 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3906 let mut unknown_features = NodeFeatures::empty();
3907 unknown_features.set_unknown_feature_required();
3908 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3909 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3910 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3912 // If all nodes require some features we don't understand, route should fail
3913 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3914 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3915 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3916 &Default::default(), &random_seed_bytes) {
3917 assert_eq!(err, "Failed to find a path to the given destination");
3918 } else { panic!(); }
3920 // If we specify a channel to node7, that overrides our local channel view and that gets used
3921 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3922 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3923 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3924 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3925 &Default::default(), &random_seed_bytes).unwrap();
3926 assert_eq!(route.paths[0].hops.len(), 2);
3928 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3929 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3930 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3931 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3932 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3933 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3935 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3936 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3937 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3938 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3939 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3940 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3942 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3943 // naively) assume that the user checked the feature bits on the invoice, which override
3944 // the node_announcement.
3948 fn our_chans_test() {
3949 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3950 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3951 let scorer = ln_test_utils::TestScorer::new();
3952 let random_seed_bytes = [42; 32];
3954 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3955 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3956 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3957 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3958 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3959 assert_eq!(route.paths[0].hops.len(), 3);
3961 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3962 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3963 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3964 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3965 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3966 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3968 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3969 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3970 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3971 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3972 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3973 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3975 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3976 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3977 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3978 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3979 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3980 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3982 // If we specify a channel to node7, that overrides our local channel view and that gets used
3983 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3984 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3985 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3986 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3987 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3988 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3989 &Default::default(), &random_seed_bytes).unwrap();
3990 assert_eq!(route.paths[0].hops.len(), 2);
3992 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3993 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3994 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3995 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3996 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3997 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3999 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4000 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
4001 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4002 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4003 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4004 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
4007 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4008 let zero_fees = RoutingFees {
4010 proportional_millionths: 0,
4012 vec![RouteHint(vec![RouteHintHop {
4013 src_node_id: nodes[3],
4014 short_channel_id: 8,
4016 cltv_expiry_delta: (8 << 4) | 1,
4017 htlc_minimum_msat: None,
4018 htlc_maximum_msat: None,
4020 ]), RouteHint(vec![RouteHintHop {
4021 src_node_id: nodes[4],
4022 short_channel_id: 9,
4025 proportional_millionths: 0,
4027 cltv_expiry_delta: (9 << 4) | 1,
4028 htlc_minimum_msat: None,
4029 htlc_maximum_msat: None,
4030 }]), RouteHint(vec![RouteHintHop {
4031 src_node_id: nodes[5],
4032 short_channel_id: 10,
4034 cltv_expiry_delta: (10 << 4) | 1,
4035 htlc_minimum_msat: None,
4036 htlc_maximum_msat: None,
4040 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4041 let zero_fees = RoutingFees {
4043 proportional_millionths: 0,
4045 vec![RouteHint(vec![RouteHintHop {
4046 src_node_id: nodes[2],
4047 short_channel_id: 5,
4050 proportional_millionths: 0,
4052 cltv_expiry_delta: (5 << 4) | 1,
4053 htlc_minimum_msat: None,
4054 htlc_maximum_msat: None,
4056 src_node_id: nodes[3],
4057 short_channel_id: 8,
4059 cltv_expiry_delta: (8 << 4) | 1,
4060 htlc_minimum_msat: None,
4061 htlc_maximum_msat: None,
4063 ]), RouteHint(vec![RouteHintHop {
4064 src_node_id: nodes[4],
4065 short_channel_id: 9,
4068 proportional_millionths: 0,
4070 cltv_expiry_delta: (9 << 4) | 1,
4071 htlc_minimum_msat: None,
4072 htlc_maximum_msat: None,
4073 }]), RouteHint(vec![RouteHintHop {
4074 src_node_id: nodes[5],
4075 short_channel_id: 10,
4077 cltv_expiry_delta: (10 << 4) | 1,
4078 htlc_minimum_msat: None,
4079 htlc_maximum_msat: None,
4084 fn partial_route_hint_test() {
4085 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4086 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4087 let scorer = ln_test_utils::TestScorer::new();
4088 let random_seed_bytes = [42; 32];
4090 // Simple test across 2, 3, 5, and 4 via a last_hop channel
4091 // Tests the behaviour when the RouteHint contains a suboptimal hop.
4092 // RouteHint may be partially used by the algo to build the best path.
4094 // First check that last hop can't have its source as the payee.
4095 let invalid_last_hop = RouteHint(vec![RouteHintHop {
4096 src_node_id: nodes[6],
4097 short_channel_id: 8,
4100 proportional_millionths: 0,
4102 cltv_expiry_delta: (8 << 4) | 1,
4103 htlc_minimum_msat: None,
4104 htlc_maximum_msat: None,
4107 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
4108 invalid_last_hops.push(invalid_last_hop);
4110 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4111 .with_route_hints(invalid_last_hops).unwrap();
4112 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4113 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
4114 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
4115 &Default::default(), &random_seed_bytes) {
4116 assert_eq!(err, "Route hint cannot have the payee as the source.");
4117 } else { panic!(); }
4120 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4121 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
4122 payment_params.max_path_length = 5;
4123 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4124 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4125 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4126 assert_eq!(route.paths[0].hops.len(), 5);
4128 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4129 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4130 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4131 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4132 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4133 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4135 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4136 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4137 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4138 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4139 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4140 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4142 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4143 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4144 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4145 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4146 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4147 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4149 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4150 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4151 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4152 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4153 // If we have a peer in the node map, we'll use their features here since we don't have
4154 // a way of figuring out their features from the invoice:
4155 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4156 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4158 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4159 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4160 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4161 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4162 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4163 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4166 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4167 let zero_fees = RoutingFees {
4169 proportional_millionths: 0,
4171 vec![RouteHint(vec![RouteHintHop {
4172 src_node_id: nodes[3],
4173 short_channel_id: 8,
4175 cltv_expiry_delta: (8 << 4) | 1,
4176 htlc_minimum_msat: None,
4177 htlc_maximum_msat: None,
4178 }]), RouteHint(vec![
4180 ]), RouteHint(vec![RouteHintHop {
4181 src_node_id: nodes[5],
4182 short_channel_id: 10,
4184 cltv_expiry_delta: (10 << 4) | 1,
4185 htlc_minimum_msat: None,
4186 htlc_maximum_msat: None,
4191 fn ignores_empty_last_hops_test() {
4192 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4193 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4194 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
4195 let scorer = ln_test_utils::TestScorer::new();
4196 let random_seed_bytes = [42; 32];
4198 // Test handling of an empty RouteHint passed in Invoice.
4199 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4200 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4201 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4202 assert_eq!(route.paths[0].hops.len(), 5);
4204 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4205 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4206 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4207 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4208 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4209 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4211 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4212 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4213 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4214 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4215 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4216 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4218 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4219 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4220 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4221 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4222 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4223 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4225 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4226 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4227 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4228 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4229 // If we have a peer in the node map, we'll use their features here since we don't have
4230 // a way of figuring out their features from the invoice:
4231 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4232 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4234 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4235 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4236 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4237 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4238 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4239 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4242 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
4244 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
4245 let zero_fees = RoutingFees {
4247 proportional_millionths: 0,
4249 vec![RouteHint(vec![RouteHintHop {
4250 src_node_id: hint_hops[0],
4251 short_channel_id: 0xff00,
4254 proportional_millionths: 0,
4256 cltv_expiry_delta: (5 << 4) | 1,
4257 htlc_minimum_msat: None,
4258 htlc_maximum_msat: None,
4260 src_node_id: hint_hops[1],
4261 short_channel_id: 0xff01,
4263 cltv_expiry_delta: (8 << 4) | 1,
4264 htlc_minimum_msat: None,
4265 htlc_maximum_msat: None,
4270 fn multi_hint_last_hops_test() {
4271 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4272 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4273 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
4274 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4275 let scorer = ln_test_utils::TestScorer::new();
4276 let random_seed_bytes = [42; 32];
4278 // Test through channels 2, 3, 0xff00, 0xff01.
4279 // Test shows that multi-hop route hints are considered and factored correctly into the
4282 // Disabling channels 6 & 7 by flags=2
4283 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4284 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4285 short_channel_id: 6,
4287 flags: 2, // to disable
4288 cltv_expiry_delta: 0,
4289 htlc_minimum_msat: 0,
4290 htlc_maximum_msat: MAX_VALUE_MSAT,
4292 fee_proportional_millionths: 0,
4293 excess_data: Vec::new()
4295 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4296 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4297 short_channel_id: 7,
4299 flags: 2, // to disable
4300 cltv_expiry_delta: 0,
4301 htlc_minimum_msat: 0,
4302 htlc_maximum_msat: MAX_VALUE_MSAT,
4304 fee_proportional_millionths: 0,
4305 excess_data: Vec::new()
4308 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4309 route_params.payment_params.max_path_length = 4;
4310 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4311 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4312 assert_eq!(route.paths[0].hops.len(), 4);
4314 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4315 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4316 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4317 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4318 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4319 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4321 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4322 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4323 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4324 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4325 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4326 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4328 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4329 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4330 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4331 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4332 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4333 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4335 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4336 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4337 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4338 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4339 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4340 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4341 route_params.payment_params.max_path_length = 3;
4342 get_route(&our_id, &route_params, &network_graph.read_only(), None,
4343 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap_err();
4347 fn private_multi_hint_last_hops_test() {
4348 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4349 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4351 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4352 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4354 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4355 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4356 let scorer = ln_test_utils::TestScorer::new();
4357 // Test through channels 2, 3, 0xff00, 0xff01.
4358 // Test shows that multiple hop hints are considered.
4360 // Disabling channels 6 & 7 by flags=2
4361 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4362 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4363 short_channel_id: 6,
4365 flags: 2, // to disable
4366 cltv_expiry_delta: 0,
4367 htlc_minimum_msat: 0,
4368 htlc_maximum_msat: MAX_VALUE_MSAT,
4370 fee_proportional_millionths: 0,
4371 excess_data: Vec::new()
4373 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4374 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4375 short_channel_id: 7,
4377 flags: 2, // to disable
4378 cltv_expiry_delta: 0,
4379 htlc_minimum_msat: 0,
4380 htlc_maximum_msat: MAX_VALUE_MSAT,
4382 fee_proportional_millionths: 0,
4383 excess_data: Vec::new()
4386 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4387 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4388 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4389 assert_eq!(route.paths[0].hops.len(), 4);
4391 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4392 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4393 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4394 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4395 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4396 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4398 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4399 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4400 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4401 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4402 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4403 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4405 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4406 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4407 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4408 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4409 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4410 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4412 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4413 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4414 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4415 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4416 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4417 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4420 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4421 let zero_fees = RoutingFees {
4423 proportional_millionths: 0,
4425 vec![RouteHint(vec![RouteHintHop {
4426 src_node_id: nodes[4],
4427 short_channel_id: 11,
4429 cltv_expiry_delta: (11 << 4) | 1,
4430 htlc_minimum_msat: None,
4431 htlc_maximum_msat: None,
4433 src_node_id: nodes[3],
4434 short_channel_id: 8,
4436 cltv_expiry_delta: (8 << 4) | 1,
4437 htlc_minimum_msat: None,
4438 htlc_maximum_msat: None,
4439 }]), RouteHint(vec![RouteHintHop {
4440 src_node_id: nodes[4],
4441 short_channel_id: 9,
4444 proportional_millionths: 0,
4446 cltv_expiry_delta: (9 << 4) | 1,
4447 htlc_minimum_msat: None,
4448 htlc_maximum_msat: None,
4449 }]), RouteHint(vec![RouteHintHop {
4450 src_node_id: nodes[5],
4451 short_channel_id: 10,
4453 cltv_expiry_delta: (10 << 4) | 1,
4454 htlc_minimum_msat: None,
4455 htlc_maximum_msat: None,
4460 fn last_hops_with_public_channel_test() {
4461 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4462 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4463 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4464 let scorer = ln_test_utils::TestScorer::new();
4465 let random_seed_bytes = [42; 32];
4467 // This test shows that public routes can be present in the invoice
4468 // which would be handled in the same manner.
4470 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4471 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4472 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4473 assert_eq!(route.paths[0].hops.len(), 5);
4475 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4476 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4477 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4478 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4479 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4480 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4482 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4483 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4484 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4485 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4486 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4487 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4489 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4490 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4491 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4492 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4493 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4494 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4496 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4497 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4498 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4499 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4500 // If we have a peer in the node map, we'll use their features here since we don't have
4501 // a way of figuring out their features from the invoice:
4502 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4503 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4505 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4506 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4507 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4508 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4509 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4510 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4514 fn our_chans_last_hop_connect_test() {
4515 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4516 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4517 let scorer = ln_test_utils::TestScorer::new();
4518 let random_seed_bytes = [42; 32];
4520 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4521 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4522 let mut last_hops = last_hops(&nodes);
4523 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4524 .with_route_hints(last_hops.clone()).unwrap();
4525 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4526 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4527 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4528 &Default::default(), &random_seed_bytes).unwrap();
4529 assert_eq!(route.paths[0].hops.len(), 2);
4531 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4532 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4533 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4534 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4535 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4536 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4538 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4539 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4540 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4541 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4542 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4543 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4545 last_hops[0].0[0].fees.base_msat = 1000;
4547 // Revert to via 6 as the fee on 8 goes up
4548 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4549 .with_route_hints(last_hops).unwrap();
4550 let route_params = RouteParameters::from_payment_params_and_value(
4551 payment_params.clone(), 100);
4552 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4553 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4554 assert_eq!(route.paths[0].hops.len(), 4);
4556 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4557 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4558 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4559 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4560 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4561 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4563 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4564 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4565 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4566 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4567 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4568 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4570 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4571 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4572 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4573 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4574 // If we have a peer in the node map, we'll use their features here since we don't have
4575 // a way of figuring out their features from the invoice:
4576 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4577 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4579 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4580 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4581 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4582 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4583 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4584 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4586 // ...but still use 8 for larger payments as 6 has a variable feerate
4587 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4588 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4589 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4590 assert_eq!(route.paths[0].hops.len(), 5);
4592 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4593 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4594 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4595 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4596 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4597 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4599 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4600 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4601 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4602 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4603 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4604 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4606 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4607 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4608 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4609 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4610 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4611 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4613 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4614 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4615 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4616 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4617 // If we have a peer in the node map, we'll use their features here since we don't have
4618 // a way of figuring out their features from the invoice:
4619 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4620 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4622 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4623 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4624 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4625 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4626 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4627 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4630 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> {
4631 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4632 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4633 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4635 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4636 let last_hops = RouteHint(vec![RouteHintHop {
4637 src_node_id: middle_node_id,
4638 short_channel_id: 8,
4641 proportional_millionths: last_hop_fee_prop,
4643 cltv_expiry_delta: (8 << 4) | 1,
4644 htlc_minimum_msat: None,
4645 htlc_maximum_msat: last_hop_htlc_max,
4647 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4648 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4649 let scorer = ln_test_utils::TestScorer::new();
4650 let random_seed_bytes = [42; 32];
4651 let logger = ln_test_utils::TestLogger::new();
4652 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4653 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4654 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4655 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4656 &random_seed_bytes);
4661 fn unannounced_path_test() {
4662 // We should be able to send a payment to a destination without any help of a routing graph
4663 // if we have a channel with a common counterparty that appears in the first and last hop
4665 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4667 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4668 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4669 assert_eq!(route.paths[0].hops.len(), 2);
4671 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4672 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4673 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4674 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4675 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4676 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4678 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4679 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4680 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4681 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4682 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4683 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4687 fn overflow_unannounced_path_test_liquidity_underflow() {
4688 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4689 // the last-hop had a fee which overflowed a u64, we'd panic.
4690 // This was due to us adding the first-hop from us unconditionally, causing us to think
4691 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4692 // In this test, we previously hit a subtraction underflow due to having less available
4693 // liquidity at the last hop than 0.
4694 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());
4698 fn overflow_unannounced_path_test_feerate_overflow() {
4699 // This tests for the same case as above, except instead of hitting a subtraction
4700 // underflow, we hit a case where the fee charged at a hop overflowed.
4701 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());
4705 fn available_amount_while_routing_test() {
4706 // Tests whether we choose the correct available channel amount while routing.
4708 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4709 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4710 let scorer = ln_test_utils::TestScorer::new();
4711 let random_seed_bytes = [42; 32];
4712 let config = UserConfig::default();
4713 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4714 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4717 // We will use a simple single-path route from
4718 // our node to node2 via node0: channels {1, 3}.
4720 // First disable all other paths.
4721 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4722 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4723 short_channel_id: 2,
4726 cltv_expiry_delta: 0,
4727 htlc_minimum_msat: 0,
4728 htlc_maximum_msat: 100_000,
4730 fee_proportional_millionths: 0,
4731 excess_data: Vec::new()
4733 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4734 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4735 short_channel_id: 12,
4738 cltv_expiry_delta: 0,
4739 htlc_minimum_msat: 0,
4740 htlc_maximum_msat: 100_000,
4742 fee_proportional_millionths: 0,
4743 excess_data: Vec::new()
4746 // Make the first channel (#1) very permissive,
4747 // and we will be testing all limits on the second channel.
4748 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4749 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4750 short_channel_id: 1,
4753 cltv_expiry_delta: 0,
4754 htlc_minimum_msat: 0,
4755 htlc_maximum_msat: 1_000_000_000,
4757 fee_proportional_millionths: 0,
4758 excess_data: Vec::new()
4761 // First, let's see if routing works if we have absolutely no idea about the available amount.
4762 // In this case, it should be set to 250_000 sats.
4763 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4764 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4765 short_channel_id: 3,
4768 cltv_expiry_delta: 0,
4769 htlc_minimum_msat: 0,
4770 htlc_maximum_msat: 250_000_000,
4772 fee_proportional_millionths: 0,
4773 excess_data: Vec::new()
4777 // Attempt to route more than available results in a failure.
4778 let route_params = RouteParameters::from_payment_params_and_value(
4779 payment_params.clone(), 250_000_001);
4780 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4781 &our_id, &route_params, &network_graph.read_only(), None,
4782 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4783 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4784 } else { panic!(); }
4788 // Now, attempt to route an exact amount we have should be fine.
4789 let route_params = RouteParameters::from_payment_params_and_value(
4790 payment_params.clone(), 250_000_000);
4791 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4792 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4793 assert_eq!(route.paths.len(), 1);
4794 let path = route.paths.last().unwrap();
4795 assert_eq!(path.hops.len(), 2);
4796 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4797 assert_eq!(path.final_value_msat(), 250_000_000);
4800 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4801 // Disable channel #1 and use another first hop.
4802 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4803 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4804 short_channel_id: 1,
4807 cltv_expiry_delta: 0,
4808 htlc_minimum_msat: 0,
4809 htlc_maximum_msat: 1_000_000_000,
4811 fee_proportional_millionths: 0,
4812 excess_data: Vec::new()
4815 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4816 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4819 // Attempt to route more than available results in a failure.
4820 let route_params = RouteParameters::from_payment_params_and_value(
4821 payment_params.clone(), 200_000_001);
4822 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4823 &our_id, &route_params, &network_graph.read_only(),
4824 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4825 &Default::default(), &random_seed_bytes) {
4826 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4827 } else { panic!(); }
4831 // Now, attempt to route an exact amount we have should be fine.
4832 let route_params = RouteParameters::from_payment_params_and_value(
4833 payment_params.clone(), 200_000_000);
4834 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4835 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4836 &Default::default(), &random_seed_bytes).unwrap();
4837 assert_eq!(route.paths.len(), 1);
4838 let path = route.paths.last().unwrap();
4839 assert_eq!(path.hops.len(), 2);
4840 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4841 assert_eq!(path.final_value_msat(), 200_000_000);
4844 // Enable channel #1 back.
4845 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4846 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4847 short_channel_id: 1,
4850 cltv_expiry_delta: 0,
4851 htlc_minimum_msat: 0,
4852 htlc_maximum_msat: 1_000_000_000,
4854 fee_proportional_millionths: 0,
4855 excess_data: Vec::new()
4859 // Now let's see if routing works if we know only htlc_maximum_msat.
4860 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4861 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4862 short_channel_id: 3,
4865 cltv_expiry_delta: 0,
4866 htlc_minimum_msat: 0,
4867 htlc_maximum_msat: 15_000,
4869 fee_proportional_millionths: 0,
4870 excess_data: Vec::new()
4874 // Attempt to route more than available results in a failure.
4875 let route_params = RouteParameters::from_payment_params_and_value(
4876 payment_params.clone(), 15_001);
4877 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4878 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4879 &scorer, &Default::default(), &random_seed_bytes) {
4880 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4881 } else { panic!(); }
4885 // Now, attempt to route an exact amount we have should be fine.
4886 let route_params = RouteParameters::from_payment_params_and_value(
4887 payment_params.clone(), 15_000);
4888 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4889 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4890 assert_eq!(route.paths.len(), 1);
4891 let path = route.paths.last().unwrap();
4892 assert_eq!(path.hops.len(), 2);
4893 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4894 assert_eq!(path.final_value_msat(), 15_000);
4897 // Now let's see if routing works if we know only capacity from the UTXO.
4899 // We can't change UTXO capacity on the fly, so we'll disable
4900 // the existing channel and add another one with the capacity we need.
4901 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4902 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4903 short_channel_id: 3,
4906 cltv_expiry_delta: 0,
4907 htlc_minimum_msat: 0,
4908 htlc_maximum_msat: MAX_VALUE_MSAT,
4910 fee_proportional_millionths: 0,
4911 excess_data: Vec::new()
4914 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4915 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4916 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4917 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4918 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_p2wsh();
4920 *chain_monitor.utxo_ret.lock().unwrap() =
4921 UtxoResult::Sync(Ok(TxOut { value: Amount::from_sat(15), script_pubkey: good_script.clone() }));
4922 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4924 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4925 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4926 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4927 short_channel_id: 333,
4930 cltv_expiry_delta: (3 << 4) | 1,
4931 htlc_minimum_msat: 0,
4932 htlc_maximum_msat: 15_000,
4934 fee_proportional_millionths: 0,
4935 excess_data: Vec::new()
4937 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4938 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4939 short_channel_id: 333,
4942 cltv_expiry_delta: (3 << 4) | 2,
4943 htlc_minimum_msat: 0,
4944 htlc_maximum_msat: 15_000,
4946 fee_proportional_millionths: 0,
4947 excess_data: Vec::new()
4951 // Attempt to route more than available results in a failure.
4952 let route_params = RouteParameters::from_payment_params_and_value(
4953 payment_params.clone(), 15_001);
4954 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4955 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4956 &scorer, &Default::default(), &random_seed_bytes) {
4957 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4958 } else { panic!(); }
4962 // Now, attempt to route an exact amount we have should be fine.
4963 let route_params = RouteParameters::from_payment_params_and_value(
4964 payment_params.clone(), 15_000);
4965 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4966 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4967 assert_eq!(route.paths.len(), 1);
4968 let path = route.paths.last().unwrap();
4969 assert_eq!(path.hops.len(), 2);
4970 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4971 assert_eq!(path.final_value_msat(), 15_000);
4974 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4975 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4976 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4977 short_channel_id: 333,
4980 cltv_expiry_delta: 0,
4981 htlc_minimum_msat: 0,
4982 htlc_maximum_msat: 10_000,
4984 fee_proportional_millionths: 0,
4985 excess_data: Vec::new()
4989 // Attempt to route more than available results in a failure.
4990 let route_params = RouteParameters::from_payment_params_and_value(
4991 payment_params.clone(), 10_001);
4992 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4993 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4994 &scorer, &Default::default(), &random_seed_bytes) {
4995 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4996 } else { panic!(); }
5000 // Now, attempt to route an exact amount we have should be fine.
5001 let route_params = RouteParameters::from_payment_params_and_value(
5002 payment_params.clone(), 10_000);
5003 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5004 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5005 assert_eq!(route.paths.len(), 1);
5006 let path = route.paths.last().unwrap();
5007 assert_eq!(path.hops.len(), 2);
5008 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5009 assert_eq!(path.final_value_msat(), 10_000);
5014 fn available_liquidity_last_hop_test() {
5015 // Check that available liquidity properly limits the path even when only
5016 // one of the latter hops is limited.
5017 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5018 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5019 let scorer = ln_test_utils::TestScorer::new();
5020 let random_seed_bytes = [42; 32];
5021 let config = UserConfig::default();
5022 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5023 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5026 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5027 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
5028 // Total capacity: 50 sats.
5030 // Disable other potential paths.
5031 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5032 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5033 short_channel_id: 2,
5036 cltv_expiry_delta: 0,
5037 htlc_minimum_msat: 0,
5038 htlc_maximum_msat: 100_000,
5040 fee_proportional_millionths: 0,
5041 excess_data: Vec::new()
5043 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5044 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5045 short_channel_id: 7,
5048 cltv_expiry_delta: 0,
5049 htlc_minimum_msat: 0,
5050 htlc_maximum_msat: 100_000,
5052 fee_proportional_millionths: 0,
5053 excess_data: Vec::new()
5058 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5059 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5060 short_channel_id: 12,
5063 cltv_expiry_delta: 0,
5064 htlc_minimum_msat: 0,
5065 htlc_maximum_msat: 100_000,
5067 fee_proportional_millionths: 0,
5068 excess_data: Vec::new()
5070 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5071 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5072 short_channel_id: 13,
5075 cltv_expiry_delta: 0,
5076 htlc_minimum_msat: 0,
5077 htlc_maximum_msat: 100_000,
5079 fee_proportional_millionths: 0,
5080 excess_data: Vec::new()
5083 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5084 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5085 short_channel_id: 6,
5088 cltv_expiry_delta: 0,
5089 htlc_minimum_msat: 0,
5090 htlc_maximum_msat: 50_000,
5092 fee_proportional_millionths: 0,
5093 excess_data: Vec::new()
5095 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5096 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5097 short_channel_id: 11,
5100 cltv_expiry_delta: 0,
5101 htlc_minimum_msat: 0,
5102 htlc_maximum_msat: 100_000,
5104 fee_proportional_millionths: 0,
5105 excess_data: Vec::new()
5108 // Attempt to route more than available results in a failure.
5109 let route_params = RouteParameters::from_payment_params_and_value(
5110 payment_params.clone(), 60_000);
5111 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5112 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5113 &scorer, &Default::default(), &random_seed_bytes) {
5114 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5115 } else { panic!(); }
5119 // Now, attempt to route 49 sats (just a bit below the capacity).
5120 let route_params = RouteParameters::from_payment_params_and_value(
5121 payment_params.clone(), 49_000);
5122 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5123 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5124 assert_eq!(route.paths.len(), 1);
5125 let mut total_amount_paid_msat = 0;
5126 for path in &route.paths {
5127 assert_eq!(path.hops.len(), 4);
5128 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5129 total_amount_paid_msat += path.final_value_msat();
5131 assert_eq!(total_amount_paid_msat, 49_000);
5135 // Attempt to route an exact amount is also fine
5136 let route_params = RouteParameters::from_payment_params_and_value(
5137 payment_params, 50_000);
5138 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5139 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5140 assert_eq!(route.paths.len(), 1);
5141 let mut total_amount_paid_msat = 0;
5142 for path in &route.paths {
5143 assert_eq!(path.hops.len(), 4);
5144 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5145 total_amount_paid_msat += path.final_value_msat();
5147 assert_eq!(total_amount_paid_msat, 50_000);
5152 fn ignore_fee_first_hop_test() {
5153 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5154 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5155 let scorer = ln_test_utils::TestScorer::new();
5156 let random_seed_bytes = [42; 32];
5157 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5159 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5160 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5161 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5162 short_channel_id: 1,
5165 cltv_expiry_delta: 0,
5166 htlc_minimum_msat: 0,
5167 htlc_maximum_msat: 100_000,
5168 fee_base_msat: 1_000_000,
5169 fee_proportional_millionths: 0,
5170 excess_data: Vec::new()
5172 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5173 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5174 short_channel_id: 3,
5177 cltv_expiry_delta: 0,
5178 htlc_minimum_msat: 0,
5179 htlc_maximum_msat: 50_000,
5181 fee_proportional_millionths: 0,
5182 excess_data: Vec::new()
5186 let route_params = RouteParameters::from_payment_params_and_value(
5187 payment_params, 50_000);
5188 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5189 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5190 assert_eq!(route.paths.len(), 1);
5191 let mut total_amount_paid_msat = 0;
5192 for path in &route.paths {
5193 assert_eq!(path.hops.len(), 2);
5194 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5195 total_amount_paid_msat += path.final_value_msat();
5197 assert_eq!(total_amount_paid_msat, 50_000);
5202 fn simple_mpp_route_test() {
5203 let (secp_ctx, _, _, _, _) = build_graph();
5204 let (_, _, _, nodes) = get_nodes(&secp_ctx);
5205 let config = UserConfig::default();
5206 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5207 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5209 do_simple_mpp_route_test(clear_payment_params);
5211 // MPP to a 1-hop blinded path for nodes[2]
5212 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
5213 let blinded_path = BlindedPath {
5214 introduction_node: IntroductionNode::NodeId(nodes[2]),
5215 blinding_point: ln_test_utils::pubkey(42),
5216 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
5218 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
5220 fee_proportional_millionths: 0,
5221 htlc_minimum_msat: 0,
5222 htlc_maximum_msat: 0,
5223 cltv_expiry_delta: 0,
5224 features: BlindedHopFeatures::empty(),
5226 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
5227 .with_bolt12_features(bolt12_features.clone()).unwrap();
5228 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
5230 // MPP to 3 2-hop blinded paths
5231 let mut blinded_path_node_0 = blinded_path.clone();
5232 blinded_path_node_0.introduction_node = IntroductionNode::NodeId(nodes[0]);
5233 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
5234 let mut node_0_payinfo = blinded_payinfo.clone();
5235 node_0_payinfo.htlc_maximum_msat = 50_000;
5237 let mut blinded_path_node_7 = blinded_path_node_0.clone();
5238 blinded_path_node_7.introduction_node = IntroductionNode::NodeId(nodes[7]);
5239 let mut node_7_payinfo = blinded_payinfo.clone();
5240 node_7_payinfo.htlc_maximum_msat = 60_000;
5242 let mut blinded_path_node_1 = blinded_path_node_0.clone();
5243 blinded_path_node_1.introduction_node = IntroductionNode::NodeId(nodes[1]);
5244 let mut node_1_payinfo = blinded_payinfo.clone();
5245 node_1_payinfo.htlc_maximum_msat = 180_000;
5247 let two_hop_blinded_payment_params = PaymentParameters::blinded(
5249 (node_0_payinfo, blinded_path_node_0),
5250 (node_7_payinfo, blinded_path_node_7),
5251 (node_1_payinfo, blinded_path_node_1)
5253 .with_bolt12_features(bolt12_features).unwrap();
5254 do_simple_mpp_route_test(two_hop_blinded_payment_params);
5258 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
5259 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5260 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5261 let scorer = ln_test_utils::TestScorer::new();
5262 let random_seed_bytes = [42; 32];
5264 // We need a route consisting of 3 paths:
5265 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5266 // To achieve this, the amount being transferred should be around
5267 // the total capacity of these 3 paths.
5269 // First, we set limits on these (previously unlimited) channels.
5270 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
5272 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5273 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5274 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5275 short_channel_id: 1,
5278 cltv_expiry_delta: 0,
5279 htlc_minimum_msat: 0,
5280 htlc_maximum_msat: 100_000,
5282 fee_proportional_millionths: 0,
5283 excess_data: Vec::new()
5285 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5286 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5287 short_channel_id: 3,
5290 cltv_expiry_delta: 0,
5291 htlc_minimum_msat: 0,
5292 htlc_maximum_msat: 50_000,
5294 fee_proportional_millionths: 0,
5295 excess_data: Vec::new()
5298 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
5299 // (total limit 60).
5300 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5301 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5302 short_channel_id: 12,
5305 cltv_expiry_delta: 0,
5306 htlc_minimum_msat: 0,
5307 htlc_maximum_msat: 60_000,
5309 fee_proportional_millionths: 0,
5310 excess_data: Vec::new()
5312 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5313 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5314 short_channel_id: 13,
5317 cltv_expiry_delta: 0,
5318 htlc_minimum_msat: 0,
5319 htlc_maximum_msat: 60_000,
5321 fee_proportional_millionths: 0,
5322 excess_data: Vec::new()
5325 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5326 // (total capacity 180 sats).
5327 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5328 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5329 short_channel_id: 2,
5332 cltv_expiry_delta: 0,
5333 htlc_minimum_msat: 0,
5334 htlc_maximum_msat: 200_000,
5336 fee_proportional_millionths: 0,
5337 excess_data: Vec::new()
5339 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5340 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5341 short_channel_id: 4,
5344 cltv_expiry_delta: 0,
5345 htlc_minimum_msat: 0,
5346 htlc_maximum_msat: 180_000,
5348 fee_proportional_millionths: 0,
5349 excess_data: Vec::new()
5353 // Attempt to route more than available results in a failure.
5354 let route_params = RouteParameters::from_payment_params_and_value(
5355 payment_params.clone(), 300_000);
5356 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5357 &our_id, &route_params, &network_graph.read_only(), None,
5358 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5359 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5360 } else { panic!(); }
5364 // Attempt to route while setting max_path_count to 0 results in a failure.
5365 let zero_payment_params = payment_params.clone().with_max_path_count(0);
5366 let route_params = RouteParameters::from_payment_params_and_value(
5367 zero_payment_params, 100);
5368 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5369 &our_id, &route_params, &network_graph.read_only(), None,
5370 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5371 assert_eq!(err, "Can't find a route with no paths allowed.");
5372 } else { panic!(); }
5376 // Attempt to route while setting max_path_count to 3 results in a failure.
5377 // This is the case because the minimal_value_contribution_msat would require each path
5378 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5379 let fail_payment_params = payment_params.clone().with_max_path_count(3);
5380 let route_params = RouteParameters::from_payment_params_and_value(
5381 fail_payment_params, 250_000);
5382 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5383 &our_id, &route_params, &network_graph.read_only(), None,
5384 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5385 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5386 } else { panic!(); }
5390 // Now, attempt to route 250 sats (just a bit below the capacity).
5391 // Our algorithm should provide us with these 3 paths.
5392 let route_params = RouteParameters::from_payment_params_and_value(
5393 payment_params.clone(), 250_000);
5394 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5395 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5396 assert_eq!(route.paths.len(), 3);
5397 let mut total_amount_paid_msat = 0;
5398 for path in &route.paths {
5399 if let Some(bt) = &path.blinded_tail {
5400 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5402 assert_eq!(path.hops.len(), 2);
5403 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5405 total_amount_paid_msat += path.final_value_msat();
5407 assert_eq!(total_amount_paid_msat, 250_000);
5411 // Attempt to route an exact amount is also fine
5412 let route_params = RouteParameters::from_payment_params_and_value(
5413 payment_params.clone(), 290_000);
5414 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5415 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5416 assert_eq!(route.paths.len(), 3);
5417 let mut total_amount_paid_msat = 0;
5418 for path in &route.paths {
5419 if payment_params.payee.blinded_route_hints().len() != 0 {
5420 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5421 if let Some(bt) = &path.blinded_tail {
5422 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5423 if bt.hops.len() > 1 {
5424 let network_graph = network_graph.read_only();
5426 NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
5427 payment_params.payee.blinded_route_hints().iter()
5428 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5429 .and_then(|(_, p)| p.public_introduction_node_id(&network_graph))
5434 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5437 assert_eq!(path.hops.len(), 2);
5438 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5440 total_amount_paid_msat += path.final_value_msat();
5442 assert_eq!(total_amount_paid_msat, 290_000);
5447 fn long_mpp_route_test() {
5448 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5449 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5450 let scorer = ln_test_utils::TestScorer::new();
5451 let random_seed_bytes = [42; 32];
5452 let config = UserConfig::default();
5453 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5454 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5457 // We need a route consisting of 3 paths:
5458 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5459 // Note that these paths overlap (channels 5, 12, 13).
5460 // We will route 300 sats.
5461 // Each path will have 100 sats capacity, those channels which
5462 // are used twice will have 200 sats capacity.
5464 // Disable other potential paths.
5465 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5466 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5467 short_channel_id: 2,
5470 cltv_expiry_delta: 0,
5471 htlc_minimum_msat: 0,
5472 htlc_maximum_msat: 100_000,
5474 fee_proportional_millionths: 0,
5475 excess_data: Vec::new()
5477 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5478 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5479 short_channel_id: 7,
5482 cltv_expiry_delta: 0,
5483 htlc_minimum_msat: 0,
5484 htlc_maximum_msat: 100_000,
5486 fee_proportional_millionths: 0,
5487 excess_data: Vec::new()
5490 // Path via {node0, node2} is channels {1, 3, 5}.
5491 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5492 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5493 short_channel_id: 1,
5496 cltv_expiry_delta: 0,
5497 htlc_minimum_msat: 0,
5498 htlc_maximum_msat: 100_000,
5500 fee_proportional_millionths: 0,
5501 excess_data: Vec::new()
5503 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5504 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5505 short_channel_id: 3,
5508 cltv_expiry_delta: 0,
5509 htlc_minimum_msat: 0,
5510 htlc_maximum_msat: 100_000,
5512 fee_proportional_millionths: 0,
5513 excess_data: Vec::new()
5516 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5517 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5518 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5519 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5520 short_channel_id: 5,
5523 cltv_expiry_delta: 0,
5524 htlc_minimum_msat: 0,
5525 htlc_maximum_msat: 200_000,
5527 fee_proportional_millionths: 0,
5528 excess_data: Vec::new()
5530 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5531 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5532 short_channel_id: 5,
5534 flags: 3, // disable direction 1
5535 cltv_expiry_delta: 0,
5536 htlc_minimum_msat: 0,
5537 htlc_maximum_msat: 200_000,
5539 fee_proportional_millionths: 0,
5540 excess_data: Vec::new()
5543 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5544 // Add 100 sats to the capacities of {12, 13}, because these channels
5545 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5546 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5547 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5548 short_channel_id: 12,
5551 cltv_expiry_delta: 0,
5552 htlc_minimum_msat: 0,
5553 htlc_maximum_msat: 200_000,
5555 fee_proportional_millionths: 0,
5556 excess_data: Vec::new()
5558 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5559 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5560 short_channel_id: 13,
5563 cltv_expiry_delta: 0,
5564 htlc_minimum_msat: 0,
5565 htlc_maximum_msat: 200_000,
5567 fee_proportional_millionths: 0,
5568 excess_data: Vec::new()
5571 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5572 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5573 short_channel_id: 6,
5576 cltv_expiry_delta: 0,
5577 htlc_minimum_msat: 0,
5578 htlc_maximum_msat: 100_000,
5580 fee_proportional_millionths: 0,
5581 excess_data: Vec::new()
5583 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5584 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5585 short_channel_id: 11,
5588 cltv_expiry_delta: 0,
5589 htlc_minimum_msat: 0,
5590 htlc_maximum_msat: 100_000,
5592 fee_proportional_millionths: 0,
5593 excess_data: Vec::new()
5596 // Path via {node7, node2} is channels {12, 13, 5}.
5597 // We already limited them to 200 sats (they are used twice for 100 sats).
5598 // Nothing to do here.
5601 // Attempt to route more than available results in a failure.
5602 let route_params = RouteParameters::from_payment_params_and_value(
5603 payment_params.clone(), 350_000);
5604 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5605 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5606 &scorer, &Default::default(), &random_seed_bytes) {
5607 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5608 } else { panic!(); }
5612 // Now, attempt to route 300 sats (exact amount we can route).
5613 // Our algorithm should provide us with these 3 paths, 100 sats each.
5614 let route_params = RouteParameters::from_payment_params_and_value(
5615 payment_params, 300_000);
5616 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5617 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5618 assert_eq!(route.paths.len(), 3);
5620 let mut total_amount_paid_msat = 0;
5621 for path in &route.paths {
5622 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5623 total_amount_paid_msat += path.final_value_msat();
5625 assert_eq!(total_amount_paid_msat, 300_000);
5631 fn mpp_cheaper_route_test() {
5632 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5633 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5634 let scorer = ln_test_utils::TestScorer::new();
5635 let random_seed_bytes = [42; 32];
5636 let config = UserConfig::default();
5637 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5638 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5641 // This test checks that if we have two cheaper paths and one more expensive path,
5642 // so that liquidity-wise any 2 of 3 combination is sufficient,
5643 // two cheaper paths will be taken.
5644 // These paths have equal available liquidity.
5646 // We need a combination of 3 paths:
5647 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5648 // Note that these paths overlap (channels 5, 12, 13).
5649 // Each path will have 100 sats capacity, those channels which
5650 // are used twice will have 200 sats capacity.
5652 // Disable other potential paths.
5653 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5654 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5655 short_channel_id: 2,
5658 cltv_expiry_delta: 0,
5659 htlc_minimum_msat: 0,
5660 htlc_maximum_msat: 100_000,
5662 fee_proportional_millionths: 0,
5663 excess_data: Vec::new()
5665 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5666 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5667 short_channel_id: 7,
5670 cltv_expiry_delta: 0,
5671 htlc_minimum_msat: 0,
5672 htlc_maximum_msat: 100_000,
5674 fee_proportional_millionths: 0,
5675 excess_data: Vec::new()
5678 // Path via {node0, node2} is channels {1, 3, 5}.
5679 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5680 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5681 short_channel_id: 1,
5684 cltv_expiry_delta: 0,
5685 htlc_minimum_msat: 0,
5686 htlc_maximum_msat: 100_000,
5688 fee_proportional_millionths: 0,
5689 excess_data: Vec::new()
5691 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5692 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5693 short_channel_id: 3,
5696 cltv_expiry_delta: 0,
5697 htlc_minimum_msat: 0,
5698 htlc_maximum_msat: 100_000,
5700 fee_proportional_millionths: 0,
5701 excess_data: Vec::new()
5704 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5705 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5706 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5707 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5708 short_channel_id: 5,
5711 cltv_expiry_delta: 0,
5712 htlc_minimum_msat: 0,
5713 htlc_maximum_msat: 200_000,
5715 fee_proportional_millionths: 0,
5716 excess_data: Vec::new()
5718 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5719 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5720 short_channel_id: 5,
5722 flags: 3, // disable direction 1
5723 cltv_expiry_delta: 0,
5724 htlc_minimum_msat: 0,
5725 htlc_maximum_msat: 200_000,
5727 fee_proportional_millionths: 0,
5728 excess_data: Vec::new()
5731 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5732 // Add 100 sats to the capacities of {12, 13}, because these channels
5733 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5734 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5735 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5736 short_channel_id: 12,
5739 cltv_expiry_delta: 0,
5740 htlc_minimum_msat: 0,
5741 htlc_maximum_msat: 200_000,
5743 fee_proportional_millionths: 0,
5744 excess_data: Vec::new()
5746 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5747 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5748 short_channel_id: 13,
5751 cltv_expiry_delta: 0,
5752 htlc_minimum_msat: 0,
5753 htlc_maximum_msat: 200_000,
5755 fee_proportional_millionths: 0,
5756 excess_data: Vec::new()
5759 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5760 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5761 short_channel_id: 6,
5764 cltv_expiry_delta: 0,
5765 htlc_minimum_msat: 0,
5766 htlc_maximum_msat: 100_000,
5767 fee_base_msat: 1_000,
5768 fee_proportional_millionths: 0,
5769 excess_data: Vec::new()
5771 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5772 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5773 short_channel_id: 11,
5776 cltv_expiry_delta: 0,
5777 htlc_minimum_msat: 0,
5778 htlc_maximum_msat: 100_000,
5780 fee_proportional_millionths: 0,
5781 excess_data: Vec::new()
5784 // Path via {node7, node2} is channels {12, 13, 5}.
5785 // We already limited them to 200 sats (they are used twice for 100 sats).
5786 // Nothing to do here.
5789 // Now, attempt to route 180 sats.
5790 // Our algorithm should provide us with these 2 paths.
5791 let route_params = RouteParameters::from_payment_params_and_value(
5792 payment_params, 180_000);
5793 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5794 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5795 assert_eq!(route.paths.len(), 2);
5797 let mut total_value_transferred_msat = 0;
5798 let mut total_paid_msat = 0;
5799 for path in &route.paths {
5800 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5801 total_value_transferred_msat += path.final_value_msat();
5802 for hop in &path.hops {
5803 total_paid_msat += hop.fee_msat;
5806 // If we paid fee, this would be higher.
5807 assert_eq!(total_value_transferred_msat, 180_000);
5808 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5809 assert_eq!(total_fees_paid, 0);
5814 fn fees_on_mpp_route_test() {
5815 // This test makes sure that MPP algorithm properly takes into account
5816 // fees charged on the channels, by making the fees impactful:
5817 // if the fee is not properly accounted for, the behavior is different.
5818 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5819 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5820 let scorer = ln_test_utils::TestScorer::new();
5821 let random_seed_bytes = [42; 32];
5822 let config = UserConfig::default();
5823 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5824 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5827 // We need a route consisting of 2 paths:
5828 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5829 // We will route 200 sats, Each path will have 100 sats capacity.
5831 // This test is not particularly stable: e.g.,
5832 // there's a way to route via {node0, node2, node4}.
5833 // It works while pathfinding is deterministic, but can be broken otherwise.
5834 // It's fine to ignore this concern for now.
5836 // Disable other potential paths.
5837 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5838 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5839 short_channel_id: 2,
5842 cltv_expiry_delta: 0,
5843 htlc_minimum_msat: 0,
5844 htlc_maximum_msat: 100_000,
5846 fee_proportional_millionths: 0,
5847 excess_data: Vec::new()
5850 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5851 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5852 short_channel_id: 7,
5855 cltv_expiry_delta: 0,
5856 htlc_minimum_msat: 0,
5857 htlc_maximum_msat: 100_000,
5859 fee_proportional_millionths: 0,
5860 excess_data: Vec::new()
5863 // Path via {node0, node2} is channels {1, 3, 5}.
5864 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5865 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5866 short_channel_id: 1,
5869 cltv_expiry_delta: 0,
5870 htlc_minimum_msat: 0,
5871 htlc_maximum_msat: 100_000,
5873 fee_proportional_millionths: 0,
5874 excess_data: Vec::new()
5876 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5877 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5878 short_channel_id: 3,
5881 cltv_expiry_delta: 0,
5882 htlc_minimum_msat: 0,
5883 htlc_maximum_msat: 100_000,
5885 fee_proportional_millionths: 0,
5886 excess_data: Vec::new()
5889 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5890 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5891 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5892 short_channel_id: 5,
5895 cltv_expiry_delta: 0,
5896 htlc_minimum_msat: 0,
5897 htlc_maximum_msat: 100_000,
5899 fee_proportional_millionths: 0,
5900 excess_data: Vec::new()
5902 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5903 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5904 short_channel_id: 5,
5906 flags: 3, // Disable direction 1
5907 cltv_expiry_delta: 0,
5908 htlc_minimum_msat: 0,
5909 htlc_maximum_msat: 100_000,
5911 fee_proportional_millionths: 0,
5912 excess_data: Vec::new()
5915 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5916 // All channels should be 100 sats capacity. But for the fee experiment,
5917 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5918 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5919 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5920 // so no matter how large are other channels,
5921 // the whole path will be limited by 100 sats with just these 2 conditions:
5922 // - channel 12 capacity is 250 sats
5923 // - fee for channel 6 is 150 sats
5924 // Let's test this by enforcing these 2 conditions and removing other limits.
5925 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5926 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5927 short_channel_id: 12,
5930 cltv_expiry_delta: 0,
5931 htlc_minimum_msat: 0,
5932 htlc_maximum_msat: 250_000,
5934 fee_proportional_millionths: 0,
5935 excess_data: Vec::new()
5937 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5938 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5939 short_channel_id: 13,
5942 cltv_expiry_delta: 0,
5943 htlc_minimum_msat: 0,
5944 htlc_maximum_msat: MAX_VALUE_MSAT,
5946 fee_proportional_millionths: 0,
5947 excess_data: Vec::new()
5950 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5951 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5952 short_channel_id: 6,
5955 cltv_expiry_delta: 0,
5956 htlc_minimum_msat: 0,
5957 htlc_maximum_msat: MAX_VALUE_MSAT,
5958 fee_base_msat: 150_000,
5959 fee_proportional_millionths: 0,
5960 excess_data: Vec::new()
5962 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5963 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5964 short_channel_id: 11,
5967 cltv_expiry_delta: 0,
5968 htlc_minimum_msat: 0,
5969 htlc_maximum_msat: MAX_VALUE_MSAT,
5971 fee_proportional_millionths: 0,
5972 excess_data: Vec::new()
5976 // Attempt to route more than available results in a failure.
5977 let route_params = RouteParameters::from_payment_params_and_value(
5978 payment_params.clone(), 210_000);
5979 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5980 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5981 &scorer, &Default::default(), &random_seed_bytes) {
5982 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5983 } else { panic!(); }
5987 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5988 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5989 max_total_routing_fee_msat: Some(149_999) };
5990 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5991 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5992 &scorer, &Default::default(), &random_seed_bytes) {
5993 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5994 } else { panic!(); }
5998 // Now, attempt to route 200 sats (exact amount we can route).
5999 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
6000 max_total_routing_fee_msat: Some(150_000) };
6001 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6002 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6003 assert_eq!(route.paths.len(), 2);
6005 let mut total_amount_paid_msat = 0;
6006 for path in &route.paths {
6007 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
6008 total_amount_paid_msat += path.final_value_msat();
6010 assert_eq!(total_amount_paid_msat, 200_000);
6011 assert_eq!(route.get_total_fees(), 150_000);
6016 fn mpp_with_last_hops() {
6017 // Previously, if we tried to send an MPP payment to a destination which was only reachable
6018 // via a single last-hop route hint, we'd fail to route if we first collected routes
6019 // totaling close but not quite enough to fund the full payment.
6021 // This was because we considered last-hop hints to have exactly the sought payment amount
6022 // instead of the amount we were trying to collect, needlessly limiting our path searching
6023 // at the very first hop.
6025 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
6026 // criterion to cause us to refuse all routes at the last hop hint which would be considered
6027 // to only have the remaining to-collect amount in available liquidity.
6029 // This bug appeared in production in some specific channel configurations.
6030 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6031 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6032 let scorer = ln_test_utils::TestScorer::new();
6033 let random_seed_bytes = [42; 32];
6034 let config = UserConfig::default();
6035 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
6036 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
6037 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
6038 src_node_id: nodes[2],
6039 short_channel_id: 42,
6040 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
6041 cltv_expiry_delta: 42,
6042 htlc_minimum_msat: None,
6043 htlc_maximum_msat: None,
6044 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
6046 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
6047 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
6048 // would first use the no-fee route and then fail to find a path along the second route as
6049 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
6050 // under 5% of our payment amount.
6051 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6052 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6053 short_channel_id: 1,
6056 cltv_expiry_delta: (5 << 4) | 5,
6057 htlc_minimum_msat: 0,
6058 htlc_maximum_msat: 99_000,
6059 fee_base_msat: u32::max_value(),
6060 fee_proportional_millionths: u32::max_value(),
6061 excess_data: Vec::new()
6063 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6064 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6065 short_channel_id: 2,
6068 cltv_expiry_delta: (5 << 4) | 3,
6069 htlc_minimum_msat: 0,
6070 htlc_maximum_msat: 99_000,
6071 fee_base_msat: u32::max_value(),
6072 fee_proportional_millionths: u32::max_value(),
6073 excess_data: Vec::new()
6075 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6076 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6077 short_channel_id: 4,
6080 cltv_expiry_delta: (4 << 4) | 1,
6081 htlc_minimum_msat: 0,
6082 htlc_maximum_msat: MAX_VALUE_MSAT,
6084 fee_proportional_millionths: 0,
6085 excess_data: Vec::new()
6087 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6088 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6089 short_channel_id: 13,
6091 flags: 0|2, // Channel disabled
6092 cltv_expiry_delta: (13 << 4) | 1,
6093 htlc_minimum_msat: 0,
6094 htlc_maximum_msat: MAX_VALUE_MSAT,
6096 fee_proportional_millionths: 2000000,
6097 excess_data: Vec::new()
6100 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
6102 let route_params = RouteParameters::from_payment_params_and_value(
6103 payment_params, 100_000);
6104 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6105 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6106 assert_eq!(route.paths.len(), 2);
6107 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
6108 // Paths are manually ordered ordered by SCID, so:
6109 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
6110 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
6111 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
6112 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
6113 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
6114 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
6115 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
6116 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
6117 assert_eq!(route.get_total_fees(), 1);
6118 assert_eq!(route.get_total_amount(), 100_000);
6122 fn drop_lowest_channel_mpp_route_test() {
6123 // This test checks that low-capacity channel is dropped when after
6124 // path finding we realize that we found more capacity than we need.
6125 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6126 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6127 let scorer = ln_test_utils::TestScorer::new();
6128 let random_seed_bytes = [42; 32];
6129 let config = UserConfig::default();
6130 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6131 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6133 .with_max_channel_saturation_power_of_half(0);
6135 // We need a route consisting of 3 paths:
6136 // From our node to node2 via node0, node7, node1 (three paths one hop each).
6138 // The first and the second paths should be sufficient, but the third should be
6139 // cheaper, so that we select it but drop later.
6141 // First, we set limits on these (previously unlimited) channels.
6142 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
6144 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
6145 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6146 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6147 short_channel_id: 1,
6150 cltv_expiry_delta: 0,
6151 htlc_minimum_msat: 0,
6152 htlc_maximum_msat: 100_000,
6154 fee_proportional_millionths: 0,
6155 excess_data: Vec::new()
6157 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6158 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6159 short_channel_id: 3,
6162 cltv_expiry_delta: 0,
6163 htlc_minimum_msat: 0,
6164 htlc_maximum_msat: 50_000,
6166 fee_proportional_millionths: 0,
6167 excess_data: Vec::new()
6170 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
6171 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6172 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6173 short_channel_id: 12,
6176 cltv_expiry_delta: 0,
6177 htlc_minimum_msat: 0,
6178 htlc_maximum_msat: 60_000,
6180 fee_proportional_millionths: 0,
6181 excess_data: Vec::new()
6183 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6184 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6185 short_channel_id: 13,
6188 cltv_expiry_delta: 0,
6189 htlc_minimum_msat: 0,
6190 htlc_maximum_msat: 60_000,
6192 fee_proportional_millionths: 0,
6193 excess_data: Vec::new()
6196 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
6197 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6198 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6199 short_channel_id: 2,
6202 cltv_expiry_delta: 0,
6203 htlc_minimum_msat: 0,
6204 htlc_maximum_msat: 20_000,
6206 fee_proportional_millionths: 0,
6207 excess_data: Vec::new()
6209 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6210 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6211 short_channel_id: 4,
6214 cltv_expiry_delta: 0,
6215 htlc_minimum_msat: 0,
6216 htlc_maximum_msat: 20_000,
6218 fee_proportional_millionths: 0,
6219 excess_data: Vec::new()
6223 // Attempt to route more than available results in a failure.
6224 let route_params = RouteParameters::from_payment_params_and_value(
6225 payment_params.clone(), 150_000);
6226 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6227 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6228 &scorer, &Default::default(), &random_seed_bytes) {
6229 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6230 } else { panic!(); }
6234 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
6235 // Our algorithm should provide us with these 3 paths.
6236 let route_params = RouteParameters::from_payment_params_and_value(
6237 payment_params.clone(), 125_000);
6238 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6239 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6240 assert_eq!(route.paths.len(), 3);
6241 let mut total_amount_paid_msat = 0;
6242 for path in &route.paths {
6243 assert_eq!(path.hops.len(), 2);
6244 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6245 total_amount_paid_msat += path.final_value_msat();
6247 assert_eq!(total_amount_paid_msat, 125_000);
6251 // Attempt to route without the last small cheap channel
6252 let route_params = RouteParameters::from_payment_params_and_value(
6253 payment_params, 90_000);
6254 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6255 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6256 assert_eq!(route.paths.len(), 2);
6257 let mut total_amount_paid_msat = 0;
6258 for path in &route.paths {
6259 assert_eq!(path.hops.len(), 2);
6260 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6261 total_amount_paid_msat += path.final_value_msat();
6263 assert_eq!(total_amount_paid_msat, 90_000);
6268 fn min_criteria_consistency() {
6269 // Test that we don't use an inconsistent metric between updating and walking nodes during
6270 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
6271 // was updated with a different criterion from the heap sorting, resulting in loops in
6272 // calculated paths. We test for that specific case here.
6274 // We construct a network that looks like this:
6276 // node2 -1(3)2- node3
6280 // node1 -1(5)2- node4 -1(1)2- node6
6286 // We create a loop on the side of our real path - our destination is node 6, with a
6287 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
6288 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
6289 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
6290 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
6291 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
6292 // "previous hop" being set to node 3, creating a loop in the path.
6293 let secp_ctx = Secp256k1::new();
6294 let logger = Arc::new(ln_test_utils::TestLogger::new());
6295 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6296 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
6297 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6298 let scorer = ln_test_utils::TestScorer::new();
6299 let random_seed_bytes = [42; 32];
6300 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
6302 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
6303 for (key, flags) in [(&our_privkey, 0), (&privkeys[1], 3)] {
6304 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6305 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6306 short_channel_id: 6,
6309 cltv_expiry_delta: (6 << 4) | 0,
6310 htlc_minimum_msat: 0,
6311 htlc_maximum_msat: MAX_VALUE_MSAT,
6313 fee_proportional_millionths: 0,
6314 excess_data: Vec::new()
6317 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
6319 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6320 for (key, flags) in [(&privkeys[1], 0), (&privkeys[4], 3)] {
6321 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6322 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6323 short_channel_id: 5,
6326 cltv_expiry_delta: (5 << 4) | 0,
6327 htlc_minimum_msat: 0,
6328 htlc_maximum_msat: MAX_VALUE_MSAT,
6330 fee_proportional_millionths: 0,
6331 excess_data: Vec::new()
6334 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
6336 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
6337 for (key, flags) in [(&privkeys[4], 0), (&privkeys[3], 3)] {
6338 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6339 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6340 short_channel_id: 4,
6343 cltv_expiry_delta: (4 << 4) | 0,
6344 htlc_minimum_msat: 0,
6345 htlc_maximum_msat: MAX_VALUE_MSAT,
6347 fee_proportional_millionths: 0,
6348 excess_data: Vec::new()
6351 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6353 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6354 for (key, flags) in [(&privkeys[3], 0), (&privkeys[2], 3)] {
6355 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6356 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6357 short_channel_id: 3,
6360 cltv_expiry_delta: (3 << 4) | 0,
6361 htlc_minimum_msat: 0,
6362 htlc_maximum_msat: MAX_VALUE_MSAT,
6364 fee_proportional_millionths: 0,
6365 excess_data: Vec::new()
6368 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6370 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6371 for (key, flags) in [(&privkeys[2], 0), (&privkeys[4], 3)] {
6372 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6373 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6374 short_channel_id: 2,
6377 cltv_expiry_delta: (2 << 4) | 0,
6378 htlc_minimum_msat: 0,
6379 htlc_maximum_msat: MAX_VALUE_MSAT,
6381 fee_proportional_millionths: 0,
6382 excess_data: Vec::new()
6386 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6387 for (key, flags) in [(&privkeys[4], 0), (&privkeys[6], 3)] {
6388 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6389 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6390 short_channel_id: 1,
6393 cltv_expiry_delta: (1 << 4) | 0,
6394 htlc_minimum_msat: 100,
6395 htlc_maximum_msat: MAX_VALUE_MSAT,
6397 fee_proportional_millionths: 0,
6398 excess_data: Vec::new()
6401 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6404 // Now ensure the route flows simply over nodes 1 and 4 to 6.
6405 let route_params = RouteParameters::from_payment_params_and_value(
6406 payment_params, 10_000);
6407 let route = get_route(&our_id, &route_params, &network.read_only(), None,
6408 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6409 assert_eq!(route.paths.len(), 1);
6410 assert_eq!(route.paths[0].hops.len(), 3);
6412 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6413 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6414 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6415 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6416 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6417 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6419 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6420 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6421 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6422 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6423 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6424 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6426 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6427 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6428 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6429 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6430 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6431 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6437 fn exact_fee_liquidity_limit() {
6438 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6439 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6440 // we calculated fees on a higher value, resulting in us ignoring such paths.
6441 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6442 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6443 let scorer = ln_test_utils::TestScorer::new();
6444 let random_seed_bytes = [42; 32];
6445 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6447 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6449 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6450 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6451 short_channel_id: 2,
6454 cltv_expiry_delta: 0,
6455 htlc_minimum_msat: 0,
6456 htlc_maximum_msat: 85_000,
6458 fee_proportional_millionths: 0,
6459 excess_data: Vec::new()
6462 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6463 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6464 short_channel_id: 12,
6467 cltv_expiry_delta: (4 << 4) | 1,
6468 htlc_minimum_msat: 0,
6469 htlc_maximum_msat: 270_000,
6471 fee_proportional_millionths: 1000000,
6472 excess_data: Vec::new()
6476 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6477 // 200% fee charged channel 13 in the 1-to-2 direction.
6478 let mut route_params = RouteParameters::from_payment_params_and_value(
6479 payment_params, 90_000);
6480 route_params.max_total_routing_fee_msat = Some(90_000*2);
6481 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6482 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6483 assert_eq!(route.paths.len(), 1);
6484 assert_eq!(route.paths[0].hops.len(), 2);
6486 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6487 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6488 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6489 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6490 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6491 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6493 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6494 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6495 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6496 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6497 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6498 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6503 fn htlc_max_reduction_below_min() {
6504 // Test that if, while walking the graph, we reduce the value being sent to meet an
6505 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6506 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6507 // resulting in us thinking there is no possible path, even if other paths exist.
6508 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6509 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6510 let scorer = ln_test_utils::TestScorer::new();
6511 let random_seed_bytes = [42; 32];
6512 let config = UserConfig::default();
6513 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6514 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6517 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6518 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6519 // then try to send 90_000.
6520 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6521 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6522 short_channel_id: 2,
6525 cltv_expiry_delta: 0,
6526 htlc_minimum_msat: 0,
6527 htlc_maximum_msat: 80_000,
6529 fee_proportional_millionths: 0,
6530 excess_data: Vec::new()
6532 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6533 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6534 short_channel_id: 4,
6537 cltv_expiry_delta: (4 << 4) | 1,
6538 htlc_minimum_msat: 90_000,
6539 htlc_maximum_msat: MAX_VALUE_MSAT,
6541 fee_proportional_millionths: 0,
6542 excess_data: Vec::new()
6546 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6547 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6548 // expensive) channels 12-13 path.
6549 let mut route_params = RouteParameters::from_payment_params_and_value(
6550 payment_params, 90_000);
6551 route_params.max_total_routing_fee_msat = Some(90_000*2);
6552 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6553 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6554 assert_eq!(route.paths.len(), 1);
6555 assert_eq!(route.paths[0].hops.len(), 2);
6557 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6558 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6559 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6560 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6561 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6562 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6564 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6565 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6566 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6567 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6568 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6569 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6574 fn multiple_direct_first_hops() {
6575 // Previously we'd only ever considered one first hop path per counterparty.
6576 // However, as we don't restrict users to one channel per peer, we really need to support
6577 // looking at all first hop paths.
6578 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6579 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6580 // route over multiple channels with the same first hop.
6581 let secp_ctx = Secp256k1::new();
6582 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6583 let logger = Arc::new(ln_test_utils::TestLogger::new());
6584 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6585 let scorer = ln_test_utils::TestScorer::new();
6586 let config = UserConfig::default();
6587 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6588 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6590 let random_seed_bytes = [42; 32];
6593 let route_params = RouteParameters::from_payment_params_and_value(
6594 payment_params.clone(), 100_000);
6595 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6596 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6597 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6598 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6599 assert_eq!(route.paths.len(), 1);
6600 assert_eq!(route.paths[0].hops.len(), 1);
6602 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6603 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6604 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6607 let route_params = RouteParameters::from_payment_params_and_value(
6608 payment_params.clone(), 100_000);
6609 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6610 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6611 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6612 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6613 assert_eq!(route.paths.len(), 2);
6614 assert_eq!(route.paths[0].hops.len(), 1);
6615 assert_eq!(route.paths[1].hops.len(), 1);
6617 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6618 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6620 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6621 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6623 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6624 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6628 // If we have a bunch of outbound channels to the same node, where most are not
6629 // sufficient to pay the full payment, but one is, we should default to just using the
6630 // one single channel that has sufficient balance, avoiding MPP.
6632 // If we have several options above the 3xpayment value threshold, we should pick the
6633 // smallest of them, avoiding further fragmenting our available outbound balance to
6635 let route_params = RouteParameters::from_payment_params_and_value(
6636 payment_params, 100_000);
6637 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6638 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6639 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6640 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6641 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6642 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6643 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6644 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6645 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6646 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6647 assert_eq!(route.paths.len(), 1);
6648 assert_eq!(route.paths[0].hops.len(), 1);
6650 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6651 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6652 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6657 fn prefers_shorter_route_with_higher_fees() {
6658 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6659 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6660 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6662 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6663 let scorer = ln_test_utils::TestScorer::new();
6664 let random_seed_bytes = [42; 32];
6665 let route_params = RouteParameters::from_payment_params_and_value(
6666 payment_params.clone(), 100);
6667 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6668 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6669 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6671 assert_eq!(route.get_total_fees(), 100);
6672 assert_eq!(route.get_total_amount(), 100);
6673 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6675 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6676 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6677 let scorer = FixedPenaltyScorer::with_penalty(100);
6678 let route_params = RouteParameters::from_payment_params_and_value(
6679 payment_params, 100);
6680 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6681 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6682 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6684 assert_eq!(route.get_total_fees(), 300);
6685 assert_eq!(route.get_total_amount(), 100);
6686 assert_eq!(path, vec![2, 4, 7, 10]);
6689 struct BadChannelScorer {
6690 short_channel_id: u64,
6694 impl Writeable for BadChannelScorer {
6695 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6697 impl ScoreLookUp for BadChannelScorer {
6698 type ScoreParams = ();
6699 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6700 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6704 struct BadNodeScorer {
6709 impl Writeable for BadNodeScorer {
6710 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6713 impl ScoreLookUp for BadNodeScorer {
6714 type ScoreParams = ();
6715 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6716 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6721 fn avoids_routing_through_bad_channels_and_nodes() {
6722 let (secp_ctx, network, _, _, logger) = build_graph();
6723 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6724 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6725 let network_graph = network.read_only();
6727 // A path to nodes[6] exists when no penalties are applied to any channel.
6728 let scorer = ln_test_utils::TestScorer::new();
6729 let random_seed_bytes = [42; 32];
6730 let route_params = RouteParameters::from_payment_params_and_value(
6731 payment_params, 100);
6732 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6733 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6734 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6736 assert_eq!(route.get_total_fees(), 100);
6737 assert_eq!(route.get_total_amount(), 100);
6738 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6740 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6741 let scorer = BadChannelScorer { short_channel_id: 6 };
6742 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6743 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6744 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6746 assert_eq!(route.get_total_fees(), 300);
6747 assert_eq!(route.get_total_amount(), 100);
6748 assert_eq!(path, vec![2, 4, 7, 10]);
6750 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6751 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6752 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6753 &scorer, &Default::default(), &random_seed_bytes) {
6754 Err(LightningError { err, .. } ) => {
6755 assert_eq!(err, "Failed to find a path to the given destination");
6757 Ok(_) => panic!("Expected error"),
6762 fn total_fees_single_path() {
6764 paths: vec![Path { hops: vec![
6766 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6767 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6768 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6771 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6772 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6773 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6776 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6777 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6778 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6780 ], blinded_tail: None }],
6784 assert_eq!(route.get_total_fees(), 250);
6785 assert_eq!(route.get_total_amount(), 225);
6789 fn total_fees_multi_path() {
6791 paths: vec![Path { hops: vec![
6793 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6794 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6795 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6798 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6799 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6800 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6802 ], blinded_tail: None }, Path { hops: vec![
6804 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6805 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6806 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6809 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6810 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6811 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6813 ], blinded_tail: None }],
6817 assert_eq!(route.get_total_fees(), 200);
6818 assert_eq!(route.get_total_amount(), 300);
6822 fn total_empty_route_no_panic() {
6823 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6824 // would both panic if the route was completely empty. We test to ensure they return 0
6825 // here, even though its somewhat nonsensical as a route.
6826 let route = Route { paths: Vec::new(), route_params: None };
6828 assert_eq!(route.get_total_fees(), 0);
6829 assert_eq!(route.get_total_amount(), 0);
6833 fn limits_total_cltv_delta() {
6834 let (secp_ctx, network, _, _, logger) = build_graph();
6835 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6836 let network_graph = network.read_only();
6838 let scorer = ln_test_utils::TestScorer::new();
6840 // Make sure that generally there is at least one route available
6841 let feasible_max_total_cltv_delta = 1008;
6842 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6843 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6844 let random_seed_bytes = [42; 32];
6845 let route_params = RouteParameters::from_payment_params_and_value(
6846 feasible_payment_params, 100);
6847 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6848 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6849 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6850 assert_ne!(path.len(), 0);
6852 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6853 let fail_max_total_cltv_delta = 23;
6854 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6855 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6856 let route_params = RouteParameters::from_payment_params_and_value(
6857 fail_payment_params, 100);
6858 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6859 &Default::default(), &random_seed_bytes)
6861 Err(LightningError { err, .. } ) => {
6862 assert_eq!(err, "Failed to find a path to the given destination");
6864 Ok(_) => panic!("Expected error"),
6869 fn avoids_recently_failed_paths() {
6870 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6871 // randomly inserting channels into it until we can't find a route anymore.
6872 let (secp_ctx, network, _, _, logger) = build_graph();
6873 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6874 let network_graph = network.read_only();
6876 let scorer = ln_test_utils::TestScorer::new();
6877 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6878 .with_max_path_count(1);
6879 let random_seed_bytes = [42; 32];
6881 // We should be able to find a route initially, and then after we fail a few random
6882 // channels eventually we won't be able to any longer.
6883 let route_params = RouteParameters::from_payment_params_and_value(
6884 payment_params.clone(), 100);
6885 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6886 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6888 let route_params = RouteParameters::from_payment_params_and_value(
6889 payment_params.clone(), 100);
6890 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6891 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6893 for chan in route.paths[0].hops.iter() {
6894 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6896 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6897 % route.paths[0].hops.len();
6898 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6904 fn limits_path_length() {
6905 let (secp_ctx, network, _, _, logger) = build_line_graph();
6906 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6907 let network_graph = network.read_only();
6909 let scorer = ln_test_utils::TestScorer::new();
6910 let random_seed_bytes = [42; 32];
6912 // First check we can actually create a long route on this graph.
6913 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6914 let route_params = RouteParameters::from_payment_params_and_value(
6915 feasible_payment_params, 100);
6916 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6917 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6918 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6919 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6921 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6922 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6923 let route_params = RouteParameters::from_payment_params_and_value(
6924 fail_payment_params, 100);
6925 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6926 &Default::default(), &random_seed_bytes)
6928 Err(LightningError { err, .. } ) => {
6929 assert_eq!(err, "Failed to find a path to the given destination");
6931 Ok(_) => panic!("Expected error"),
6936 fn adds_and_limits_cltv_offset() {
6937 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6938 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6940 let scorer = ln_test_utils::TestScorer::new();
6942 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6943 let random_seed_bytes = [42; 32];
6944 let route_params = RouteParameters::from_payment_params_and_value(
6945 payment_params.clone(), 100);
6946 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6947 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6948 assert_eq!(route.paths.len(), 1);
6950 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6952 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6953 let mut route_default = route.clone();
6954 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6955 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6956 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6957 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6958 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6960 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6961 let mut route_limited = route.clone();
6962 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6963 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6964 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6965 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6966 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6970 fn adds_plausible_cltv_offset() {
6971 let (secp_ctx, network, _, _, logger) = build_graph();
6972 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6973 let network_graph = network.read_only();
6974 let network_nodes = network_graph.nodes();
6975 let network_channels = network_graph.channels();
6976 let scorer = ln_test_utils::TestScorer::new();
6977 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6978 let random_seed_bytes = [42; 32];
6980 let route_params = RouteParameters::from_payment_params_and_value(
6981 payment_params.clone(), 100);
6982 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6983 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6984 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6986 let mut path_plausibility = vec![];
6988 for p in route.paths {
6989 // 1. Select random observation point
6990 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6991 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6993 prng.process_in_place(&mut random_bytes);
6994 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6995 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6997 // 2. Calculate what CLTV expiry delta we would observe there
6998 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
7000 // 3. Starting from the observation point, find candidate paths
7001 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
7002 candidates.push_back((observation_point, vec![]));
7004 let mut found_plausible_candidate = false;
7006 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
7007 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
7008 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
7009 found_plausible_candidate = true;
7010 break 'candidate_loop;
7014 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
7015 for channel_id in &cur_node.channels {
7016 if let Some(channel_info) = network_channels.get(&channel_id) {
7017 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
7018 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
7019 if cur_path_cltv_deltas.iter().sum::<u32>()
7020 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
7021 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
7022 new_path_cltv_deltas.push(next_cltv_expiry_delta);
7023 candidates.push_back((*next_id, new_path_cltv_deltas));
7031 path_plausibility.push(found_plausible_candidate);
7033 assert!(path_plausibility.iter().all(|x| *x));
7037 fn builds_correct_path_from_hops() {
7038 let (secp_ctx, network, _, _, logger) = build_graph();
7039 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7040 let network_graph = network.read_only();
7042 let random_seed_bytes = [42; 32];
7043 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
7044 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
7045 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
7046 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
7047 Arc::clone(&logger), &random_seed_bytes).unwrap();
7048 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
7049 assert_eq!(hops.len(), route.paths[0].hops.len());
7050 for (idx, hop_pubkey) in hops.iter().enumerate() {
7051 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
7056 fn avoids_saturating_channels() {
7057 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
7058 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
7059 let decay_params = ProbabilisticScoringDecayParameters::default();
7060 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
7062 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
7063 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
7064 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7065 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7066 short_channel_id: 4,
7069 cltv_expiry_delta: (4 << 4) | 1,
7070 htlc_minimum_msat: 0,
7071 htlc_maximum_msat: 250_000_000,
7073 fee_proportional_millionths: 0,
7074 excess_data: Vec::new()
7076 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
7077 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7078 short_channel_id: 13,
7081 cltv_expiry_delta: (13 << 4) | 1,
7082 htlc_minimum_msat: 0,
7083 htlc_maximum_msat: 250_000_000,
7085 fee_proportional_millionths: 0,
7086 excess_data: Vec::new()
7089 let config = UserConfig::default();
7090 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
7091 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7093 let random_seed_bytes = [42; 32];
7095 // 100,000 sats is less than the available liquidity on each channel, set above.
7096 let route_params = RouteParameters::from_payment_params_and_value(
7097 payment_params, 100_000_000);
7098 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
7099 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
7100 assert_eq!(route.paths.len(), 2);
7101 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
7102 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
7105 #[cfg(feature = "std")]
7106 pub(super) fn random_init_seed() -> u64 {
7107 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
7108 use core::hash::{BuildHasher, Hasher};
7109 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
7110 println!("Using seed of {}", seed);
7115 #[cfg(feature = "std")]
7116 fn generate_routes() {
7117 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7119 let logger = ln_test_utils::TestLogger::new();
7120 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7128 let params = ProbabilisticScoringFeeParameters::default();
7129 let features = super::Bolt11InvoiceFeatures::empty();
7131 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7135 #[cfg(feature = "std")]
7136 fn generate_routes_mpp() {
7137 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7139 let logger = ln_test_utils::TestLogger::new();
7140 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7148 let params = ProbabilisticScoringFeeParameters::default();
7149 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7151 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7155 #[cfg(feature = "std")]
7156 fn generate_large_mpp_routes() {
7157 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7159 let logger = ln_test_utils::TestLogger::new();
7160 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7168 let params = ProbabilisticScoringFeeParameters::default();
7169 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7171 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
7175 fn honors_manual_penalties() {
7176 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
7177 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7179 let random_seed_bytes = [42; 32];
7180 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
7181 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
7183 // First check set manual penalties are returned by the scorer.
7184 let usage = ChannelUsage {
7186 inflight_htlc_msat: 0,
7187 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
7189 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
7190 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
7191 let network_graph = network_graph.read_only();
7192 let channels = network_graph.channels();
7193 let channel = channels.get(&5).unwrap();
7194 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
7195 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop(PublicHopCandidate {
7197 short_channel_id: 5,
7199 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
7201 // Then check we can get a normal route
7202 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
7203 let route_params = RouteParameters::from_payment_params_and_value(
7204 payment_params, 100);
7205 let route = get_route(&our_id, &route_params, &network_graph, None,
7206 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
7207 assert!(route.is_ok());
7209 // Then check that we can't get a route if we ban an intermediate node.
7210 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
7211 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7212 assert!(route.is_err());
7214 // Finally make sure we can route again, when we remove the ban.
7215 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
7216 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7217 assert!(route.is_ok());
7221 fn abide_by_route_hint_max_htlc() {
7222 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
7223 // params in the final route.
7224 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7225 let netgraph = network_graph.read_only();
7226 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7227 let scorer = ln_test_utils::TestScorer::new();
7228 let random_seed_bytes = [42; 32];
7229 let config = UserConfig::default();
7231 let max_htlc_msat = 50_000;
7232 let route_hint_1 = RouteHint(vec![RouteHintHop {
7233 src_node_id: nodes[2],
7234 short_channel_id: 42,
7237 proportional_millionths: 0,
7239 cltv_expiry_delta: 10,
7240 htlc_minimum_msat: None,
7241 htlc_maximum_msat: Some(max_htlc_msat),
7243 let dest_node_id = ln_test_utils::pubkey(42);
7244 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7245 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
7246 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7249 // Make sure we'll error if our route hints don't have enough liquidity according to their
7250 // htlc_maximum_msat.
7251 let mut route_params = RouteParameters::from_payment_params_and_value(
7252 payment_params, max_htlc_msat + 1);
7253 route_params.max_total_routing_fee_msat = None;
7254 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
7255 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
7258 assert_eq!(err, "Failed to find a sufficient route to the given destination");
7259 } else { panic!(); }
7261 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
7262 let mut route_hint_2 = route_hint_1.clone();
7263 route_hint_2.0[0].short_channel_id = 43;
7264 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7265 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7266 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7268 let mut route_params = RouteParameters::from_payment_params_and_value(
7269 payment_params, max_htlc_msat + 1);
7270 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
7271 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
7272 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7273 assert_eq!(route.paths.len(), 2);
7274 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7275 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7279 fn direct_channel_to_hints_with_max_htlc() {
7280 // Check that if we have a first hop channel peer that's connected to multiple provided route
7281 // hints, that we properly split the payment between the route hints if needed.
7282 let logger = Arc::new(ln_test_utils::TestLogger::new());
7283 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7284 let scorer = ln_test_utils::TestScorer::new();
7285 let random_seed_bytes = [42; 32];
7286 let config = UserConfig::default();
7288 let our_node_id = ln_test_utils::pubkey(42);
7289 let intermed_node_id = ln_test_utils::pubkey(43);
7290 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7292 let amt_msat = 900_000;
7293 let max_htlc_msat = 500_000;
7294 let route_hint_1 = RouteHint(vec![RouteHintHop {
7295 src_node_id: intermed_node_id,
7296 short_channel_id: 44,
7299 proportional_millionths: 0,
7301 cltv_expiry_delta: 10,
7302 htlc_minimum_msat: None,
7303 htlc_maximum_msat: Some(max_htlc_msat),
7305 src_node_id: intermed_node_id,
7306 short_channel_id: 45,
7309 proportional_millionths: 0,
7311 cltv_expiry_delta: 10,
7312 htlc_minimum_msat: None,
7313 // Check that later route hint max htlcs don't override earlier ones
7314 htlc_maximum_msat: Some(max_htlc_msat - 50),
7316 let mut route_hint_2 = route_hint_1.clone();
7317 route_hint_2.0[0].short_channel_id = 46;
7318 route_hint_2.0[1].short_channel_id = 47;
7319 let dest_node_id = ln_test_utils::pubkey(44);
7320 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7321 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7322 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7325 let route_params = RouteParameters::from_payment_params_and_value(
7326 payment_params, amt_msat);
7327 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7328 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7329 &Default::default(), &random_seed_bytes).unwrap();
7330 assert_eq!(route.paths.len(), 2);
7331 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7332 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7333 assert_eq!(route.get_total_amount(), amt_msat);
7335 // Re-run but with two first hop channels connected to the same route hint peers that must be
7337 let first_hops = vec![
7338 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7339 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7341 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7342 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7343 &Default::default(), &random_seed_bytes).unwrap();
7344 assert_eq!(route.paths.len(), 2);
7345 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7346 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7347 assert_eq!(route.get_total_amount(), amt_msat);
7349 // Make sure this works for blinded route hints.
7350 let blinded_path = BlindedPath {
7351 introduction_node: IntroductionNode::NodeId(intermed_node_id),
7352 blinding_point: ln_test_utils::pubkey(42),
7354 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
7355 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
7358 let blinded_payinfo = BlindedPayInfo {
7360 fee_proportional_millionths: 0,
7361 htlc_minimum_msat: 1,
7362 htlc_maximum_msat: max_htlc_msat,
7363 cltv_expiry_delta: 10,
7364 features: BlindedHopFeatures::empty(),
7366 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7367 let payment_params = PaymentParameters::blinded(vec![
7368 (blinded_payinfo.clone(), blinded_path.clone()),
7369 (blinded_payinfo.clone(), blinded_path.clone())])
7370 .with_bolt12_features(bolt12_features).unwrap();
7371 let route_params = RouteParameters::from_payment_params_and_value(
7372 payment_params, amt_msat);
7373 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7374 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7375 &Default::default(), &random_seed_bytes).unwrap();
7376 assert_eq!(route.paths.len(), 2);
7377 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7378 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7379 assert_eq!(route.get_total_amount(), amt_msat);
7383 fn blinded_route_ser() {
7384 let blinded_path_1 = BlindedPath {
7385 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(42)),
7386 blinding_point: ln_test_utils::pubkey(43),
7388 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7389 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7392 let blinded_path_2 = BlindedPath {
7393 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(46)),
7394 blinding_point: ln_test_utils::pubkey(47),
7396 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7397 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7400 // (De)serialize a Route with 1 blinded path out of two total paths.
7401 let mut route = Route { paths: vec![Path {
7402 hops: vec![RouteHop {
7403 pubkey: ln_test_utils::pubkey(50),
7404 node_features: NodeFeatures::empty(),
7405 short_channel_id: 42,
7406 channel_features: ChannelFeatures::empty(),
7408 cltv_expiry_delta: 0,
7409 maybe_announced_channel: true,
7411 blinded_tail: Some(BlindedTail {
7412 hops: blinded_path_1.blinded_hops,
7413 blinding_point: blinded_path_1.blinding_point,
7414 excess_final_cltv_expiry_delta: 40,
7415 final_value_msat: 100,
7417 hops: vec![RouteHop {
7418 pubkey: ln_test_utils::pubkey(51),
7419 node_features: NodeFeatures::empty(),
7420 short_channel_id: 43,
7421 channel_features: ChannelFeatures::empty(),
7423 cltv_expiry_delta: 0,
7424 maybe_announced_channel: true,
7425 }], blinded_tail: None }],
7428 let encoded_route = route.encode();
7429 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7430 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7431 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7433 // (De)serialize a Route with two paths, each containing a blinded tail.
7434 route.paths[1].blinded_tail = Some(BlindedTail {
7435 hops: blinded_path_2.blinded_hops,
7436 blinding_point: blinded_path_2.blinding_point,
7437 excess_final_cltv_expiry_delta: 41,
7438 final_value_msat: 101,
7440 let encoded_route = route.encode();
7441 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7442 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7443 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7447 fn blinded_path_inflight_processing() {
7448 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7449 // account for the blinded tail's final amount_msat.
7450 let mut inflight_htlcs = InFlightHtlcs::new();
7451 let blinded_path = BlindedPath {
7452 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(43)),
7453 blinding_point: ln_test_utils::pubkey(48),
7454 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7457 hops: vec![RouteHop {
7458 pubkey: ln_test_utils::pubkey(42),
7459 node_features: NodeFeatures::empty(),
7460 short_channel_id: 42,
7461 channel_features: ChannelFeatures::empty(),
7463 cltv_expiry_delta: 0,
7464 maybe_announced_channel: false,
7467 pubkey: ln_test_utils::pubkey(43),
7468 node_features: NodeFeatures::empty(),
7469 short_channel_id: 43,
7470 channel_features: ChannelFeatures::empty(),
7472 cltv_expiry_delta: 0,
7473 maybe_announced_channel: false,
7475 blinded_tail: Some(BlindedTail {
7476 hops: blinded_path.blinded_hops,
7477 blinding_point: blinded_path.blinding_point,
7478 excess_final_cltv_expiry_delta: 0,
7479 final_value_msat: 200,
7482 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7483 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7484 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7488 fn blinded_path_cltv_shadow_offset() {
7489 // Make sure we add a shadow offset when sending to blinded paths.
7490 let blinded_path = BlindedPath {
7491 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(43)),
7492 blinding_point: ln_test_utils::pubkey(44),
7494 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7495 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7498 let mut route = Route { paths: vec![Path {
7499 hops: vec![RouteHop {
7500 pubkey: ln_test_utils::pubkey(42),
7501 node_features: NodeFeatures::empty(),
7502 short_channel_id: 42,
7503 channel_features: ChannelFeatures::empty(),
7505 cltv_expiry_delta: 0,
7506 maybe_announced_channel: false,
7509 pubkey: ln_test_utils::pubkey(43),
7510 node_features: NodeFeatures::empty(),
7511 short_channel_id: 43,
7512 channel_features: ChannelFeatures::empty(),
7514 cltv_expiry_delta: 0,
7515 maybe_announced_channel: false,
7518 blinded_tail: Some(BlindedTail {
7519 hops: blinded_path.blinded_hops,
7520 blinding_point: blinded_path.blinding_point,
7521 excess_final_cltv_expiry_delta: 0,
7522 final_value_msat: 200,
7524 }], route_params: None};
7526 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7527 let (_, network_graph, _, _, _) = build_line_graph();
7528 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7529 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7530 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7534 fn simple_blinded_route_hints() {
7535 do_simple_blinded_route_hints(1);
7536 do_simple_blinded_route_hints(2);
7537 do_simple_blinded_route_hints(3);
7540 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7541 // Check that we can generate a route to a blinded path with the expected hops.
7542 let (secp_ctx, network, _, _, logger) = build_graph();
7543 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7544 let network_graph = network.read_only();
7546 let scorer = ln_test_utils::TestScorer::new();
7547 let random_seed_bytes = [42; 32];
7549 let mut blinded_path = BlindedPath {
7550 introduction_node: IntroductionNode::NodeId(nodes[2]),
7551 blinding_point: ln_test_utils::pubkey(42),
7552 blinded_hops: Vec::with_capacity(num_blinded_hops),
7554 for i in 0..num_blinded_hops {
7555 blinded_path.blinded_hops.push(
7556 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7559 let blinded_payinfo = BlindedPayInfo {
7561 fee_proportional_millionths: 500,
7562 htlc_minimum_msat: 1000,
7563 htlc_maximum_msat: 100_000_000,
7564 cltv_expiry_delta: 15,
7565 features: BlindedHopFeatures::empty(),
7568 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7569 let route_params = RouteParameters::from_payment_params_and_value(
7570 payment_params, 1001);
7571 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7572 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7573 assert_eq!(route.paths.len(), 1);
7574 assert_eq!(route.paths[0].hops.len(), 2);
7576 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7577 assert_eq!(tail.hops, blinded_path.blinded_hops);
7578 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7579 assert_eq!(tail.final_value_msat, 1001);
7581 let final_hop = route.paths[0].hops.last().unwrap();
7583 NodeId::from_pubkey(&final_hop.pubkey),
7584 *blinded_path.public_introduction_node_id(&network_graph).unwrap()
7586 if tail.hops.len() > 1 {
7587 assert_eq!(final_hop.fee_msat,
7588 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7589 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7591 assert_eq!(final_hop.fee_msat, 0);
7592 assert_eq!(final_hop.cltv_expiry_delta, 0);
7597 fn blinded_path_routing_errors() {
7598 // Check that we can generate a route to a blinded path with the expected hops.
7599 let (secp_ctx, network, _, _, logger) = build_graph();
7600 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7601 let network_graph = network.read_only();
7603 let scorer = ln_test_utils::TestScorer::new();
7604 let random_seed_bytes = [42; 32];
7606 let mut invalid_blinded_path = BlindedPath {
7607 introduction_node: IntroductionNode::NodeId(nodes[2]),
7608 blinding_point: ln_test_utils::pubkey(42),
7610 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7613 let blinded_payinfo = BlindedPayInfo {
7615 fee_proportional_millionths: 500,
7616 htlc_minimum_msat: 1000,
7617 htlc_maximum_msat: 100_000_000,
7618 cltv_expiry_delta: 15,
7619 features: BlindedHopFeatures::empty(),
7622 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7623 invalid_blinded_path_2.introduction_node = IntroductionNode::NodeId(ln_test_utils::pubkey(45));
7624 let payment_params = PaymentParameters::blinded(vec![
7625 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7626 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7627 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7628 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7629 &scorer, &Default::default(), &random_seed_bytes)
7631 Err(LightningError { err, .. }) => {
7632 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7634 _ => panic!("Expected error")
7637 invalid_blinded_path.introduction_node = IntroductionNode::NodeId(our_id);
7638 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7639 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7640 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7641 &Default::default(), &random_seed_bytes)
7643 Err(LightningError { err, .. }) => {
7644 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7646 _ => panic!("Expected error")
7649 invalid_blinded_path.introduction_node = IntroductionNode::NodeId(ln_test_utils::pubkey(46));
7650 invalid_blinded_path.blinded_hops.clear();
7651 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7652 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7653 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7654 &Default::default(), &random_seed_bytes)
7656 Err(LightningError { err, .. }) => {
7657 assert_eq!(err, "0-hop blinded path provided");
7659 _ => panic!("Expected error")
7664 fn matching_intro_node_paths_provided() {
7665 // Check that if multiple blinded paths with the same intro node are provided in payment
7666 // parameters, we'll return the correct paths in the resulting MPP route.
7667 let (secp_ctx, network, _, _, logger) = build_graph();
7668 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7669 let network_graph = network.read_only();
7671 let scorer = ln_test_utils::TestScorer::new();
7672 let random_seed_bytes = [42; 32];
7673 let config = UserConfig::default();
7675 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7676 let blinded_path_1 = BlindedPath {
7677 introduction_node: IntroductionNode::NodeId(nodes[2]),
7678 blinding_point: ln_test_utils::pubkey(42),
7680 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7681 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7684 let blinded_payinfo_1 = BlindedPayInfo {
7686 fee_proportional_millionths: 0,
7687 htlc_minimum_msat: 0,
7688 htlc_maximum_msat: 30_000,
7689 cltv_expiry_delta: 0,
7690 features: BlindedHopFeatures::empty(),
7693 let mut blinded_path_2 = blinded_path_1.clone();
7694 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7695 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7696 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7698 let blinded_hints = vec![
7699 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7700 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7702 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7703 .with_bolt12_features(bolt12_features).unwrap();
7705 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7706 route_params.max_total_routing_fee_msat = Some(100_000);
7707 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7708 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7709 assert_eq!(route.paths.len(), 2);
7710 let mut total_amount_paid_msat = 0;
7711 for path in route.paths.into_iter() {
7712 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7713 if let Some(bt) = &path.blinded_tail {
7714 assert_eq!(bt.blinding_point,
7715 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7716 .map(|(_, bp)| bp.blinding_point).unwrap());
7717 } else { panic!(); }
7718 total_amount_paid_msat += path.final_value_msat();
7720 assert_eq!(total_amount_paid_msat, 100_000);
7724 fn direct_to_intro_node() {
7725 // This previously caused a debug panic in the router when asserting
7726 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7727 // direct channels we failed to account for the fee charged for use of the blinded path.
7730 // node0 -1(1)2 - node1
7731 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7732 // doesn't account for the blinded path fee.
7734 let secp_ctx = Secp256k1::new();
7735 let logger = Arc::new(ln_test_utils::TestLogger::new());
7736 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7737 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7738 let scorer = ln_test_utils::TestScorer::new();
7739 let random_seed_bytes = [42; 32];
7741 let amt_msat = 10_000_000;
7742 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7743 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7744 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7745 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7746 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7747 short_channel_id: 1,
7750 cltv_expiry_delta: 42,
7751 htlc_minimum_msat: 1_000,
7752 htlc_maximum_msat: 10_000_000,
7754 fee_proportional_millionths: 0,
7755 excess_data: Vec::new()
7757 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7758 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7759 short_channel_id: 1,
7762 cltv_expiry_delta: 42,
7763 htlc_minimum_msat: 1_000,
7764 htlc_maximum_msat: 10_000_000,
7766 fee_proportional_millionths: 0,
7767 excess_data: Vec::new()
7769 let first_hops = vec![
7770 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7772 let blinded_path = BlindedPath {
7773 introduction_node: IntroductionNode::NodeId(nodes[1]),
7774 blinding_point: ln_test_utils::pubkey(42),
7776 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7777 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7780 let blinded_payinfo = BlindedPayInfo {
7781 fee_base_msat: 1000,
7782 fee_proportional_millionths: 0,
7783 htlc_minimum_msat: 1000,
7784 htlc_maximum_msat: MAX_VALUE_MSAT,
7785 cltv_expiry_delta: 0,
7786 features: BlindedHopFeatures::empty(),
7788 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7790 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7792 let netgraph = network_graph.read_only();
7793 let route_params = RouteParameters::from_payment_params_and_value(
7794 payment_params.clone(), amt_msat);
7795 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7796 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7797 &Default::default(), &random_seed_bytes) {
7798 assert_eq!(err, "Failed to find a path to the given destination");
7799 } else { panic!("Expected error") }
7801 // Sending an exact amount accounting for the blinded path fee works.
7802 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7803 let route_params = RouteParameters::from_payment_params_and_value(
7804 payment_params, amt_minus_blinded_path_fee);
7805 let route = get_route(&nodes[0], &route_params, &netgraph,
7806 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7807 &Default::default(), &random_seed_bytes).unwrap();
7808 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7809 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7813 fn direct_to_matching_intro_nodes() {
7814 // This previously caused us to enter `unreachable` code in the following situation:
7815 // 1. We add a route candidate for intro_node contributing a high amount
7816 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7817 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7818 // amount, and update our route candidate for intro_node for the lower amount
7819 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7820 // lower contribution amount, but fail (this was previously caused by failure to account for
7821 // blinded path fees when adding first_hop<>intro_node candidates)
7822 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7823 // candidate still thinks its path is contributing the original higher amount. This caused us
7824 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7826 let secp_ctx = Secp256k1::new();
7827 let logger = Arc::new(ln_test_utils::TestLogger::new());
7828 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7829 let scorer = ln_test_utils::TestScorer::new();
7830 let random_seed_bytes = [42; 32];
7831 let config = UserConfig::default();
7833 // Values are taken from the fuzz input that uncovered this panic.
7834 let amt_msat = 21_7020_5185_1403_2640;
7835 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7836 let first_hops = vec![
7837 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7838 18446744073709551615)];
7840 let blinded_path = BlindedPath {
7841 introduction_node: IntroductionNode::NodeId(nodes[1]),
7842 blinding_point: ln_test_utils::pubkey(42),
7844 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7845 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7848 let blinded_payinfo = BlindedPayInfo {
7849 fee_base_msat: 5046_2720,
7850 fee_proportional_millionths: 0,
7851 htlc_minimum_msat: 4503_5996_2737_0496,
7852 htlc_maximum_msat: 45_0359_9627_3704_9600,
7853 cltv_expiry_delta: 0,
7854 features: BlindedHopFeatures::empty(),
7856 let mut blinded_hints = vec![
7857 (blinded_payinfo.clone(), blinded_path.clone()),
7858 (blinded_payinfo.clone(), blinded_path.clone()),
7860 blinded_hints[1].0.fee_base_msat = 419_4304;
7861 blinded_hints[1].0.fee_proportional_millionths = 257;
7862 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7863 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7864 blinded_hints[1].0.cltv_expiry_delta = 0;
7866 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7867 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7868 .with_bolt12_features(bolt12_features).unwrap();
7870 let netgraph = network_graph.read_only();
7871 let route_params = RouteParameters::from_payment_params_and_value(
7872 payment_params, amt_msat);
7873 let route = get_route(&nodes[0], &route_params, &netgraph,
7874 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7875 &Default::default(), &random_seed_bytes).unwrap();
7876 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7877 assert_eq!(route.get_total_amount(), amt_msat);
7881 fn we_are_intro_node_candidate_hops() {
7882 // This previously led to a panic in the router because we'd generate a Path with only a
7883 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7884 // where the origin node is the intro node. We now fully disallow considering candidate hops
7885 // where the origin node is the intro node.
7886 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7887 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7888 let scorer = ln_test_utils::TestScorer::new();
7889 let random_seed_bytes = [42; 32];
7890 let config = UserConfig::default();
7892 // Values are taken from the fuzz input that uncovered this panic.
7893 let amt_msat = 21_7020_5185_1423_0019;
7895 let blinded_path = BlindedPath {
7896 introduction_node: IntroductionNode::NodeId(our_id),
7897 blinding_point: ln_test_utils::pubkey(42),
7899 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7900 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7903 let blinded_payinfo = BlindedPayInfo {
7904 fee_base_msat: 5052_9027,
7905 fee_proportional_millionths: 0,
7906 htlc_minimum_msat: 21_7020_5185_1423_0019,
7907 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7908 cltv_expiry_delta: 0,
7909 features: BlindedHopFeatures::empty(),
7911 let mut blinded_hints = vec![
7912 (blinded_payinfo.clone(), blinded_path.clone()),
7913 (blinded_payinfo.clone(), blinded_path.clone()),
7915 blinded_hints[1].1.introduction_node = IntroductionNode::NodeId(nodes[6]);
7917 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7918 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7919 .with_bolt12_features(bolt12_features.clone()).unwrap();
7921 let netgraph = network_graph.read_only();
7922 let route_params = RouteParameters::from_payment_params_and_value(
7923 payment_params, amt_msat);
7924 if let Err(LightningError { err, .. }) = get_route(
7925 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7927 assert_eq!(err, "Failed to find a path to the given destination");
7932 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7933 // This previously led to a debug panic in the router because we'd find an invalid Path with
7934 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7935 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7936 // the payment, when it was intended to only include the final value of the payment.
7937 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7938 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7939 let scorer = ln_test_utils::TestScorer::new();
7940 let random_seed_bytes = [42; 32];
7941 let config = UserConfig::default();
7943 // Values are taken from the fuzz input that uncovered this panic.
7944 let amt_msat = 21_7020_5185_1423_0019;
7946 let blinded_path = BlindedPath {
7947 introduction_node: IntroductionNode::NodeId(our_id),
7948 blinding_point: ln_test_utils::pubkey(42),
7950 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7951 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7954 let blinded_payinfo = BlindedPayInfo {
7955 fee_base_msat: 10_4425_1395,
7956 fee_proportional_millionths: 0,
7957 htlc_minimum_msat: 21_7301_9934_9094_0931,
7958 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7959 cltv_expiry_delta: 0,
7960 features: BlindedHopFeatures::empty(),
7962 let mut blinded_hints = vec![
7963 (blinded_payinfo.clone(), blinded_path.clone()),
7964 (blinded_payinfo.clone(), blinded_path.clone()),
7965 (blinded_payinfo.clone(), blinded_path.clone()),
7967 blinded_hints[1].0.fee_base_msat = 5052_9027;
7968 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7969 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7971 blinded_hints[2].1.introduction_node = IntroductionNode::NodeId(nodes[6]);
7973 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7974 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7975 .with_bolt12_features(bolt12_features.clone()).unwrap();
7977 let netgraph = network_graph.read_only();
7978 let route_params = RouteParameters::from_payment_params_and_value(
7979 payment_params, amt_msat);
7980 if let Err(LightningError { err, .. }) = get_route(
7981 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7983 assert_eq!(err, "Failed to find a path to the given destination");
7988 fn min_htlc_overpay_violates_max_htlc() {
7989 do_min_htlc_overpay_violates_max_htlc(true);
7990 do_min_htlc_overpay_violates_max_htlc(false);
7992 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7993 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7994 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7995 // to `targets` and build an invalid path with it, and subsequently hit a debug panic asserting
7996 // that the used liquidity for a hop was less than its available liquidity limit.
7997 let secp_ctx = Secp256k1::new();
7998 let logger = Arc::new(ln_test_utils::TestLogger::new());
7999 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8000 let scorer = ln_test_utils::TestScorer::new();
8001 let random_seed_bytes = [42; 32];
8002 let config = UserConfig::default();
8004 // Values are taken from the fuzz input that uncovered this panic.
8005 let amt_msat = 7_4009_8048;
8006 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8007 let first_hop_outbound_capacity = 2_7345_2000;
8008 let first_hops = vec![get_channel_details(
8009 Some(200), nodes[0], channelmanager::provided_init_features(&config),
8010 first_hop_outbound_capacity
8013 let base_fee = 1_6778_3453;
8014 let htlc_min = 2_5165_8240;
8015 let payment_params = if blinded_payee {
8016 let blinded_path = BlindedPath {
8017 introduction_node: IntroductionNode::NodeId(nodes[0]),
8018 blinding_point: ln_test_utils::pubkey(42),
8020 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8021 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8024 let blinded_payinfo = BlindedPayInfo {
8025 fee_base_msat: base_fee,
8026 fee_proportional_millionths: 0,
8027 htlc_minimum_msat: htlc_min,
8028 htlc_maximum_msat: htlc_min * 1000,
8029 cltv_expiry_delta: 0,
8030 features: BlindedHopFeatures::empty(),
8032 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8033 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
8034 .with_bolt12_features(bolt12_features.clone()).unwrap()
8036 let route_hint = RouteHint(vec![RouteHintHop {
8037 src_node_id: nodes[0],
8038 short_channel_id: 42,
8040 base_msat: base_fee,
8041 proportional_millionths: 0,
8043 cltv_expiry_delta: 10,
8044 htlc_minimum_msat: Some(htlc_min),
8045 htlc_maximum_msat: None,
8048 PaymentParameters::from_node_id(nodes[1], 42)
8049 .with_route_hints(vec![route_hint]).unwrap()
8050 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8053 let netgraph = network_graph.read_only();
8054 let route_params = RouteParameters::from_payment_params_and_value(
8055 payment_params, amt_msat);
8056 if let Err(LightningError { err, .. }) = get_route(
8057 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8058 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8060 assert_eq!(err, "Failed to find a path to the given destination");
8065 fn previously_used_liquidity_violates_max_htlc() {
8066 do_previously_used_liquidity_violates_max_htlc(true);
8067 do_previously_used_liquidity_violates_max_htlc(false);
8070 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
8071 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
8072 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
8073 // candidate. In this case, the candidate does not have enough due to a previous path taking up
8074 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
8075 // asserting that the used liquidity for a hop was less than its available liquidity limit.
8076 let secp_ctx = Secp256k1::new();
8077 let logger = Arc::new(ln_test_utils::TestLogger::new());
8078 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8079 let scorer = ln_test_utils::TestScorer::new();
8080 let random_seed_bytes = [42; 32];
8081 let config = UserConfig::default();
8083 // Values are taken from the fuzz input that uncovered this panic.
8084 let amt_msat = 52_4288;
8085 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8086 let first_hops = vec![get_channel_details(
8087 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
8088 ), get_channel_details(
8089 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
8092 let base_fees = [0, 425_9840, 0, 0];
8093 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
8094 let payment_params = if blinded_payee {
8095 let blinded_path = BlindedPath {
8096 introduction_node: IntroductionNode::NodeId(nodes[0]),
8097 blinding_point: ln_test_utils::pubkey(42),
8099 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8100 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8103 let mut blinded_hints = Vec::new();
8104 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
8105 blinded_hints.push((BlindedPayInfo {
8106 fee_base_msat: *base_fee,
8107 fee_proportional_millionths: 0,
8108 htlc_minimum_msat: *htlc_min,
8109 htlc_maximum_msat: htlc_min * 100,
8110 cltv_expiry_delta: 10,
8111 features: BlindedHopFeatures::empty(),
8112 }, blinded_path.clone()));
8114 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8115 PaymentParameters::blinded(blinded_hints.clone())
8116 .with_bolt12_features(bolt12_features.clone()).unwrap()
8118 let mut route_hints = Vec::new();
8119 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
8120 route_hints.push(RouteHint(vec![RouteHintHop {
8121 src_node_id: nodes[0],
8122 short_channel_id: 42 + idx as u64,
8124 base_msat: *base_fee,
8125 proportional_millionths: 0,
8127 cltv_expiry_delta: 10,
8128 htlc_minimum_msat: Some(*htlc_min),
8129 htlc_maximum_msat: Some(htlc_min * 100),
8132 PaymentParameters::from_node_id(nodes[1], 42)
8133 .with_route_hints(route_hints).unwrap()
8134 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8137 let netgraph = network_graph.read_only();
8138 let route_params = RouteParameters::from_payment_params_and_value(
8139 payment_params, amt_msat);
8141 let route = get_route(
8142 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8143 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8145 assert_eq!(route.paths.len(), 1);
8146 assert_eq!(route.get_total_amount(), amt_msat);
8150 fn candidate_path_min() {
8151 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
8152 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
8153 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
8154 // would add a connecting first_hop node that did not have enough contribution amount, leading
8155 // to a debug panic upon invalid path construction.
8156 let secp_ctx = Secp256k1::new();
8157 let logger = Arc::new(ln_test_utils::TestLogger::new());
8158 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8159 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
8160 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8161 let random_seed_bytes = [42; 32];
8162 let config = UserConfig::default();
8164 // Values are taken from the fuzz input that uncovered this panic.
8165 let amt_msat = 7_4009_8048;
8166 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
8167 let first_hops = vec![get_channel_details(
8168 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
8171 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
8172 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8173 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8174 short_channel_id: 6,
8177 cltv_expiry_delta: (6 << 4) | 0,
8178 htlc_minimum_msat: 0,
8179 htlc_maximum_msat: MAX_VALUE_MSAT,
8181 fee_proportional_millionths: 0,
8182 excess_data: Vec::new()
8184 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
8186 let htlc_min = 2_5165_8240;
8187 let blinded_hints = vec![
8189 fee_base_msat: 1_6778_3453,
8190 fee_proportional_millionths: 0,
8191 htlc_minimum_msat: htlc_min,
8192 htlc_maximum_msat: htlc_min * 100,
8193 cltv_expiry_delta: 10,
8194 features: BlindedHopFeatures::empty(),
8196 introduction_node: IntroductionNode::NodeId(nodes[0]),
8197 blinding_point: ln_test_utils::pubkey(42),
8199 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8200 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8204 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8205 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8206 .with_bolt12_features(bolt12_features.clone()).unwrap();
8207 let route_params = RouteParameters::from_payment_params_and_value(
8208 payment_params, amt_msat);
8209 let netgraph = network_graph.read_only();
8211 if let Err(LightningError { err, .. }) = get_route(
8212 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8213 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8216 assert_eq!(err, "Failed to find a path to the given destination");
8221 fn path_contribution_includes_min_htlc_overpay() {
8222 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
8223 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
8224 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
8225 // selection, both tested here.
8226 let secp_ctx = Secp256k1::new();
8227 let logger = Arc::new(ln_test_utils::TestLogger::new());
8228 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8229 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8230 let random_seed_bytes = [42; 32];
8231 let config = UserConfig::default();
8233 // Values are taken from the fuzz input that uncovered this panic.
8234 let amt_msat = 562_0000;
8235 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8236 let first_hops = vec![
8237 get_channel_details(
8238 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
8242 let htlc_mins = [49_0000, 1125_0000];
8243 let payment_params = {
8244 let blinded_path = BlindedPath {
8245 introduction_node: IntroductionNode::NodeId(nodes[0]),
8246 blinding_point: ln_test_utils::pubkey(42),
8248 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8249 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8252 let mut blinded_hints = Vec::new();
8253 for htlc_min in htlc_mins.iter() {
8254 blinded_hints.push((BlindedPayInfo {
8256 fee_proportional_millionths: 0,
8257 htlc_minimum_msat: *htlc_min,
8258 htlc_maximum_msat: *htlc_min * 100,
8259 cltv_expiry_delta: 10,
8260 features: BlindedHopFeatures::empty(),
8261 }, blinded_path.clone()));
8263 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8264 PaymentParameters::blinded(blinded_hints.clone())
8265 .with_bolt12_features(bolt12_features.clone()).unwrap()
8268 let netgraph = network_graph.read_only();
8269 let route_params = RouteParameters::from_payment_params_and_value(
8270 payment_params, amt_msat);
8271 let route = get_route(
8272 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8273 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8276 assert_eq!(route.paths.len(), 1);
8277 assert_eq!(route.get_total_amount(), amt_msat);
8281 fn first_hop_preferred_over_hint() {
8282 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
8283 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
8284 let secp_ctx = Secp256k1::new();
8285 let logger = Arc::new(ln_test_utils::TestLogger::new());
8286 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8287 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
8288 let scorer = ln_test_utils::TestScorer::new();
8289 let random_seed_bytes = [42; 32];
8290 let config = UserConfig::default();
8292 let amt_msat = 1_000_000;
8293 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
8295 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
8296 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
8297 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8298 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8299 short_channel_id: 1,
8302 cltv_expiry_delta: 42,
8303 htlc_minimum_msat: 1_000,
8304 htlc_maximum_msat: 10_000_000,
8306 fee_proportional_millionths: 0,
8307 excess_data: Vec::new()
8309 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8310 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8311 short_channel_id: 1,
8314 cltv_expiry_delta: 42,
8315 htlc_minimum_msat: 1_000,
8316 htlc_maximum_msat: 10_000_000,
8318 fee_proportional_millionths: 0,
8319 excess_data: Vec::new()
8322 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
8323 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
8324 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8325 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8326 short_channel_id: 2,
8329 cltv_expiry_delta: 42,
8330 htlc_minimum_msat: 1_000,
8331 htlc_maximum_msat: 10_000_000,
8333 fee_proportional_millionths: 0,
8334 excess_data: Vec::new()
8336 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8337 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8338 short_channel_id: 2,
8341 cltv_expiry_delta: 42,
8342 htlc_minimum_msat: 1_000,
8343 htlc_maximum_msat: 10_000_000,
8345 fee_proportional_millionths: 0,
8346 excess_data: Vec::new()
8349 let dest_node_id = nodes[2];
8351 let route_hint = RouteHint(vec![RouteHintHop {
8352 src_node_id: our_node_id,
8353 short_channel_id: 44,
8356 proportional_millionths: 0,
8358 cltv_expiry_delta: 10,
8359 htlc_minimum_msat: None,
8360 htlc_maximum_msat: Some(5_000_000),
8363 src_node_id: nodes[0],
8364 short_channel_id: 45,
8367 proportional_millionths: 0,
8369 cltv_expiry_delta: 10,
8370 htlc_minimum_msat: None,
8371 htlc_maximum_msat: None,
8374 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8375 .with_route_hints(vec![route_hint]).unwrap()
8376 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8377 let route_params = RouteParameters::from_payment_params_and_value(
8378 payment_params, amt_msat);
8380 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8382 let first_hop = get_channel_details(Some(1), nodes[0],
8383 channelmanager::provided_init_features(&config), 999_999);
8384 let first_hops = vec![first_hop];
8386 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8387 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8388 &Default::default(), &random_seed_bytes).unwrap();
8389 assert_eq!(route.paths.len(), 1);
8390 assert_eq!(route.get_total_amount(), amt_msat);
8391 assert_eq!(route.paths[0].hops.len(), 2);
8392 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8393 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8394 assert_eq!(route.get_total_fees(), 123);
8396 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8397 // for a first hop channel.
8398 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8399 first_hop.outbound_scid_alias = Some(44);
8400 let first_hops = vec![first_hop];
8402 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8403 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8404 &Default::default(), &random_seed_bytes);
8405 assert!(route_res.is_err());
8407 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8408 // use the cheaper second hop of the route hint.
8409 let mut first_hop = get_channel_details(Some(1), nodes[0],
8410 channelmanager::provided_init_features(&config), 10_000_000);
8411 first_hop.outbound_scid_alias = Some(44);
8412 let first_hops = vec![first_hop];
8414 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8415 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8416 &Default::default(), &random_seed_bytes).unwrap();
8417 assert_eq!(route.paths.len(), 1);
8418 assert_eq!(route.get_total_amount(), amt_msat);
8419 assert_eq!(route.paths[0].hops.len(), 2);
8420 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8421 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8422 assert_eq!(route.get_total_fees(), 123);
8426 fn allow_us_being_first_hint() {
8427 // Check that we consider a route hint even if we are the src of the first hop.
8428 let secp_ctx = Secp256k1::new();
8429 let logger = Arc::new(ln_test_utils::TestLogger::new());
8430 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8431 let scorer = ln_test_utils::TestScorer::new();
8432 let random_seed_bytes = [42; 32];
8433 let config = UserConfig::default();
8435 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8437 let amt_msat = 1_000_000;
8438 let dest_node_id = nodes[1];
8440 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8441 let first_hops = vec![first_hop];
8443 let route_hint = RouteHint(vec![RouteHintHop {
8444 src_node_id: our_node_id,
8445 short_channel_id: 44,
8448 proportional_millionths: 0,
8450 cltv_expiry_delta: 10,
8451 htlc_minimum_msat: None,
8452 htlc_maximum_msat: None,
8455 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8456 .with_route_hints(vec![route_hint]).unwrap()
8457 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8459 let route_params = RouteParameters::from_payment_params_and_value(
8460 payment_params, amt_msat);
8463 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8464 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8465 &Default::default(), &random_seed_bytes).unwrap();
8467 assert_eq!(route.paths.len(), 1);
8468 assert_eq!(route.get_total_amount(), amt_msat);
8469 assert_eq!(route.get_total_fees(), 0);
8470 assert_eq!(route.paths[0].hops.len(), 1);
8472 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8476 #[cfg(all(any(test, ldk_bench), feature = "std"))]
8477 pub(crate) mod bench_utils {
8481 use bitcoin::hashes::Hash;
8482 use bitcoin::secp256k1::SecretKey;
8484 use crate::chain::transaction::OutPoint;
8485 use crate::routing::scoring::{ProbabilisticScorer, ScoreUpdate};
8486 use crate::ln::channel_state::{ChannelCounterparty, ChannelShutdownState};
8487 use crate::ln::channelmanager;
8488 use crate::ln::types::ChannelId;
8489 use crate::util::config::UserConfig;
8490 use crate::util::test_utils::TestLogger;
8491 use crate::sync::Arc;
8493 /// Tries to open a network graph file, or panics with a URL to fetch it.
8494 pub(crate) fn get_graph_scorer_file() -> Result<(std::fs::File, std::fs::File), &'static str> {
8495 let load_file = |fname, err_str| {
8496 File::open(fname) // By default we're run in RL/lightning
8497 .or_else(|_| File::open(&format!("lightning/{}", fname))) // We may be run manually in RL/
8498 .or_else(|_| { // Fall back to guessing based on the binary location
8499 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8500 let mut path = std::env::current_exe().unwrap();
8501 path.pop(); // lightning-...
8503 path.pop(); // debug
8504 path.pop(); // target
8505 path.push("lightning");
8509 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8510 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8511 let mut path = std::env::current_exe().unwrap();
8512 path.pop(); // bench...
8514 path.pop(); // debug
8515 path.pop(); // target
8516 path.pop(); // bench
8517 path.push("lightning");
8521 .map_err(|_| err_str)
8523 let graph_res = load_file(
8524 "net_graph-2023-12-10.bin",
8525 "Please fetch https://bitcoin.ninja/ldk-net_graph-v0.0.118-2023-12-10.bin and place it at lightning/net_graph-2023-12-10.bin"
8527 let scorer_res = load_file(
8528 "scorer-2023-12-10.bin",
8529 "Please fetch https://bitcoin.ninja/ldk-scorer-v0.0.118-2023-12-10.bin and place it at lightning/scorer-2023-12-10.bin"
8531 #[cfg(require_route_graph_test)]
8532 return Ok((graph_res.unwrap(), scorer_res.unwrap()));
8533 #[cfg(not(require_route_graph_test))]
8534 return Ok((graph_res?, scorer_res?));
8537 pub(crate) fn read_graph_scorer(logger: &TestLogger)
8538 -> Result<(Arc<NetworkGraph<&TestLogger>>, ProbabilisticScorer<Arc<NetworkGraph<&TestLogger>>, &TestLogger>), &'static str> {
8539 let (mut graph_file, mut scorer_file) = get_graph_scorer_file()?;
8540 let graph = Arc::new(NetworkGraph::read(&mut graph_file, logger).unwrap());
8541 let scorer_args = (Default::default(), Arc::clone(&graph), logger);
8542 let scorer = ProbabilisticScorer::read(&mut scorer_file, scorer_args).unwrap();
8546 pub(crate) fn payer_pubkey() -> PublicKey {
8547 let secp_ctx = Secp256k1::new();
8548 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8552 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8554 channel_id: ChannelId::new_zero(),
8555 counterparty: ChannelCounterparty {
8556 features: channelmanager::provided_init_features(&UserConfig::default()),
8558 unspendable_punishment_reserve: 0,
8559 forwarding_info: None,
8560 outbound_htlc_minimum_msat: None,
8561 outbound_htlc_maximum_msat: None,
8563 funding_txo: Some(OutPoint {
8564 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8567 short_channel_id: Some(1),
8568 inbound_scid_alias: None,
8569 outbound_scid_alias: None,
8570 channel_value_satoshis: 10_000_000_000,
8572 balance_msat: 10_000_000_000,
8573 outbound_capacity_msat: 10_000_000_000,
8574 next_outbound_htlc_minimum_msat: 0,
8575 next_outbound_htlc_limit_msat: 10_000_000_000,
8576 inbound_capacity_msat: 0,
8577 unspendable_punishment_reserve: None,
8578 confirmations_required: None,
8579 confirmations: None,
8580 force_close_spend_delay: None,
8582 is_channel_ready: true,
8585 inbound_htlc_minimum_msat: None,
8586 inbound_htlc_maximum_msat: None,
8588 feerate_sat_per_1000_weight: None,
8589 channel_shutdown_state: Some(ChannelShutdownState::NotShuttingDown),
8590 pending_inbound_htlcs: Vec::new(),
8591 pending_outbound_htlcs: Vec::new(),
8595 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8596 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8597 starting_amount: u64, route_count: usize,
8598 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8599 let payer = payer_pubkey();
8600 let random_seed_bytes = [42; 32];
8602 let nodes = graph.read_only().nodes().clone();
8603 let mut route_endpoints = Vec::new();
8604 for _ in 0..route_count {
8606 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8607 let src = PublicKey::from_slice(nodes.unordered_keys()
8608 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8609 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8610 let dst = PublicKey::from_slice(nodes.unordered_keys()
8611 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8612 let params = PaymentParameters::from_node_id(dst, 42)
8613 .with_bolt11_features(features.clone()).unwrap();
8614 let first_hop = first_hop(src);
8615 let amt_msat = starting_amount + seed % 1_000_000;
8616 let route_params = RouteParameters::from_payment_params_and_value(
8617 params.clone(), amt_msat);
8619 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8620 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8622 route_endpoints.push((first_hop, params, amt_msat));
8635 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8636 use crate::ln::channelmanager;
8637 use crate::ln::features::Bolt11InvoiceFeatures;
8638 use crate::routing::gossip::NetworkGraph;
8639 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScoringFeeParameters};
8640 use crate::util::config::UserConfig;
8641 use crate::util::logger::{Logger, Record};
8642 use crate::util::test_utils::TestLogger;
8644 use criterion::Criterion;
8646 struct DummyLogger {}
8647 impl Logger for DummyLogger {
8648 fn log(&self, _record: Record) {}
8651 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8652 let logger = TestLogger::new();
8653 let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap();
8654 let scorer = FixedPenaltyScorer::with_penalty(0);
8655 generate_routes(bench, &network_graph, scorer, &Default::default(),
8656 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8659 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8660 let logger = TestLogger::new();
8661 let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap();
8662 let scorer = FixedPenaltyScorer::with_penalty(0);
8663 generate_routes(bench, &network_graph, scorer, &Default::default(),
8664 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8665 "generate_mpp_routes_with_zero_penalty_scorer");
8668 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8669 let logger = TestLogger::new();
8670 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8671 let params = ProbabilisticScoringFeeParameters::default();
8672 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8673 "generate_routes_with_probabilistic_scorer");
8676 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8677 let logger = TestLogger::new();
8678 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8679 let params = ProbabilisticScoringFeeParameters::default();
8680 generate_routes(bench, &network_graph, scorer, ¶ms,
8681 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8682 "generate_mpp_routes_with_probabilistic_scorer");
8685 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8686 let logger = TestLogger::new();
8687 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8688 let params = ProbabilisticScoringFeeParameters::default();
8689 generate_routes(bench, &network_graph, scorer, ¶ms,
8690 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8691 "generate_large_mpp_routes_with_probabilistic_scorer");
8694 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8695 let logger = TestLogger::new();
8696 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8697 let mut params = ProbabilisticScoringFeeParameters::default();
8698 params.linear_success_probability = false;
8699 generate_routes(bench, &network_graph, scorer, ¶ms,
8700 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8701 "generate_routes_with_nonlinear_probabilistic_scorer");
8704 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8705 let logger = TestLogger::new();
8706 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8707 let mut params = ProbabilisticScoringFeeParameters::default();
8708 params.linear_success_probability = false;
8709 generate_routes(bench, &network_graph, scorer, ¶ms,
8710 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8711 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8714 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8715 let logger = TestLogger::new();
8716 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8717 let mut params = ProbabilisticScoringFeeParameters::default();
8718 params.linear_success_probability = false;
8719 generate_routes(bench, &network_graph, scorer, ¶ms,
8720 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8721 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8724 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8725 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8726 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8727 bench_name: &'static str,
8729 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8730 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8732 // ...then benchmark finding paths between the nodes we learned.
8733 do_route_bench(bench, graph, scorer, score_params, bench_name, route_endpoints);
8737 fn do_route_bench<S: ScoreLookUp + ScoreUpdate>(
8738 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, scorer: S,
8739 score_params: &S::ScoreParams, bench_name: &'static str,
8740 route_endpoints: Vec<(ChannelDetails, PaymentParameters, u64)>,
8742 let payer = bench_utils::payer_pubkey();
8743 let random_seed_bytes = [42; 32];
8746 bench.bench_function(bench_name, |b| b.iter(|| {
8747 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8748 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8749 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8750 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());