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 // Limit to peers with announced channels unless the recipient is unannounced.
123 .filter(|details| network_graph
124 .node(&NodeId::from_pubkey(&details.counterparty.node_id))
125 .map(|node| !is_recipient_announced || node.channels.len() >= MIN_PEER_CHANNELS)
126 // Allow payments directly with the only peer when unannounced.
127 .unwrap_or(!is_recipient_announced && has_one_peer)
129 .filter_map(|details| {
130 let short_channel_id = match details.get_inbound_payment_scid() {
131 Some(short_channel_id) => short_channel_id,
134 let payment_relay: PaymentRelay = match details.counterparty.forwarding_info {
135 Some(forwarding_info) => match forwarding_info.try_into() {
136 Ok(payment_relay) => payment_relay,
137 Err(()) => return None,
142 let cltv_expiry_delta = payment_relay.cltv_expiry_delta as u32;
143 let payment_constraints = PaymentConstraints {
144 max_cltv_expiry: tlvs.payment_constraints.max_cltv_expiry + cltv_expiry_delta,
145 htlc_minimum_msat: details.inbound_htlc_minimum_msat.unwrap_or(0),
147 Some(payment::ForwardNode {
152 features: BlindedHopFeatures::empty(),
154 node_id: details.counterparty.node_id,
155 htlc_maximum_msat: details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX),
158 .map(|forward_node| {
159 BlindedPath::new_for_payment(
160 &[forward_node], recipient, tlvs.clone(), u64::MAX, MIN_FINAL_CLTV_EXPIRY_DELTA,
161 &*self.entropy_source, secp_ctx
164 .take(MAX_PAYMENT_PATHS)
165 .collect::<Result<Vec<_>, _>>();
168 Ok(paths) if !paths.is_empty() => Ok(paths),
170 if network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient)) {
171 BlindedPath::one_hop_for_payment(
172 recipient, tlvs, MIN_FINAL_CLTV_EXPIRY_DELTA, &*self.entropy_source, secp_ctx
173 ).map(|path| vec![path])
182 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
184 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
185 ES::Target: EntropySource,
188 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
189 ) -> Result<OnionMessagePath, ()> {
190 self.message_router.find_path(sender, peers, destination)
193 fn create_blinded_paths<
194 T: secp256k1::Signing + secp256k1::Verification
196 &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
197 ) -> Result<Vec<BlindedPath>, ()> {
198 self.message_router.create_blinded_paths(recipient, peers, secp_ctx)
201 fn create_compact_blinded_paths<
202 T: secp256k1::Signing + secp256k1::Verification
204 &self, recipient: PublicKey, peers: Vec<message::ForwardNode>, secp_ctx: &Secp256k1<T>,
205 ) -> Result<Vec<BlindedPath>, ()> {
206 self.message_router.create_compact_blinded_paths(recipient, peers, secp_ctx)
210 /// A trait defining behavior for routing a payment.
211 pub trait Router: MessageRouter {
212 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
214 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
215 /// and [`RouteParameters::final_value_msat`], respectively.
217 &self, payer: &PublicKey, route_params: &RouteParameters,
218 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
219 ) -> Result<Route, LightningError>;
221 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
223 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
224 /// and [`RouteParameters::final_value_msat`], respectively.
226 /// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
228 fn find_route_with_id(
229 &self, payer: &PublicKey, route_params: &RouteParameters,
230 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
231 _payment_hash: PaymentHash, _payment_id: PaymentId
232 ) -> Result<Route, LightningError> {
233 self.find_route(payer, route_params, first_hops, inflight_htlcs)
236 /// Creates [`BlindedPath`]s for payment to the `recipient` node. The channels in `first_hops`
237 /// are assumed to be with the `recipient`'s peers. The payment secret and any constraints are
239 fn create_blinded_payment_paths<
240 T: secp256k1::Signing + secp256k1::Verification
242 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
243 amount_msats: u64, secp_ctx: &Secp256k1<T>
244 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()>;
247 /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
249 /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
252 /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
253 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> where S::Target: ScoreLookUp {
255 // Maps a channel's short channel id and its direction to the liquidity used up.
256 inflight_htlcs: &'a InFlightHtlcs,
258 impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
259 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
260 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
261 ScorerAccountingForInFlightHtlcs {
268 impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
269 type ScoreParams = <S::Target as ScoreLookUp>::ScoreParams;
270 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
271 let target = match candidate.target() {
272 Some(target) => target,
273 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
275 let short_channel_id = match candidate.short_channel_id() {
276 Some(short_channel_id) => short_channel_id,
277 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
279 let source = candidate.source();
280 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
281 &source, &target, short_channel_id
283 let usage = ChannelUsage {
284 inflight_htlc_msat: usage.inflight_htlc_msat.saturating_add(used_liquidity),
288 self.scorer.channel_penalty_msat(candidate, usage, score_params)
290 self.scorer.channel_penalty_msat(candidate, usage, score_params)
295 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
296 /// in-use channel liquidity.
298 pub struct InFlightHtlcs(
299 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
300 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
301 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
303 HashMap<(u64, bool), u64>
307 /// Constructs an empty `InFlightHtlcs`.
308 pub fn new() -> Self { InFlightHtlcs(new_hash_map()) }
310 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
311 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
312 if path.hops.is_empty() { return };
314 let mut cumulative_msat = 0;
315 if let Some(tail) = &path.blinded_tail {
316 cumulative_msat += tail.final_value_msat;
319 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
320 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
321 // the router excludes the payer node. In the following lines, the payer's information is
322 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
323 // in our sliding window of two.
324 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
325 .map(|hop| hop.pubkey)
326 .chain(core::iter::once(payer_node_id));
328 // Taking the reversed vector from above, we zip it with just the reversed hops list to
329 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
330 // the total amount sent.
331 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
332 cumulative_msat += next_hop.fee_msat;
334 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
335 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
336 .or_insert(cumulative_msat);
340 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
342 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
344 .entry((channel_scid, source < target))
345 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
346 .or_insert(used_msat);
349 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
351 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
352 self.0.get(&(channel_scid, source < target)).map(|v| *v)
356 impl Writeable for InFlightHtlcs {
357 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
360 impl Readable for InFlightHtlcs {
361 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
362 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
363 Ok(Self(infight_map))
367 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
368 /// that leads to it.
369 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
370 pub struct RouteHop {
371 /// The node_id of the node at this hop.
372 pub pubkey: PublicKey,
373 /// The node_announcement features of the node at this hop. For the last hop, these may be
374 /// amended to match the features present in the invoice this node generated.
375 pub node_features: NodeFeatures,
376 /// The channel that should be used from the previous hop to reach this node.
377 pub short_channel_id: u64,
378 /// The channel_announcement features of the channel that should be used from the previous hop
379 /// to reach this node.
380 pub channel_features: ChannelFeatures,
381 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
382 /// If this is the last hop in [`Path::hops`]:
383 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
384 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
386 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
388 /// The CLTV delta added for this hop.
389 /// If this is the last hop in [`Path::hops`]:
390 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
391 /// * otherwise, this is the CLTV delta expected at the destination
393 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
394 pub cltv_expiry_delta: u32,
395 /// Indicates whether this hop is possibly announced in the public network graph.
397 /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
398 /// either know for sure it's announced in the public graph, or if any public channels exist
399 /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
400 /// the channel to be unannounced.
402 /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
403 pub maybe_announced_channel: bool,
406 impl_writeable_tlv_based!(RouteHop, {
407 (0, pubkey, required),
408 (1, maybe_announced_channel, (default_value, true)),
409 (2, node_features, required),
410 (4, short_channel_id, required),
411 (6, channel_features, required),
412 (8, fee_msat, required),
413 (10, cltv_expiry_delta, required),
416 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
417 /// their [`Bolt12Invoice`].
419 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
420 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
421 pub struct BlindedTail {
422 /// The hops of the [`BlindedPath`] provided by the recipient.
424 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
425 pub hops: Vec<BlindedHop>,
426 /// The blinding point of the [`BlindedPath`] provided by the recipient.
428 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
429 pub blinding_point: PublicKey,
430 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
431 /// inferring the destination. May be 0.
432 pub excess_final_cltv_expiry_delta: u32,
433 /// The total amount paid on this [`Path`], excluding the fees.
434 pub final_value_msat: u64,
437 impl_writeable_tlv_based!(BlindedTail, {
438 (0, hops, required_vec),
439 (2, blinding_point, required),
440 (4, excess_final_cltv_expiry_delta, required),
441 (6, final_value_msat, required),
444 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
445 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
446 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
448 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
449 pub hops: Vec<RouteHop>,
450 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
451 pub blinded_tail: Option<BlindedTail>,
455 /// Gets the fees for a given path, excluding any excess paid to the recipient.
456 pub fn fee_msat(&self) -> u64 {
457 match &self.blinded_tail {
458 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
460 // Do not count last hop of each path since that's the full value of the payment
461 self.hops.split_last().map_or(0,
462 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
467 /// Gets the total amount paid on this [`Path`], excluding the fees.
468 pub fn final_value_msat(&self) -> u64 {
469 match &self.blinded_tail {
470 Some(blinded_tail) => blinded_tail.final_value_msat,
471 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
475 /// Gets the final hop's CLTV expiry delta.
476 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
477 match &self.blinded_tail {
479 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
484 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
485 /// it can take multiple paths. Each path is composed of one or more hops through the network.
486 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
488 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
489 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
491 pub paths: Vec<Path>,
492 /// The `route_params` parameter passed to [`find_route`].
494 /// This is used by `ChannelManager` to track information which may be required for retries.
496 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
497 pub route_params: Option<RouteParameters>,
501 /// Returns the total amount of fees paid on this [`Route`].
503 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
504 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
505 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
507 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
508 pub fn get_total_fees(&self) -> u64 {
509 let overpaid_value_msat = self.route_params.as_ref()
510 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
511 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
514 /// Returns the total amount paid on this [`Route`], excluding the fees.
516 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
517 /// we had to reach the [`htlc_minimum_msat`] limits.
519 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
520 pub fn get_total_amount(&self) -> u64 {
521 self.paths.iter().map(|path| path.final_value_msat()).sum()
525 impl fmt::Display for Route {
526 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
527 log_route!(self).fmt(f)
531 const SERIALIZATION_VERSION: u8 = 1;
532 const MIN_SERIALIZATION_VERSION: u8 = 1;
534 impl Writeable for Route {
535 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
536 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
537 (self.paths.len() as u64).write(writer)?;
538 let mut blinded_tails = Vec::new();
539 for (idx, path) in self.paths.iter().enumerate() {
540 (path.hops.len() as u8).write(writer)?;
541 for hop in path.hops.iter() {
544 if let Some(blinded_tail) = &path.blinded_tail {
545 if blinded_tails.is_empty() {
546 blinded_tails = Vec::with_capacity(path.hops.len());
548 blinded_tails.push(None);
551 blinded_tails.push(Some(blinded_tail));
552 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
554 write_tlv_fields!(writer, {
555 // For compatibility with LDK versions prior to 0.0.117, we take the individual
556 // RouteParameters' fields and reconstruct them on read.
557 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
558 (2, blinded_tails, optional_vec),
559 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
560 (5, self.route_params.as_ref().and_then(|p| p.max_total_routing_fee_msat), option),
566 impl Readable for Route {
567 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
568 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
569 let path_count: u64 = Readable::read(reader)?;
570 if path_count == 0 { return Err(DecodeError::InvalidValue); }
571 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
572 let mut min_final_cltv_expiry_delta = u32::max_value();
573 for _ in 0..path_count {
574 let hop_count: u8 = Readable::read(reader)?;
575 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
576 for _ in 0..hop_count {
577 hops.push(Readable::read(reader)?);
579 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
580 min_final_cltv_expiry_delta =
581 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
582 paths.push(Path { hops, blinded_tail: None });
584 _init_and_read_len_prefixed_tlv_fields!(reader, {
585 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
586 (2, blinded_tails, optional_vec),
587 (3, final_value_msat, option),
588 (5, max_total_routing_fee_msat, option)
590 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
591 if blinded_tails.len() != 0 {
592 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
593 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
594 path.blinded_tail = blinded_tail_opt;
598 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
599 let route_params = match (payment_params, final_value_msat) {
600 (Some(payment_params), Some(final_value_msat)) => {
601 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
606 Ok(Route { paths, route_params })
610 /// Parameters needed to find a [`Route`].
612 /// Passed to [`find_route`] and [`build_route_from_hops`].
613 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
614 pub struct RouteParameters {
615 /// The parameters of the failed payment path.
616 pub payment_params: PaymentParameters,
618 /// The amount in msats sent on the failed payment path.
619 pub final_value_msat: u64,
621 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
623 /// This limit also applies to the total fees that may arise while retrying failed payment
626 /// Note that values below a few sats may result in some paths being spuriously ignored.
627 pub max_total_routing_fee_msat: Option<u64>,
630 impl RouteParameters {
631 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
633 /// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
634 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
635 Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
638 /// Sets the maximum number of hops that can be included in a payment path, based on the provided
639 /// [`RecipientOnionFields`] and blinded paths.
640 pub fn set_max_path_length(
641 &mut self, recipient_onion: &RecipientOnionFields, is_keysend: bool, best_block_height: u32
642 ) -> Result<(), ()> {
643 let keysend_preimage_opt = is_keysend.then(|| PaymentPreimage([42; 32]));
644 onion_utils::set_max_path_length(
645 self, recipient_onion, keysend_preimage_opt, best_block_height
650 impl Writeable for RouteParameters {
651 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
652 write_tlv_fields!(writer, {
653 (0, self.payment_params, required),
654 (1, self.max_total_routing_fee_msat, option),
655 (2, self.final_value_msat, required),
656 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
657 // `RouteParameters` directly. For compatibility, we write it here.
658 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
664 impl Readable for RouteParameters {
665 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
666 _init_and_read_len_prefixed_tlv_fields!(reader, {
667 (0, payment_params, (required: ReadableArgs, 0)),
668 (1, max_total_routing_fee_msat, option),
669 (2, final_value_msat, required),
670 (4, final_cltv_delta, option),
672 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
673 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
674 if final_cltv_expiry_delta == &0 {
675 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
680 final_value_msat: final_value_msat.0.unwrap(),
681 max_total_routing_fee_msat,
686 /// Maximum total CTLV difference we allow for a full payment path.
687 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
689 /// Maximum number of paths we allow an (MPP) payment to have.
690 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
691 // limits, but for now more than 10 paths likely carries too much one-path failure.
692 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
694 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
696 // The median hop CLTV expiry delta currently seen in the network.
697 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
699 /// Estimated maximum number of hops that can be included in a payment path. May be inaccurate if
700 /// payment metadata, custom TLVs, or blinded paths are included in the payment.
701 // During routing, we only consider paths shorter than our maximum length estimate.
702 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
703 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
704 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
706 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
707 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
708 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
709 // (payment_secret and total_msat) = 93 bytes for the final hop.
710 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
711 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
712 pub const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
714 /// Information used to route a payment.
715 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
716 pub struct PaymentParameters {
717 /// Information about the payee, such as their features and route hints for their channels.
720 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
721 pub expiry_time: Option<u64>,
723 /// The maximum total CLTV delta we accept for the route.
724 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
725 pub max_total_cltv_expiry_delta: u32,
727 /// The maximum number of paths that may be used by (MPP) payments.
728 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
729 pub max_path_count: u8,
731 /// The maximum number of [`Path::hops`] in any returned path.
732 /// Defaults to [`MAX_PATH_LENGTH_ESTIMATE`].
733 pub max_path_length: u8,
735 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
736 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
737 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
738 /// increasing failure probability for those paths.
740 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
741 /// restriction have been found. While paths which meet this criteria will be searched for, it
742 /// is ultimately up to the scorer to select them over other paths.
744 /// A value of 0 will allow payments up to and including a channel's total announced usable
745 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
748 pub max_channel_saturation_power_of_half: u8,
750 /// A list of SCIDs which this payment was previously attempted over and which caused the
751 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
753 pub previously_failed_channels: Vec<u64>,
755 /// A list of indices corresponding to blinded paths in [`Payee::Blinded::route_hints`] which this
756 /// payment was previously attempted over and which caused the payment to fail. Future attempts
757 /// for the same payment shouldn't be relayed through any of these blinded paths.
758 pub previously_failed_blinded_path_idxs: Vec<u64>,
761 impl Writeable for PaymentParameters {
762 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
763 let mut clear_hints = &vec![];
764 let mut blinded_hints = &vec![];
766 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
767 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
769 write_tlv_fields!(writer, {
770 (0, self.payee.node_id(), option),
771 (1, self.max_total_cltv_expiry_delta, required),
772 (2, self.payee.features(), option),
773 (3, self.max_path_count, required),
774 (4, *clear_hints, required_vec),
775 (5, self.max_channel_saturation_power_of_half, required),
776 (6, self.expiry_time, option),
777 (7, self.previously_failed_channels, required_vec),
778 (8, *blinded_hints, optional_vec),
779 (9, self.payee.final_cltv_expiry_delta(), option),
780 (11, self.previously_failed_blinded_path_idxs, required_vec),
781 (13, self.max_path_length, required),
787 impl ReadableArgs<u32> for PaymentParameters {
788 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
789 _init_and_read_len_prefixed_tlv_fields!(reader, {
790 (0, payee_pubkey, option),
791 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
792 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
793 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
794 (4, clear_route_hints, required_vec),
795 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
796 (6, expiry_time, option),
797 (7, previously_failed_channels, optional_vec),
798 (8, blinded_route_hints, optional_vec),
799 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
800 (11, previously_failed_blinded_path_idxs, optional_vec),
801 (13, max_path_length, (default_value, MAX_PATH_LENGTH_ESTIMATE)),
803 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
804 let payee = if blinded_route_hints.len() != 0 {
805 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
807 route_hints: blinded_route_hints,
808 features: features.and_then(|f: Features| f.bolt12()),
812 route_hints: clear_route_hints,
813 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
814 features: features.and_then(|f| f.bolt11()),
815 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
819 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
820 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
822 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
824 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
825 previously_failed_blinded_path_idxs: previously_failed_blinded_path_idxs.unwrap_or(Vec::new()),
826 max_path_length: _init_tlv_based_struct_field!(max_path_length, (default_value, unused)),
832 impl PaymentParameters {
833 /// Creates a payee with the node id of the given `pubkey`.
835 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
837 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
839 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
841 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
842 max_path_count: DEFAULT_MAX_PATH_COUNT,
843 max_path_length: MAX_PATH_LENGTH_ESTIMATE,
844 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
845 previously_failed_channels: Vec::new(),
846 previously_failed_blinded_path_idxs: Vec::new(),
850 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
852 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
855 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
856 /// whether your router will be allowed to find a multi-part route for this payment. If you
857 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
858 /// [`RecipientOnionFields::secret_only`].
860 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
861 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
862 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
863 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
864 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
867 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
868 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
869 /// [`PaymentParameters::expiry_time`].
870 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
871 Self::blinded(invoice.payment_paths().to_vec())
872 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
873 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
876 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
877 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
879 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
881 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
882 max_path_count: DEFAULT_MAX_PATH_COUNT,
883 max_path_length: MAX_PATH_LENGTH_ESTIMATE,
884 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
885 previously_failed_channels: Vec::new(),
886 previously_failed_blinded_path_idxs: Vec::new(),
890 /// Includes the payee's features. Errors if the parameters were not initialized with
891 /// [`PaymentParameters::from_bolt12_invoice`].
893 /// This is not exported to bindings users since bindings don't support move semantics
894 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
896 Payee::Clear { .. } => Err(()),
897 Payee::Blinded { route_hints, .. } =>
898 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
902 /// Includes the payee's features. Errors if the parameters were initialized with
903 /// [`PaymentParameters::from_bolt12_invoice`].
905 /// This is not exported to bindings users since bindings don't support move semantics
906 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
908 Payee::Blinded { .. } => Err(()),
909 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
911 payee: Payee::Clear {
912 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
918 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
919 /// [`PaymentParameters::from_bolt12_invoice`].
921 /// This is not exported to bindings users since bindings don't support move semantics
922 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
924 Payee::Blinded { .. } => Err(()),
925 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
927 payee: Payee::Clear {
928 route_hints, node_id, features, final_cltv_expiry_delta,
934 /// Includes a payment expiration in seconds relative to the UNIX epoch.
936 /// This is not exported to bindings users since bindings don't support move semantics
937 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
938 Self { expiry_time: Some(expiry_time), ..self }
941 /// Includes a limit for the total CLTV expiry delta which is considered during routing
943 /// This is not exported to bindings users since bindings don't support move semantics
944 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
945 Self { max_total_cltv_expiry_delta, ..self }
948 /// Includes a limit for the maximum number of payment paths that may be used.
950 /// This is not exported to bindings users since bindings don't support move semantics
951 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
952 Self { max_path_count, ..self }
955 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
956 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
958 /// This is not exported to bindings users since bindings don't support move semantics
959 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
960 Self { max_channel_saturation_power_of_half, ..self }
963 pub(crate) fn insert_previously_failed_blinded_path(&mut self, failed_blinded_tail: &BlindedTail) {
964 let mut found_blinded_tail = false;
965 for (idx, (_, path)) in self.payee.blinded_route_hints().iter().enumerate() {
966 if failed_blinded_tail.hops == path.blinded_hops &&
967 failed_blinded_tail.blinding_point == path.blinding_point
969 self.previously_failed_blinded_path_idxs.push(idx as u64);
970 found_blinded_tail = true;
973 debug_assert!(found_blinded_tail);
977 /// The recipient of a payment, differing based on whether they've hidden their identity with route
979 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
981 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
982 /// will be included in the final [`Route`].
984 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
986 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
987 /// Features supported by the payee.
989 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
991 features: Option<Bolt12InvoiceFeatures>,
993 /// The recipient included these route hints in their BOLT11 invoice.
995 /// The node id of the payee.
997 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
998 route_hints: Vec<RouteHint>,
999 /// Features supported by the payee.
1001 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
1002 /// does not contain any features.
1004 /// [`for_keysend`]: PaymentParameters::for_keysend
1005 features: Option<Bolt11InvoiceFeatures>,
1006 /// The minimum CLTV delta at the end of the route. This value must not be zero.
1007 final_cltv_expiry_delta: u32,
1012 fn node_id(&self) -> Option<PublicKey> {
1014 Self::Clear { node_id, .. } => Some(*node_id),
1018 fn node_features(&self) -> Option<NodeFeatures> {
1020 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
1021 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
1024 fn supports_basic_mpp(&self) -> bool {
1026 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
1027 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
1030 fn features(&self) -> Option<FeaturesRef> {
1032 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
1033 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
1036 fn final_cltv_expiry_delta(&self) -> Option<u32> {
1038 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
1042 pub(crate) fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
1044 Self::Blinded { route_hints, .. } => &route_hints[..],
1045 Self::Clear { .. } => &[]
1049 pub(crate) fn blinded_route_hints_mut(&mut self) -> &mut [(BlindedPayInfo, BlindedPath)] {
1051 Self::Blinded { route_hints, .. } => &mut route_hints[..],
1052 Self::Clear { .. } => &mut []
1056 fn unblinded_route_hints(&self) -> &[RouteHint] {
1058 Self::Blinded { .. } => &[],
1059 Self::Clear { route_hints, .. } => &route_hints[..]
1064 enum FeaturesRef<'a> {
1065 Bolt11(&'a Bolt11InvoiceFeatures),
1066 Bolt12(&'a Bolt12InvoiceFeatures),
1069 Bolt11(Bolt11InvoiceFeatures),
1070 Bolt12(Bolt12InvoiceFeatures),
1074 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
1076 Self::Bolt12(f) => Some(f),
1080 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
1082 Self::Bolt11(f) => Some(f),
1088 impl<'a> Writeable for FeaturesRef<'a> {
1089 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1091 Self::Bolt11(f) => Ok(f.write(w)?),
1092 Self::Bolt12(f) => Ok(f.write(w)?),
1097 impl ReadableArgs<bool> for Features {
1098 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
1099 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
1100 Ok(Self::Bolt12(Readable::read(reader)?))
1104 /// A list of hops along a payment path terminating with a channel to the recipient.
1105 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1106 pub struct RouteHint(pub Vec<RouteHintHop>);
1108 impl Writeable for RouteHint {
1109 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1110 (self.0.len() as u64).write(writer)?;
1111 for hop in self.0.iter() {
1118 impl Readable for RouteHint {
1119 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1120 let hop_count: u64 = Readable::read(reader)?;
1121 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
1122 for _ in 0..hop_count {
1123 hops.push(Readable::read(reader)?);
1129 /// A channel descriptor for a hop along a payment path.
1131 /// While this generally comes from BOLT 11's `r` field, this struct includes more fields than are
1132 /// available in BOLT 11. Thus, encoding and decoding this via `lightning-invoice` is lossy, as
1133 /// fields not supported in BOLT 11 will be stripped.
1134 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1135 pub struct RouteHintHop {
1136 /// The node_id of the non-target end of the route
1137 pub src_node_id: PublicKey,
1138 /// The short_channel_id of this channel
1139 pub short_channel_id: u64,
1140 /// The fees which must be paid to use this channel
1141 pub fees: RoutingFees,
1142 /// The difference in CLTV values between this node and the next node.
1143 pub cltv_expiry_delta: u16,
1144 /// The minimum value, in msat, which must be relayed to the next hop.
1145 pub htlc_minimum_msat: Option<u64>,
1146 /// The maximum value in msat available for routing with a single HTLC.
1147 pub htlc_maximum_msat: Option<u64>,
1150 impl_writeable_tlv_based!(RouteHintHop, {
1151 (0, src_node_id, required),
1152 (1, htlc_minimum_msat, option),
1153 (2, short_channel_id, required),
1154 (3, htlc_maximum_msat, option),
1155 (4, fees, required),
1156 (6, cltv_expiry_delta, required),
1159 #[derive(Eq, PartialEq)]
1160 #[repr(align(64))] // Force the size to 64 bytes
1161 struct RouteGraphNode {
1164 // The maximum value a yet-to-be-constructed payment path might flow through this node.
1165 // This value is upper-bounded by us by:
1166 // - how much is needed for a path being constructed
1167 // - how much value can channels following this node (up to the destination) can contribute,
1168 // considering their capacity and fees
1169 value_contribution_msat: u64,
1170 total_cltv_delta: u32,
1171 /// The number of hops walked up to this node.
1172 path_length_to_node: u8,
1175 impl cmp::Ord for RouteGraphNode {
1176 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
1177 other.score.cmp(&self.score).then_with(|| other.node_id.cmp(&self.node_id))
1181 impl cmp::PartialOrd for RouteGraphNode {
1182 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
1183 Some(self.cmp(other))
1187 // While RouteGraphNode can be laid out with fewer bytes, performance appears to be improved
1188 // substantially when it is laid out at exactly 64 bytes.
1190 // Thus, we use `#[repr(C)]` on the struct to force a suboptimal layout and check that it stays 64
1192 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1193 const _GRAPH_NODE_SMALL: usize = 64 - core::mem::size_of::<RouteGraphNode>();
1194 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1195 const _GRAPH_NODE_FIXED_SIZE: usize = core::mem::size_of::<RouteGraphNode>() - 64;
1197 /// A [`CandidateRouteHop::FirstHop`] entry.
1198 #[derive(Clone, Debug)]
1199 pub struct FirstHopCandidate<'a> {
1200 /// Channel details of the first hop
1202 /// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1203 /// has been funded and is able to pay), and accessor methods may panic otherwise.
1205 /// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1207 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1208 pub details: &'a ChannelDetails,
1209 /// The node id of the payer, which is also the source side of this candidate route hop.
1211 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1212 pub payer_node_id: &'a NodeId,
1215 /// A [`CandidateRouteHop::PublicHop`] entry.
1216 #[derive(Clone, Debug)]
1217 pub struct PublicHopCandidate<'a> {
1218 /// Information about the channel, including potentially its capacity and
1219 /// direction-specific information.
1221 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1222 pub info: DirectedChannelInfo<'a>,
1223 /// The short channel ID of the channel, i.e. the identifier by which we refer to this
1225 pub short_channel_id: u64,
1228 /// A [`CandidateRouteHop::PrivateHop`] entry.
1229 #[derive(Clone, Debug)]
1230 pub struct PrivateHopCandidate<'a> {
1231 /// Information about the private hop communicated via BOLT 11.
1233 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1234 pub hint: &'a RouteHintHop,
1235 /// Node id of the next hop in BOLT 11 route hint.
1237 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1238 pub target_node_id: &'a NodeId
1241 /// A [`CandidateRouteHop::Blinded`] entry.
1242 #[derive(Clone, Debug)]
1243 pub struct BlindedPathCandidate<'a> {
1244 /// The node id of the introduction node, resolved from either the [`NetworkGraph`] or first
1247 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1248 pub source_node_id: &'a NodeId,
1249 /// Information about the blinded path including the fee, HTLC amount limits, and
1250 /// cryptographic material required to build an HTLC through the given path.
1252 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1253 pub hint: &'a (BlindedPayInfo, BlindedPath),
1254 /// Index of the hint in the original list of blinded hints.
1256 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1257 /// a short channel ID for this hop.
1261 /// A [`CandidateRouteHop::OneHopBlinded`] entry.
1262 #[derive(Clone, Debug)]
1263 pub struct OneHopBlindedPathCandidate<'a> {
1264 /// The node id of the introduction node, resolved from either the [`NetworkGraph`] or first
1267 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1268 pub source_node_id: &'a NodeId,
1269 /// Information about the blinded path including the fee, HTLC amount limits, and
1270 /// cryptographic material required to build an HTLC terminating with the given path.
1272 /// Note that the [`BlindedPayInfo`] is ignored here.
1274 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1275 pub hint: &'a (BlindedPayInfo, BlindedPath),
1276 /// Index of the hint in the original list of blinded hints.
1278 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1279 /// a short channel ID for this hop.
1283 /// A wrapper around the various hop representations.
1285 /// Can be used to examine the properties of a hop,
1286 /// potentially to decide whether to include it in a route.
1287 #[derive(Clone, Debug)]
1288 pub enum CandidateRouteHop<'a> {
1289 /// A hop from the payer, where the outbound liquidity is known.
1290 FirstHop(FirstHopCandidate<'a>),
1291 /// A hop found in the [`ReadOnlyNetworkGraph`].
1292 PublicHop(PublicHopCandidate<'a>),
1293 /// A private hop communicated by the payee, generally via a BOLT 11 invoice.
1295 /// Because BOLT 11 route hints can take multiple hops to get to the destination, this may not
1296 /// terminate at the payee.
1297 PrivateHop(PrivateHopCandidate<'a>),
1298 /// A blinded path which starts with an introduction point and ultimately terminates with the
1301 /// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1302 /// `None` in this state.
1304 /// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1305 /// path, the full path is treated as a single [`CandidateRouteHop`].
1306 Blinded(BlindedPathCandidate<'a>),
1307 /// Similar to [`Self::Blinded`], but the path here only has one hop.
1309 /// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1310 /// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1311 /// payee's identity - it's the introduction point!
1313 /// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1314 /// to the hops *between* the introduction node and the destination.
1316 /// This primarily exists to track that we need to included a blinded path at the end of our
1317 /// [`Route`], even though it doesn't actually add an additional hop in the payment.
1318 OneHopBlinded(OneHopBlindedPathCandidate<'a>),
1321 impl<'a> CandidateRouteHop<'a> {
1322 /// Returns the short channel ID for this hop, if one is known.
1324 /// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1325 /// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1327 /// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1328 /// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1329 /// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1330 /// (which is always true for channels which are funded and ready for use).
1332 /// In other words, this should always return `Some` as long as the candidate hop is not a
1333 /// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1335 /// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1336 /// define a global namespace.
1338 fn short_channel_id(&self) -> Option<u64> {
1340 CandidateRouteHop::FirstHop(hop) => hop.details.get_outbound_payment_scid(),
1341 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1342 CandidateRouteHop::PrivateHop(hop) => Some(hop.hint.short_channel_id),
1343 CandidateRouteHop::Blinded(_) => None,
1344 CandidateRouteHop::OneHopBlinded(_) => None,
1348 /// Returns the globally unique short channel ID for this hop, if one is known.
1350 /// This only returns `Some` if the channel is public (either our own, or one we've learned
1351 /// from the public network graph), and thus the short channel ID we have for this channel is
1352 /// globally unique and identifies this channel in a global namespace.
1354 pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1356 CandidateRouteHop::FirstHop(hop) => if hop.details.is_public { hop.details.short_channel_id } else { None },
1357 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1358 CandidateRouteHop::PrivateHop(_) => None,
1359 CandidateRouteHop::Blinded(_) => None,
1360 CandidateRouteHop::OneHopBlinded(_) => None,
1364 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1365 fn features(&self) -> ChannelFeatures {
1367 CandidateRouteHop::FirstHop(hop) => hop.details.counterparty.features.to_context(),
1368 CandidateRouteHop::PublicHop(hop) => hop.info.channel().features.clone(),
1369 CandidateRouteHop::PrivateHop(_) => ChannelFeatures::empty(),
1370 CandidateRouteHop::Blinded(_) => ChannelFeatures::empty(),
1371 CandidateRouteHop::OneHopBlinded(_) => ChannelFeatures::empty(),
1375 /// Returns the required difference in HTLC CLTV expiry between the [`Self::source`] and the
1376 /// next-hop for an HTLC taking this hop.
1378 /// This is the time that the node(s) in this hop have to claim the HTLC on-chain if the
1379 /// next-hop goes on chain with a payment preimage.
1381 pub fn cltv_expiry_delta(&self) -> u32 {
1383 CandidateRouteHop::FirstHop(_) => 0,
1384 CandidateRouteHop::PublicHop(hop) => hop.info.direction().cltv_expiry_delta as u32,
1385 CandidateRouteHop::PrivateHop(hop) => hop.hint.cltv_expiry_delta as u32,
1386 CandidateRouteHop::Blinded(hop) => hop.hint.0.cltv_expiry_delta as u32,
1387 CandidateRouteHop::OneHopBlinded(_) => 0,
1391 /// Returns the minimum amount that can be sent over this hop, in millisatoshis.
1393 pub fn htlc_minimum_msat(&self) -> u64 {
1395 CandidateRouteHop::FirstHop(hop) => hop.details.next_outbound_htlc_minimum_msat,
1396 CandidateRouteHop::PublicHop(hop) => hop.info.direction().htlc_minimum_msat,
1397 CandidateRouteHop::PrivateHop(hop) => hop.hint.htlc_minimum_msat.unwrap_or(0),
1398 CandidateRouteHop::Blinded(hop) => hop.hint.0.htlc_minimum_msat,
1399 CandidateRouteHop::OneHopBlinded { .. } => 0,
1403 /// Returns the fees that must be paid to route an HTLC over this channel.
1405 pub fn fees(&self) -> RoutingFees {
1407 CandidateRouteHop::FirstHop(_) => RoutingFees {
1408 base_msat: 0, proportional_millionths: 0,
1410 CandidateRouteHop::PublicHop(hop) => hop.info.direction().fees,
1411 CandidateRouteHop::PrivateHop(hop) => hop.hint.fees,
1412 CandidateRouteHop::Blinded(hop) => {
1414 base_msat: hop.hint.0.fee_base_msat,
1415 proportional_millionths: hop.hint.0.fee_proportional_millionths
1418 CandidateRouteHop::OneHopBlinded(_) =>
1419 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1423 /// Fetch the effective capacity of this hop.
1425 /// Note that this may be somewhat expensive, so calls to this should be limited and results
1427 fn effective_capacity(&self) -> EffectiveCapacity {
1429 CandidateRouteHop::FirstHop(hop) => EffectiveCapacity::ExactLiquidity {
1430 liquidity_msat: hop.details.next_outbound_htlc_limit_msat,
1432 CandidateRouteHop::PublicHop(hop) => hop.info.effective_capacity(),
1433 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. }) =>
1434 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1435 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. }) =>
1436 EffectiveCapacity::Infinite,
1437 CandidateRouteHop::Blinded(hop) =>
1438 EffectiveCapacity::HintMaxHTLC { amount_msat: hop.hint.0.htlc_maximum_msat },
1439 CandidateRouteHop::OneHopBlinded(_) => EffectiveCapacity::Infinite,
1443 /// Returns an ID describing the given hop.
1445 /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1447 fn id(&self) -> CandidateHopId {
1449 CandidateRouteHop::Blinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1450 CandidateRouteHop::OneHopBlinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1451 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1454 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1456 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1462 fn blinded_hint_idx(&self) -> Option<usize> {
1464 Self::Blinded(BlindedPathCandidate { hint_idx, .. }) |
1465 Self::OneHopBlinded(OneHopBlindedPathCandidate { hint_idx, .. }) => {
1471 /// Returns the source node id of current hop.
1473 /// Source node id refers to the node forwarding the HTLC through this hop.
1475 /// For [`Self::FirstHop`] we return payer's node id.
1477 pub fn source(&self) -> NodeId {
1479 CandidateRouteHop::FirstHop(hop) => *hop.payer_node_id,
1480 CandidateRouteHop::PublicHop(hop) => *hop.info.source(),
1481 CandidateRouteHop::PrivateHop(hop) => hop.hint.src_node_id.into(),
1482 CandidateRouteHop::Blinded(hop) => *hop.source_node_id,
1483 CandidateRouteHop::OneHopBlinded(hop) => *hop.source_node_id,
1486 /// Returns the target node id of this hop, if known.
1488 /// Target node id refers to the node receiving the HTLC after this hop.
1490 /// For [`Self::Blinded`] we return `None` because the ultimate destination after the blinded
1491 /// path is unknown.
1493 /// For [`Self::OneHopBlinded`] we return `None` because the target is the same as the source,
1494 /// and such a return value would be somewhat nonsensical.
1496 pub fn target(&self) -> Option<NodeId> {
1498 CandidateRouteHop::FirstHop(hop) => Some(hop.details.counterparty.node_id.into()),
1499 CandidateRouteHop::PublicHop(hop) => Some(*hop.info.target()),
1500 CandidateRouteHop::PrivateHop(hop) => Some(*hop.target_node_id),
1501 CandidateRouteHop::Blinded(_) => None,
1502 CandidateRouteHop::OneHopBlinded(_) => None,
1507 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1509 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1511 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1512 /// isn't guaranteed to be unique at all.
1514 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1515 /// difficult-to-use API.
1516 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1517 enum CandidateHopId {
1518 /// Contains (scid, src_node_id < target_node_id)
1520 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1525 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1526 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1528 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1529 EffectiveCapacity::Infinite => u64::max_value(),
1530 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1531 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1532 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1533 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1534 // expected to have been generated from up-to-date capacity information.
1535 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1536 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1537 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1541 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1542 -> bool where I1::Item: PartialEq<I2::Item> {
1544 let a = iter_a.next();
1545 let b = iter_b.next();
1546 if a.is_none() && b.is_none() { return true; }
1547 if a.is_none() || b.is_none() { return false; }
1548 if a.unwrap().ne(&b.unwrap()) { return false; }
1552 /// It's useful to keep track of the hops associated with the fees required to use them,
1553 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1554 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1555 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1557 #[repr(C)] // Force fields to appear in the order we define them.
1558 struct PathBuildingHop<'a> {
1559 candidate: CandidateRouteHop<'a>,
1560 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1561 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1562 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1563 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1564 /// avoid processing them again.
1565 was_processed: bool,
1566 /// Used to compare channels when choosing the for routing.
1567 /// Includes paying for the use of a hop and the following hops, as well as
1568 /// an estimated cost of reaching this hop.
1569 /// Might get stale when fees are recomputed. Primarily for internal use.
1570 total_fee_msat: u64,
1571 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1572 /// walk and may be invalid thereafter.
1573 path_htlc_minimum_msat: u64,
1574 /// All penalties incurred from this channel on the way to the destination, as calculated using
1575 /// channel scoring.
1576 path_penalty_msat: u64,
1578 // The last 16 bytes are on the next cache line by default in glibc's malloc. Thus, we should
1579 // only place fields which are not hot there. Luckily, the next three fields are only read if
1580 // we end up on the selected path, and only in the final path layout phase, so we don't care
1581 // too much if reading them is slow.
1585 /// All the fees paid *after* this channel on the way to the destination
1586 next_hops_fee_msat: u64,
1587 /// Fee paid for the use of the current channel (see candidate.fees()).
1588 /// The value will be actually deducted from the counterparty balance on the previous link.
1589 hop_use_fee_msat: u64,
1591 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1592 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1593 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1594 // value_contribution_msat, which requires tracking it here. See comments below where it is
1595 // used for more info.
1596 value_contribution_msat: u64,
1599 // Checks that the entries in the `find_route` `dist` map fit in (exactly) two standard x86-64
1600 // cache lines. Sadly, they're not guaranteed to actually lie on a cache line (and in fact,
1601 // generally won't, because at least glibc's malloc will align to a nice, big, round
1602 // boundary...plus 16), but at least it will reduce the amount of data we'll need to load.
1604 // Note that these assertions only pass on somewhat recent rustc, and thus are gated on the
1607 const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::<(NodeId, PathBuildingHop)>();
1609 const _NODE_MAP_SIZE_EXACTLY_CACHE_LINES: usize = core::mem::size_of::<(NodeId, PathBuildingHop)>() - 128;
1611 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1612 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1613 let mut debug_struct = f.debug_struct("PathBuildingHop");
1615 .field("node_id", &self.candidate.target())
1616 .field("short_channel_id", &self.candidate.short_channel_id())
1617 .field("total_fee_msat", &self.total_fee_msat)
1618 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1619 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1620 .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)))
1621 .field("path_penalty_msat", &self.path_penalty_msat)
1622 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1623 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1624 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1625 let debug_struct = debug_struct
1626 .field("value_contribution_msat", &self.value_contribution_msat);
1627 debug_struct.finish()
1631 // Instantiated with a list of hops with correct data in them collected during path finding,
1632 // an instance of this struct should be further modified only via given methods.
1634 struct PaymentPath<'a> {
1635 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1638 impl<'a> PaymentPath<'a> {
1639 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1640 fn get_value_msat(&self) -> u64 {
1641 self.hops.last().unwrap().0.fee_msat
1644 fn get_path_penalty_msat(&self) -> u64 {
1645 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1648 fn get_total_fee_paid_msat(&self) -> u64 {
1649 if self.hops.len() < 1 {
1653 // Can't use next_hops_fee_msat because it gets outdated.
1654 for (i, (hop, _)) in self.hops.iter().enumerate() {
1655 if i != self.hops.len() - 1 {
1656 result += hop.fee_msat;
1662 fn get_cost_msat(&self) -> u64 {
1663 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1666 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1667 // to change fees may result in an inconsistency.
1669 // Sometimes we call this function right after constructing a path which is inconsistent in
1670 // that it the value being transferred has decreased while we were doing path finding, leading
1671 // to the fees being paid not lining up with the actual limits.
1673 // Note that this function is not aware of the available_liquidity limit, and thus does not
1674 // support increasing the value being transferred beyond what was selected during the initial
1677 // Returns the amount that this path contributes to the total payment value, which may be greater
1678 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1679 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1680 let mut extra_contribution_msat = 0;
1681 let mut total_fee_paid_msat = 0 as u64;
1682 for i in (0..self.hops.len()).rev() {
1683 let last_hop = i == self.hops.len() - 1;
1685 // For non-last-hop, this value will represent the fees paid on the current hop. It
1686 // will consist of the fees for the use of the next hop, and extra fees to match
1687 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1688 let mut cur_hop_fees_msat = 0;
1690 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1693 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1694 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1695 cur_hop.path_penalty_msat += extra_contribution_msat;
1696 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1697 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1698 // set it too high just to maliciously take more fees by exploiting this
1699 // match htlc_minimum_msat logic.
1700 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1701 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1702 // Note that there is a risk that *previous hops* (those closer to us, as we go
1703 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1705 // This might make us end up with a broken route, although this should be super-rare
1706 // in practice, both because of how healthy channels look like, and how we pick
1707 // channels in add_entry.
1708 // Also, this can't be exploited more heavily than *announce a free path and fail
1710 cur_hop_transferred_amount_msat += extra_fees_msat;
1712 // We remember and return the extra fees on the final hop to allow accounting for
1713 // them in the path's value contribution.
1715 extra_contribution_msat = extra_fees_msat;
1717 total_fee_paid_msat += extra_fees_msat;
1718 cur_hop_fees_msat += extra_fees_msat;
1723 // Final hop is a special case: it usually has just value_msat (by design), but also
1724 // it still could overpay for the htlc_minimum_msat.
1725 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1727 // Propagate updated fees for the use of the channels to one hop back, where they
1728 // will be actually paid (fee_msat). The last hop is handled above separately.
1729 cur_hop.fee_msat = cur_hop_fees_msat;
1732 // Fee for the use of the current hop which will be deducted on the previous hop.
1733 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1734 // this channel is free for us.
1736 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1737 cur_hop.hop_use_fee_msat = new_fee;
1738 total_fee_paid_msat += new_fee;
1740 // It should not be possible because this function is called only to reduce the
1741 // value. In that case, compute_fee was already called with the same fees for
1742 // larger amount and there was no overflow.
1747 value_msat + extra_contribution_msat
1752 /// Calculate the fees required to route the given amount over a channel with the given fees.
1753 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1754 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1755 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1759 /// Calculate the fees required to route the given amount over a channel with the given fees,
1760 /// saturating to [`u64::max_value`].
1761 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1762 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1763 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1764 .saturating_add(channel_fees.base_msat as u64)
1767 /// The default `features` we assume for a node in a route, when no `features` are known about that
1770 /// Default features are:
1771 /// * variable_length_onion_optional
1772 fn default_node_features() -> NodeFeatures {
1773 let mut features = NodeFeatures::empty();
1774 features.set_variable_length_onion_optional();
1778 struct LoggedPayeePubkey(Option<PublicKey>);
1779 impl fmt::Display for LoggedPayeePubkey {
1780 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1783 "payee node id ".fmt(f)?;
1787 "blinded payee".fmt(f)
1793 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1794 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1795 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1797 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1798 "blinded route hint with introduction node ".fmt(f)?;
1799 match &hint.1.introduction_node {
1800 IntroductionNode::NodeId(pubkey) => write!(f, "id {}", pubkey)?,
1801 IntroductionNode::DirectedShortChannelId(direction, scid) => {
1803 Direction::NodeOne => {
1804 write!(f, "one on channel with SCID {}", scid)?;
1806 Direction::NodeTwo => {
1807 write!(f, "two on channel with SCID {}", scid)?;
1812 " and blinding point ".fmt(f)?;
1813 hint.1.blinding_point.fmt(f)
1815 CandidateRouteHop::FirstHop(_) => {
1816 "first hop with SCID ".fmt(f)?;
1817 self.0.short_channel_id().unwrap().fmt(f)
1819 CandidateRouteHop::PrivateHop(_) => {
1820 "route hint with SCID ".fmt(f)?;
1821 self.0.short_channel_id().unwrap().fmt(f)
1825 self.0.short_channel_id().unwrap().fmt(f)
1832 fn sort_first_hop_channels(
1833 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1834 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1836 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1837 // most like to use.
1839 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1840 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1843 // Second, because simply always sorting in descending order would always use our largest
1844 // available outbound capacity, needlessly fragmenting our available channel capacities,
1845 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1846 // which have enough, but not too much, capacity for the payment.
1848 // Available outbound balances factor in liquidity already reserved for previously found paths.
1849 channels.sort_unstable_by(|chan_a, chan_b| {
1850 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1851 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1852 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1853 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1854 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1855 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1856 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1857 // Sort in descending order
1858 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1860 // Sort in ascending order
1861 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1866 /// Finds a route from us (payer) to the given target node (payee).
1868 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1869 /// in the given [`RouteParameters::payment_params`].
1870 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1872 /// Private routing paths between a public node and the target may be included in the `payee` field
1873 /// of [`RouteParameters::payment_params`].
1875 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1876 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1877 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1879 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1880 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1881 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1885 /// Panics if first_hops contains channels without `short_channel_id`s;
1886 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1888 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1889 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1890 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1891 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1892 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1893 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1894 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1895 ) -> Result<Route, LightningError>
1896 where L::Target: Logger, GL::Target: Logger {
1897 let graph_lock = network_graph.read_only();
1898 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1899 scorer, score_params, random_seed_bytes)?;
1900 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1904 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1905 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1906 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1907 _random_seed_bytes: &[u8; 32]
1908 ) -> Result<Route, LightningError>
1909 where L::Target: Logger {
1911 let payment_params = &route_params.payment_params;
1912 let max_path_length = core::cmp::min(payment_params.max_path_length, MAX_PATH_LENGTH_ESTIMATE);
1913 let final_value_msat = route_params.final_value_msat;
1914 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1915 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1916 // so use a dummy id for this in the blinded case.
1917 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1918 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1919 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1920 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1921 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1923 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1924 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1926 if our_node_id == maybe_dummy_payee_node_id {
1927 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1930 if final_value_msat > MAX_VALUE_MSAT {
1931 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1934 if final_value_msat == 0 {
1935 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1938 let introduction_node_id_cache = payment_params.payee.blinded_route_hints().iter()
1939 .map(|(_, path)| path.public_introduction_node_id(network_graph))
1940 .collect::<Vec<_>>();
1941 match &payment_params.payee {
1942 Payee::Clear { route_hints, node_id, .. } => {
1943 for route in route_hints.iter() {
1944 for hop in &route.0 {
1945 if hop.src_node_id == *node_id {
1946 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1951 Payee::Blinded { route_hints, .. } => {
1952 if introduction_node_id_cache.iter().all(|introduction_node_id| *introduction_node_id == Some(&our_node_id)) {
1953 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});
1955 for ((_, blinded_path), introduction_node_id) in route_hints.iter().zip(introduction_node_id_cache.iter()) {
1956 if blinded_path.blinded_hops.len() == 0 {
1957 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1958 } else if *introduction_node_id == Some(&our_node_id) {
1959 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1960 } else if blinded_path.blinded_hops.len() == 1 &&
1962 .iter().zip(introduction_node_id_cache.iter())
1963 .filter(|((_, p), _)| p.blinded_hops.len() == 1)
1964 .any(|(_, p_introduction_node_id)| p_introduction_node_id != introduction_node_id)
1966 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1971 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1972 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1973 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});
1976 // The general routing idea is the following:
1977 // 1. Fill first/last hops communicated by the caller.
1978 // 2. Attempt to construct a path from payer to payee for transferring
1979 // any ~sufficient (described later) value.
1980 // If succeed, remember which channels were used and how much liquidity they have available,
1981 // so that future paths don't rely on the same liquidity.
1982 // 3. Proceed to the next step if:
1983 // - we hit the recommended target value;
1984 // - OR if we could not construct a new path. Any next attempt will fail too.
1985 // Otherwise, repeat step 2.
1986 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1987 // (not recommended value).
1988 // 5. If yes, proceed. If not, fail routing.
1989 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1990 // transferred up to the transfer target value.
1991 // 7. Reduce the value of the last path until we are sending only the target value.
1992 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1993 // them so that we're not sending two HTLCs along the same path.
1995 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1996 // distance from the payee
1998 // We are not a faithful Dijkstra's implementation because we can change values which impact
1999 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
2000 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
2001 // the value we are currently attempting to send over a path, we simply reduce the value being
2002 // sent along the path for any hops after that channel. This may imply that later fees (which
2003 // we've already tabulated) are lower because a smaller value is passing through the channels
2004 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
2005 // channels which were selected earlier (and which may still be used for other paths without a
2006 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
2009 // One potentially problematic case for this algorithm would be if there are many
2010 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
2011 // graph walking), we may never find a path which is not liquidity-limited and has lower
2012 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
2013 // Because we only consider paths with at least 5% of the total value being sent, the damage
2014 // from such a case should be limited, however this could be further reduced in the future by
2015 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
2016 // limits for the purposes of fee calculation.
2018 // Alternatively, we could store more detailed path information in the heap (targets, below)
2019 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
2020 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
2021 // and practically (as we would need to store dynamically-allocated path information in heap
2022 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
2023 // results of such an algorithm would likely be biased towards lower-value paths.
2025 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
2026 // outside of our current search value, running a path search more times to gather candidate
2027 // paths at different values. While this may be acceptable, further path searches may increase
2028 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
2029 // graph for candidate paths, calculating the maximum value which can realistically be sent at
2030 // the same time, remaining generic across different payment values.
2032 let network_channels = network_graph.channels();
2033 let network_nodes = network_graph.nodes();
2035 if payment_params.max_path_count == 0 {
2036 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
2039 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
2040 // it. If the payee supports it they're supposed to include it in the invoice, so that should
2042 let allow_mpp = if payment_params.max_path_count == 1 {
2044 } else if payment_params.payee.supports_basic_mpp() {
2046 } else if let Some(payee) = payee_node_id_opt {
2047 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
2048 |info| info.features().supports_basic_mpp()))
2051 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
2053 let first_hop_count = first_hops.map(|hops| hops.len()).unwrap_or(0);
2054 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",
2055 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
2056 if allow_mpp { "with" } else { "without" },
2057 first_hop_count, if first_hops.is_some() { "" } else { "not " },
2058 network_graph.nodes().len(), network_graph.channels().len(),
2059 max_total_routing_fee_msat);
2061 if first_hop_count < 10 {
2062 if let Some(hops) = first_hops {
2066 " First hop through {}/{} can send between {}msat and {}msat (inclusive).",
2067 hop.counterparty.node_id,
2068 hop.get_outbound_payment_scid().unwrap_or(0),
2069 hop.next_outbound_htlc_minimum_msat,
2070 hop.next_outbound_htlc_limit_msat
2077 // Prepare the data we'll use for payee-to-payer search by
2078 // inserting first hops suggested by the caller as targets.
2079 // Our search will then attempt to reach them while traversing from the payee node.
2080 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
2081 hash_map_with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
2082 if let Some(hops) = first_hops {
2084 if chan.get_outbound_payment_scid().is_none() {
2085 panic!("first_hops should be filled in with usable channels, not pending ones");
2087 if chan.counterparty.node_id == *our_node_pubkey {
2088 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
2091 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
2092 .or_insert(Vec::new())
2095 if first_hop_targets.is_empty() {
2096 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
2100 let mut private_hop_key_cache = hash_map_with_capacity(
2101 payment_params.payee.unblinded_route_hints().iter().map(|path| path.0.len()).sum()
2104 // Because we store references to private hop node_ids in `dist`, below, we need them to exist
2105 // (as `NodeId`, not `PublicKey`) for the lifetime of `dist`. Thus, we calculate all the keys
2106 // we'll need here and simply fetch them when routing.
2107 private_hop_key_cache.insert(maybe_dummy_payee_pk, NodeId::from_pubkey(&maybe_dummy_payee_pk));
2108 for route in payment_params.payee.unblinded_route_hints().iter() {
2109 for hop in route.0.iter() {
2110 private_hop_key_cache.insert(hop.src_node_id, NodeId::from_pubkey(&hop.src_node_id));
2114 // The main heap containing all candidate next-hops sorted by their score (max(fee,
2115 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
2116 // adding duplicate entries when we find a better path to a given node.
2117 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
2119 // Map from node_id to information about the best current path to that node, including feerate
2121 let mut dist: HashMap<NodeId, PathBuildingHop> = hash_map_with_capacity(network_nodes.len());
2123 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
2124 // indicating that we may wish to try again with a higher value, potentially paying to meet an
2125 // htlc_minimum with extra fees while still finding a cheaper path.
2126 let mut hit_minimum_limit;
2128 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
2129 // We start with a path_value of the exact amount we want, and if that generates a route we may
2130 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
2131 // amount we want in total across paths, selecting the best subset at the end.
2132 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
2133 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
2134 let mut path_value_msat = final_value_msat;
2136 // Routing Fragmentation Mitigation heuristic:
2138 // Routing fragmentation across many payment paths increases the overall routing
2139 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
2140 // Taking too many smaller paths also increases the chance of payment failure.
2141 // Thus to avoid this effect, we require from our collected links to provide
2142 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
2143 // This requirement is currently set to be 1/max_path_count of the payment
2144 // value to ensure we only ever return routes that do not violate this limit.
2145 let minimal_value_contribution_msat: u64 = if allow_mpp {
2146 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
2151 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
2152 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
2153 // drop the requirement by setting this to 0.
2154 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
2156 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
2157 // determine if the channel can be used by additional MPP paths or to inform path finding
2158 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
2159 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
2161 let mut used_liquidities: HashMap<CandidateHopId, u64> =
2162 hash_map_with_capacity(network_nodes.len());
2164 // Keeping track of how much value we already collected across other paths. Helps to decide
2165 // when we want to stop looking for new paths.
2166 let mut already_collected_value_msat = 0;
2168 for (_, channels) in first_hop_targets.iter_mut() {
2169 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
2173 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
2174 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
2176 // Remember how many candidates we ignored to allow for some logging afterwards.
2177 let mut num_ignored_value_contribution: u32 = 0;
2178 let mut num_ignored_path_length_limit: u32 = 0;
2179 let mut num_ignored_cltv_delta_limit: u32 = 0;
2180 let mut num_ignored_previously_failed: u32 = 0;
2181 let mut num_ignored_total_fee_limit: u32 = 0;
2182 let mut num_ignored_avoid_overpayment: u32 = 0;
2183 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
2185 macro_rules! add_entry {
2186 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
2187 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
2188 // since that value has to be transferred over this channel.
2189 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
2190 ( $candidate: expr, $next_hops_fee_msat: expr,
2191 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
2192 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
2193 // We "return" whether we updated the path at the end, and how much we can route via
2194 // this channel, via this:
2195 let mut hop_contribution_amt_msat = None;
2196 // Channels to self should not be used. This is more of belt-and-suspenders, because in
2197 // practice these cases should be caught earlier:
2198 // - for regular channels at channel announcement (TODO)
2199 // - for first and last hops early in get_route
2200 let src_node_id = $candidate.source();
2201 if Some(src_node_id) != $candidate.target() {
2202 let scid_opt = $candidate.short_channel_id();
2203 let effective_capacity = $candidate.effective_capacity();
2204 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
2206 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
2207 // It may be misleading because we might later choose to reduce the value transferred
2208 // over these channels, and the channel which was insufficient might become sufficient.
2209 // Worst case: we drop a good channel here because it can't cover the high following
2210 // fees caused by one expensive channel, but then this channel could have been used
2211 // if the amount being transferred over this path is lower.
2212 // We do this for now, but this is a subject for removal.
2213 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
2214 let used_liquidity_msat = used_liquidities
2215 .get(&$candidate.id())
2216 .map_or(0, |used_liquidity_msat| {
2217 available_value_contribution_msat = available_value_contribution_msat
2218 .saturating_sub(*used_liquidity_msat);
2219 *used_liquidity_msat
2222 // Verify the liquidity offered by this channel complies to the minimal contribution.
2223 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
2224 // Do not consider candidate hops that would exceed the maximum path length.
2225 let path_length_to_node = $next_hops_path_length
2226 + if $candidate.blinded_hint_idx().is_some() { 0 } else { 1 };
2227 let exceeds_max_path_length = path_length_to_node > max_path_length;
2229 // Do not consider candidates that exceed the maximum total cltv expiry limit.
2230 // In order to already account for some of the privacy enhancing random CLTV
2231 // expiry delta offset we add on top later, we subtract a rough estimate
2232 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
2233 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
2234 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
2235 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
2236 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
2237 .saturating_add($candidate.cltv_expiry_delta());
2238 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
2240 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
2241 // Includes paying fees for the use of the following channels.
2242 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
2243 Some(result) => result,
2244 // Can't overflow due to how the values were computed right above.
2245 None => unreachable!(),
2247 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2248 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
2249 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
2251 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2252 let may_overpay_to_meet_path_minimum_msat =
2253 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
2254 recommended_value_msat >= $candidate.htlc_minimum_msat()) ||
2255 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
2256 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
2258 let payment_failed_on_this_channel = match scid_opt {
2259 Some(scid) => payment_params.previously_failed_channels.contains(&scid),
2260 None => match $candidate.blinded_hint_idx() {
2262 payment_params.previously_failed_blinded_path_idxs.contains(&(idx as u64))
2268 let (should_log_candidate, first_hop_details) = match $candidate {
2269 CandidateRouteHop::FirstHop(hop) => (true, Some(hop.details)),
2270 CandidateRouteHop::PrivateHop(_) => (true, None),
2271 CandidateRouteHop::Blinded(_) => (true, None),
2272 CandidateRouteHop::OneHopBlinded(_) => (true, None),
2276 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
2277 // bother considering this channel. If retrying with recommended_value_msat may
2278 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
2279 // around again with a higher amount.
2280 if !contributes_sufficient_value {
2281 if should_log_candidate {
2282 log_trace!(logger, "Ignoring {} due to insufficient value contribution (channel max {:?}).",
2283 LoggedCandidateHop(&$candidate),
2284 effective_capacity);
2286 num_ignored_value_contribution += 1;
2287 } else if exceeds_max_path_length {
2288 if should_log_candidate {
2289 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
2291 num_ignored_path_length_limit += 1;
2292 } else if exceeds_cltv_delta_limit {
2293 if should_log_candidate {
2294 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
2296 if let Some(_) = first_hop_details {
2298 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
2299 hop_total_cltv_delta,
2300 max_total_cltv_expiry_delta,
2304 num_ignored_cltv_delta_limit += 1;
2305 } else if payment_failed_on_this_channel {
2306 if should_log_candidate {
2307 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
2309 num_ignored_previously_failed += 1;
2310 } else if may_overpay_to_meet_path_minimum_msat {
2311 if should_log_candidate {
2313 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit ({}).",
2314 LoggedCandidateHop(&$candidate), $candidate.htlc_minimum_msat());
2316 num_ignored_avoid_overpayment += 1;
2317 hit_minimum_limit = true;
2318 } else if over_path_minimum_msat {
2319 // Note that low contribution here (limited by available_liquidity_msat)
2320 // might violate htlc_minimum_msat on the hops which are next along the
2321 // payment path (upstream to the payee). To avoid that, we recompute
2322 // path fees knowing the final path contribution after constructing it.
2323 let curr_min = cmp::max(
2324 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
2326 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
2327 .saturating_add(curr_min);
2328 let hm_entry = dist.entry(src_node_id);
2329 let old_entry = hm_entry.or_insert_with(|| {
2330 // If there was previously no known way to access the source node
2331 // (recall it goes payee-to-payer) of short_channel_id, first add a
2332 // semi-dummy record just to compute the fees to reach the source node.
2333 // This will affect our decision on selecting short_channel_id
2334 // as a way to reach the $candidate.target() node.
2336 candidate: $candidate.clone(),
2338 next_hops_fee_msat: u64::max_value(),
2339 hop_use_fee_msat: u64::max_value(),
2340 total_fee_msat: u64::max_value(),
2341 path_htlc_minimum_msat,
2342 path_penalty_msat: u64::max_value(),
2343 was_processed: false,
2344 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2345 value_contribution_msat,
2349 #[allow(unused_mut)] // We only use the mut in cfg(test)
2350 let mut should_process = !old_entry.was_processed;
2351 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2353 // In test/fuzzing builds, we do extra checks to make sure the skipping
2354 // of already-seen nodes only happens in cases we expect (see below).
2355 if !should_process { should_process = true; }
2359 let mut hop_use_fee_msat = 0;
2360 let mut total_fee_msat: u64 = $next_hops_fee_msat;
2362 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2363 // will have the same effective-fee
2364 if src_node_id != our_node_id {
2365 // Note that `u64::max_value` means we'll always fail the
2366 // `old_entry.total_fee_msat > total_fee_msat` check below
2367 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
2368 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2371 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2372 if total_fee_msat > max_total_routing_fee_msat {
2373 if should_log_candidate {
2374 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2376 if let Some(_) = first_hop_details {
2378 "First hop candidate routing fee: {}. Limit: {}",
2380 max_total_routing_fee_msat,
2384 num_ignored_total_fee_limit += 1;
2386 let channel_usage = ChannelUsage {
2387 amount_msat: amount_to_transfer_over_msat,
2388 inflight_htlc_msat: used_liquidity_msat,
2391 let channel_penalty_msat =
2392 scorer.channel_penalty_msat($candidate,
2395 let path_penalty_msat = $next_hops_path_penalty_msat
2396 .saturating_add(channel_penalty_msat);
2398 // Update the way of reaching $candidate.source()
2399 // with the given short_channel_id (from $candidate.target()),
2400 // if this way is cheaper than the already known
2401 // (considering the cost to "reach" this channel from the route destination,
2402 // the cost of using this channel,
2403 // and the cost of routing to the source node of this channel).
2404 // Also, consider that htlc_minimum_msat_difference, because we might end up
2405 // paying it. Consider the following exploit:
2406 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2407 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2408 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2409 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2411 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2412 // but it may require additional tracking - we don't want to double-count
2413 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2414 // can't use something that may decrease on future hops.
2415 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2416 .saturating_add(old_entry.path_penalty_msat);
2417 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2418 .saturating_add(path_penalty_msat);
2420 if !old_entry.was_processed && new_cost < old_cost {
2421 let new_graph_node = RouteGraphNode {
2422 node_id: src_node_id,
2423 score: cmp::max(total_fee_msat, path_htlc_minimum_msat).saturating_add(path_penalty_msat),
2424 total_cltv_delta: hop_total_cltv_delta,
2425 value_contribution_msat,
2426 path_length_to_node,
2428 targets.push(new_graph_node);
2429 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2430 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2431 old_entry.total_fee_msat = total_fee_msat;
2432 old_entry.candidate = $candidate.clone();
2433 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2434 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2435 old_entry.path_penalty_msat = path_penalty_msat;
2436 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2438 old_entry.value_contribution_msat = value_contribution_msat;
2440 hop_contribution_amt_msat = Some(value_contribution_msat);
2441 } else if old_entry.was_processed && new_cost < old_cost {
2442 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2444 // If we're skipping processing a node which was previously
2445 // processed even though we found another path to it with a
2446 // cheaper fee, check that it was because the second path we
2447 // found (which we are processing now) has a lower value
2448 // contribution due to an HTLC minimum limit.
2450 // e.g. take a graph with two paths from node 1 to node 2, one
2451 // through channel A, and one through channel B. Channel A and
2452 // B are both in the to-process heap, with their scores set by
2453 // a higher htlc_minimum than fee.
2454 // Channel A is processed first, and the channels onwards from
2455 // node 1 are added to the to-process heap. Thereafter, we pop
2456 // Channel B off of the heap, note that it has a much more
2457 // restrictive htlc_maximum_msat, and recalculate the fees for
2458 // all of node 1's channels using the new, reduced, amount.
2460 // This would be bogus - we'd be selecting a higher-fee path
2461 // with a lower htlc_maximum_msat instead of the one we'd
2462 // already decided to use.
2463 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2465 value_contribution_msat + path_penalty_msat <
2466 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2473 if should_log_candidate {
2475 "Ignoring {} due to its htlc_minimum_msat limit.",
2476 LoggedCandidateHop(&$candidate));
2478 if let Some(details) = first_hop_details {
2480 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2481 details.next_outbound_htlc_minimum_msat,
2485 num_ignored_htlc_minimum_msat_limit += 1;
2489 hop_contribution_amt_msat
2493 let default_node_features = default_node_features();
2495 // Find ways (channels with destination) to reach a given node and store them
2496 // in the corresponding data structures (routing graph etc).
2497 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2498 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2499 // This data can later be helpful to optimize routing (pay lower fees).
2500 macro_rules! add_entries_to_cheapest_to_target_node {
2501 ( $node: expr, $node_id: expr, $next_hops_value_contribution: expr,
2502 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2503 let fee_to_target_msat;
2504 let next_hops_path_htlc_minimum_msat;
2505 let next_hops_path_penalty_msat;
2506 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
2507 let was_processed = elem.was_processed;
2508 elem.was_processed = true;
2509 fee_to_target_msat = elem.total_fee_msat;
2510 next_hops_path_htlc_minimum_msat = elem.path_htlc_minimum_msat;
2511 next_hops_path_penalty_msat = elem.path_penalty_msat;
2514 // Entries are added to dist in add_entry!() when there is a channel from a node.
2515 // Because there are no channels from payee, it will not have a dist entry at this point.
2516 // If we're processing any other node, it is always be the result of a channel from it.
2517 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2518 fee_to_target_msat = 0;
2519 next_hops_path_htlc_minimum_msat = 0;
2520 next_hops_path_penalty_msat = 0;
2525 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
2526 for details in first_channels {
2527 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2528 details, payer_node_id: &our_node_id,
2530 add_entry!(&candidate, fee_to_target_msat,
2531 $next_hops_value_contribution,
2532 next_hops_path_htlc_minimum_msat, next_hops_path_penalty_msat,
2533 $next_hops_cltv_delta, $next_hops_path_length);
2537 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2538 &node_info.features()
2540 &default_node_features
2543 if !features.requires_unknown_bits() {
2544 for chan_id in $node.channels.iter() {
2545 let chan = network_channels.get(chan_id).unwrap();
2546 if !chan.features.requires_unknown_bits() {
2547 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2548 if first_hops.is_none() || *source != our_node_id {
2549 if directed_channel.direction().enabled {
2550 let candidate = CandidateRouteHop::PublicHop(PublicHopCandidate {
2551 info: directed_channel,
2552 short_channel_id: *chan_id,
2554 add_entry!(&candidate,
2556 $next_hops_value_contribution,
2557 next_hops_path_htlc_minimum_msat,
2558 next_hops_path_penalty_msat,
2559 $next_hops_cltv_delta, $next_hops_path_length);
2570 let mut payment_paths = Vec::<PaymentPath>::new();
2572 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2573 'paths_collection: loop {
2574 // For every new path, start from scratch, except for used_liquidities, which
2575 // helps to avoid reusing previously selected paths in future iterations.
2578 hit_minimum_limit = false;
2580 // If first hop is a private channel and the only way to reach the payee, this is the only
2581 // place where it could be added.
2582 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2583 for details in first_channels {
2584 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2585 details, payer_node_id: &our_node_id,
2587 let added = add_entry!(&candidate, 0, path_value_msat,
2588 0, 0u64, 0, 0).is_some();
2589 log_trace!(logger, "{} direct route to payee via {}",
2590 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2594 // Add the payee as a target, so that the payee-to-payer
2595 // search algorithm knows what to start with.
2596 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2597 // The payee is not in our network graph, so nothing to add here.
2598 // There is still a chance of reaching them via last_hops though,
2599 // so don't yet fail the payment here.
2600 // If not, targets.pop() will not even let us enter the loop in step 2.
2603 add_entries_to_cheapest_to_target_node!(node, payee, path_value_msat, 0, 0);
2608 // If a caller provided us with last hops, add them to routing targets. Since this happens
2609 // earlier than general path finding, they will be somewhat prioritized, although currently
2610 // it matters only if the fees are exactly the same.
2611 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2612 // Only add the hops in this route to our candidate set if either
2613 // we have a direct channel to the first hop or the first hop is
2614 // in the regular network graph.
2615 let source_node_id = match introduction_node_id_cache[hint_idx] {
2616 Some(node_id) => node_id,
2617 None => match &hint.1.introduction_node {
2618 IntroductionNode::NodeId(pubkey) => {
2619 let node_id = NodeId::from_pubkey(&pubkey);
2620 match first_hop_targets.get_key_value(&node_id).map(|(key, _)| key) {
2621 Some(node_id) => node_id,
2625 IntroductionNode::DirectedShortChannelId(direction, scid) => {
2626 let first_hop = first_hop_targets.iter().find(|(_, channels)|
2629 .any(|details| Some(*scid) == details.get_outbound_payment_scid())
2632 Some((counterparty_node_id, _)) => {
2633 direction.select_node_id(&our_node_id, counterparty_node_id)
2640 if our_node_id == *source_node_id { continue }
2641 let candidate = if hint.1.blinded_hops.len() == 1 {
2642 CandidateRouteHop::OneHopBlinded(
2643 OneHopBlindedPathCandidate { source_node_id, hint, hint_idx }
2646 CandidateRouteHop::Blinded(BlindedPathCandidate { source_node_id, hint, hint_idx })
2648 let mut path_contribution_msat = path_value_msat;
2649 if let Some(hop_used_msat) = add_entry!(&candidate,
2650 0, path_contribution_msat, 0, 0_u64, 0, 0)
2652 path_contribution_msat = hop_used_msat;
2654 if let Some(first_channels) = first_hop_targets.get(source_node_id) {
2655 let mut first_channels = first_channels.clone();
2656 sort_first_hop_channels(
2657 &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2659 for details in first_channels {
2660 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2661 details, payer_node_id: &our_node_id,
2663 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2667 let path_min = candidate.htlc_minimum_msat().saturating_add(
2668 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2669 add_entry!(&first_hop_candidate, blinded_path_fee, path_contribution_msat, path_min,
2670 0_u64, candidate.cltv_expiry_delta(), 0);
2674 for route in payment_params.payee.unblinded_route_hints().iter()
2675 .filter(|route| !route.0.is_empty())
2677 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2678 let first_hop_src_is_reachable =
2679 // Only add the hops in this route to our candidate set if either we are part of
2680 // the first hop, we have a direct channel to the first hop, or the first hop is in
2681 // the regular network graph.
2682 our_node_id == first_hop_src_id ||
2683 first_hop_targets.get(&first_hop_src_id).is_some() ||
2684 network_nodes.get(&first_hop_src_id).is_some();
2685 if first_hop_src_is_reachable {
2686 // We start building the path from reverse, i.e., from payee
2687 // to the first RouteHintHop in the path.
2688 let hop_iter = route.0.iter().rev();
2689 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2690 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2691 let mut hop_used = true;
2692 let mut aggregate_next_hops_fee_msat: u64 = 0;
2693 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2694 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2695 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2696 let mut aggregate_next_hops_path_length: u8 = 0;
2697 let mut aggregate_path_contribution_msat = path_value_msat;
2699 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2700 let target = private_hop_key_cache.get(prev_hop_id).unwrap();
2702 if let Some(first_channels) = first_hop_targets.get(target) {
2703 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2704 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2705 hop.short_channel_id);
2710 let candidate = network_channels
2711 .get(&hop.short_channel_id)
2712 .and_then(|channel| channel.as_directed_to(target))
2713 .map(|(info, _)| CandidateRouteHop::PublicHop(PublicHopCandidate {
2715 short_channel_id: hop.short_channel_id,
2717 .unwrap_or_else(|| CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: hop, target_node_id: target }));
2719 if let Some(hop_used_msat) = add_entry!(&candidate,
2720 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2721 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2722 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2724 aggregate_path_contribution_msat = hop_used_msat;
2726 // If this hop was not used then there is no use checking the preceding
2727 // hops in the RouteHint. We can break by just searching for a direct
2728 // channel between last checked hop and first_hop_targets.
2732 let used_liquidity_msat = used_liquidities
2733 .get(&candidate.id()).copied()
2735 let channel_usage = ChannelUsage {
2736 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2737 inflight_htlc_msat: used_liquidity_msat,
2738 effective_capacity: candidate.effective_capacity(),
2740 let channel_penalty_msat = scorer.channel_penalty_msat(
2741 &candidate, channel_usage, score_params
2743 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2744 .saturating_add(channel_penalty_msat);
2746 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2747 .saturating_add(hop.cltv_expiry_delta as u32);
2749 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2752 // Searching for a direct channel between last checked hop and first_hop_targets
2753 if let Some(first_channels) = first_hop_targets.get(target) {
2754 let mut first_channels = first_channels.clone();
2755 sort_first_hop_channels(
2756 &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2758 for details in first_channels {
2759 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2760 details, payer_node_id: &our_node_id,
2762 add_entry!(&first_hop_candidate,
2763 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2764 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2765 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2773 // In the next values of the iterator, the aggregate fees already reflects
2774 // the sum of value sent from payer (final_value_msat) and routing fees
2775 // for the last node in the RouteHint. We need to just add the fees to
2776 // route through the current node so that the preceding node (next iteration)
2778 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2779 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2780 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2782 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2783 // this route hint's source node to forward said min over this channel.
2784 aggregate_next_hops_path_htlc_minimum_msat = {
2785 let curr_htlc_min = cmp::max(
2786 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2788 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2789 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2792 if idx == route.0.len() - 1 {
2793 // The last hop in this iterator is the first hop in
2794 // overall RouteHint.
2795 // If this hop connects to a node with which we have a direct channel,
2796 // ignore the network graph and, if the last hop was added, add our
2797 // direct channel to the candidate set.
2799 // Note that we *must* check if the last hop was added as `add_entry`
2800 // always assumes that the third argument is a node to which we have a
2802 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
2803 let mut first_channels = first_channels.clone();
2804 sort_first_hop_channels(
2805 &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2807 for details in first_channels {
2808 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2809 details, payer_node_id: &our_node_id,
2811 add_entry!(&first_hop_candidate,
2812 aggregate_next_hops_fee_msat,
2813 aggregate_path_contribution_msat,
2814 aggregate_next_hops_path_htlc_minimum_msat,
2815 aggregate_next_hops_path_penalty_msat,
2816 aggregate_next_hops_cltv_delta,
2817 aggregate_next_hops_path_length);
2825 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2827 // At this point, targets are filled with the data from first and
2828 // last hops communicated by the caller, and the payment receiver.
2829 let mut found_new_path = false;
2832 // If this loop terminates due the exhaustion of targets, two situations are possible:
2833 // - not enough outgoing liquidity:
2834 // 0 < already_collected_value_msat < final_value_msat
2835 // - enough outgoing liquidity:
2836 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2837 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2838 // paths_collection will be stopped because found_new_path==false.
2839 // This is not necessarily a routing failure.
2840 'path_construction: while let Some(RouteGraphNode { node_id, total_cltv_delta, mut value_contribution_msat, path_length_to_node, .. }) = targets.pop() {
2842 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2843 // traversing the graph and arrange the path out of what we found.
2844 if node_id == our_node_id {
2845 let mut new_entry = dist.remove(&our_node_id).unwrap();
2846 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2849 let mut features_set = false;
2850 let target = ordered_hops.last().unwrap().0.candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2851 if let Some(first_channels) = first_hop_targets.get(&target) {
2852 for details in first_channels {
2853 if let CandidateRouteHop::FirstHop(FirstHopCandidate { details: last_hop_details, .. })
2854 = ordered_hops.last().unwrap().0.candidate
2856 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2857 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2858 features_set = true;
2865 if let Some(node) = network_nodes.get(&target) {
2866 if let Some(node_info) = node.announcement_info.as_ref() {
2867 ordered_hops.last_mut().unwrap().1 = node_info.features().clone();
2869 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2872 // We can fill in features for everything except hops which were
2873 // provided via the invoice we're paying. We could guess based on the
2874 // recipient's features but for now we simply avoid guessing at all.
2878 // Means we successfully traversed from the payer to the payee, now
2879 // save this path for the payment route. Also, update the liquidity
2880 // remaining on the used hops, so that we take them into account
2881 // while looking for more paths.
2882 if target == maybe_dummy_payee_node_id {
2886 new_entry = match dist.remove(&target) {
2887 Some(payment_hop) => payment_hop,
2888 // We can't arrive at None because, if we ever add an entry to targets,
2889 // we also fill in the entry in dist (see add_entry!).
2890 None => unreachable!(),
2892 // We "propagate" the fees one hop backward (topologically) here,
2893 // so that fees paid for a HTLC forwarding on the current channel are
2894 // associated with the previous channel (where they will be subtracted).
2895 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2896 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2898 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2899 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2901 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2902 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2904 let mut payment_path = PaymentPath {hops: ordered_hops};
2906 // We could have possibly constructed a slightly inconsistent path: since we reduce
2907 // value being transferred along the way, we could have violated htlc_minimum_msat
2908 // on some channels we already passed (assuming dest->source direction). Here, we
2909 // recompute the fees again, so that if that's the case, we match the currently
2910 // underpaid htlc_minimum_msat with fees.
2911 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2912 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2913 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2915 // Since a path allows to transfer as much value as
2916 // the smallest channel it has ("bottleneck"), we should recompute
2917 // the fees so sender HTLC don't overpay fees when traversing
2918 // larger channels than the bottleneck. This may happen because
2919 // when we were selecting those channels we were not aware how much value
2920 // this path will transfer, and the relative fee for them
2921 // might have been computed considering a larger value.
2922 // Remember that we used these channels so that we don't rely
2923 // on the same liquidity in future paths.
2924 let mut prevented_redundant_path_selection = false;
2925 for (hop, _) in payment_path.hops.iter() {
2926 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2927 let used_liquidity_msat = used_liquidities
2928 .entry(hop.candidate.id())
2929 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2930 .or_insert(spent_on_hop_msat);
2931 let hop_capacity = hop.candidate.effective_capacity();
2932 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2933 if *used_liquidity_msat == hop_max_msat {
2934 // If this path used all of this channel's available liquidity, we know
2935 // this path will not be selected again in the next loop iteration.
2936 prevented_redundant_path_selection = true;
2938 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2940 if !prevented_redundant_path_selection {
2941 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2942 // we'll probably end up picking the same path again on the next iteration.
2943 // Decrease the available liquidity of a hop in the middle of the path.
2944 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2945 let exhausted = u64::max_value();
2947 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2948 LoggedCandidateHop(victim_candidate));
2949 if let Some(scid) = victim_candidate.short_channel_id() {
2950 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2951 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2955 // Track the total amount all our collected paths allow to send so that we know
2956 // when to stop looking for more paths
2957 already_collected_value_msat += value_contribution_msat;
2959 payment_paths.push(payment_path);
2960 found_new_path = true;
2961 break 'path_construction;
2964 // If we found a path back to the payee, we shouldn't try to process it again. This is
2965 // the equivalent of the `elem.was_processed` check in
2966 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2967 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2969 // Otherwise, since the current target node is not us,
2970 // keep "unrolling" the payment graph from payee to payer by
2971 // finding a way to reach the current target from the payer side.
2972 match network_nodes.get(&node_id) {
2975 add_entries_to_cheapest_to_target_node!(node, node_id,
2976 value_contribution_msat,
2977 total_cltv_delta, path_length_to_node);
2983 if !found_new_path && channel_saturation_pow_half != 0 {
2984 channel_saturation_pow_half = 0;
2985 continue 'paths_collection;
2987 // If we don't support MPP, no use trying to gather more value ever.
2988 break 'paths_collection;
2992 // Stop either when the recommended value is reached or if no new path was found in this
2994 // In the latter case, making another path finding attempt won't help,
2995 // because we deterministically terminated the search due to low liquidity.
2996 if !found_new_path && channel_saturation_pow_half != 0 {
2997 channel_saturation_pow_half = 0;
2998 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2999 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
3000 path_value_msat = recommended_value_msat;
3001 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
3002 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
3003 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
3004 break 'paths_collection;
3005 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
3006 // Further, if this was our first walk of the graph, and we weren't limited by an
3007 // htlc_minimum_msat, return immediately because this path should suffice. If we were
3008 // limited by an htlc_minimum_msat value, find another path with a higher value,
3009 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
3010 // still keeping a lower total fee than this path.
3011 if !hit_minimum_limit {
3012 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
3013 break 'paths_collection;
3015 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.");
3016 path_value_msat = recommended_value_msat;
3020 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
3021 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
3022 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
3023 num_ignored_total_fee_limit;
3024 if num_ignored_total > 0 {
3026 "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.",
3027 num_ignored_value_contribution, num_ignored_path_length_limit,
3028 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
3029 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
3030 num_ignored_total_fee_limit, num_ignored_total);
3034 if payment_paths.len() == 0 {
3035 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
3038 if already_collected_value_msat < final_value_msat {
3039 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
3043 let mut selected_route = payment_paths;
3045 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
3046 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
3048 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
3049 // the value they contribute towards the payment amount.
3050 // We sort in descending order as we will remove from the front in `retain`, next.
3051 selected_route.sort_unstable_by(|a, b|
3052 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
3053 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
3056 // We should make sure that at least 1 path left.
3057 let mut paths_left = selected_route.len();
3058 selected_route.retain(|path| {
3059 if paths_left == 1 {
3062 let path_value_msat = path.get_value_msat();
3063 if path_value_msat <= overpaid_value_msat {
3064 overpaid_value_msat -= path_value_msat;
3070 debug_assert!(selected_route.len() > 0);
3072 if overpaid_value_msat != 0 {
3074 // Now, subtract the remaining overpaid value from the most-expensive path.
3075 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
3076 // so that the sender pays less fees overall. And also htlc_minimum_msat.
3077 selected_route.sort_unstable_by(|a, b| {
3078 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3079 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3080 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
3082 let expensive_payment_path = selected_route.first_mut().unwrap();
3084 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
3085 // can't go negative.
3086 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
3087 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
3091 // Sort by the path itself and combine redundant paths.
3092 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
3093 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
3095 selected_route.sort_unstable_by_key(|path| {
3096 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
3097 debug_assert!(path.hops.len() <= key.len());
3098 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
3103 for idx in 0..(selected_route.len() - 1) {
3104 if idx + 1 >= selected_route.len() { break; }
3105 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
3106 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
3107 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
3108 selected_route[idx].update_value_and_recompute_fees(new_value);
3109 selected_route.remove(idx + 1);
3113 let mut paths = Vec::new();
3114 for payment_path in selected_route {
3115 let mut hops = Vec::with_capacity(payment_path.hops.len());
3116 for (hop, node_features) in payment_path.hops.iter()
3117 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
3119 let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
3120 let maybe_announced_channel = if let CandidateRouteHop::PublicHop(_) = hop.candidate {
3121 // If we sourced the hop from the graph we're sure the target node is announced.
3123 } else if let CandidateRouteHop::FirstHop(first_hop) = &hop.candidate {
3124 // If this is a first hop we also know if it's announced.
3125 first_hop.details.is_public
3127 // If we sourced it any other way, we double-check the network graph to see if
3128 // there are announced channels between the endpoints. If so, the hop might be
3129 // referring to any of the announced channels, as its `short_channel_id` might be
3130 // an alias, in which case we don't take any chances here.
3131 network_graph.node(&target).map_or(false, |hop_node|
3132 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
3133 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
3137 hops.push(RouteHop {
3138 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
3139 node_features: node_features.clone(),
3140 short_channel_id: hop.candidate.short_channel_id().unwrap(),
3141 channel_features: hop.candidate.features(),
3142 fee_msat: hop.fee_msat,
3143 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
3144 maybe_announced_channel,
3147 let mut final_cltv_delta = final_cltv_expiry_delta;
3148 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
3149 if let Some(blinded_path) = h.candidate.blinded_path() {
3150 final_cltv_delta = h.candidate.cltv_expiry_delta();
3152 hops: blinded_path.blinded_hops.clone(),
3153 blinding_point: blinded_path.blinding_point,
3154 excess_final_cltv_expiry_delta: 0,
3155 final_value_msat: h.fee_msat,
3159 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
3160 // applicable for the previous hop.
3161 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
3162 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
3165 paths.push(Path { hops, blinded_tail });
3167 // Make sure we would never create a route with more paths than we allow.
3168 debug_assert!(paths.len() <= payment_params.max_path_count.into());
3170 if let Some(node_features) = payment_params.payee.node_features() {
3171 for path in paths.iter_mut() {
3172 path.hops.last_mut().unwrap().node_features = node_features.clone();
3176 let route = Route { paths, route_params: Some(route_params.clone()) };
3178 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
3179 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
3180 if route.get_total_fees() > max_total_routing_fee_msat {
3181 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
3182 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
3186 log_info!(logger, "Got route: {}", log_route!(route));
3190 // When an adversarial intermediary node observes a payment, it may be able to infer its
3191 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
3192 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
3193 // payment path by adding a randomized 'shadow route' offset to the final hop.
3194 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
3195 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
3197 let network_channels = network_graph.channels();
3198 let network_nodes = network_graph.nodes();
3200 for path in route.paths.iter_mut() {
3201 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
3203 // Remember the last three nodes of the random walk and avoid looping back on them.
3204 // Init with the last three nodes from the actual path, if possible.
3205 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
3206 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
3207 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
3209 // Choose the last publicly known node as the starting point for the random walk.
3210 let mut cur_hop: Option<NodeId> = None;
3211 let mut path_nonce = [0u8; 12];
3212 if let Some(starting_hop) = path.hops.iter().rev()
3213 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
3214 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
3215 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
3218 // Init PRNG with the path-dependant nonce, which is static for private paths.
3219 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
3220 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
3222 // Pick a random path length in [1 .. 3]
3223 prng.process_in_place(&mut random_path_bytes);
3224 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
3226 for random_hop in 0..random_walk_length {
3227 // If we don't find a suitable offset in the public network graph, we default to
3228 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3229 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
3231 if let Some(cur_node_id) = cur_hop {
3232 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
3233 // Randomly choose the next unvisited hop.
3234 prng.process_in_place(&mut random_path_bytes);
3235 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
3236 .checked_rem(cur_node.channels.len())
3237 .and_then(|index| cur_node.channels.get(index))
3238 .and_then(|id| network_channels.get(id)) {
3239 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
3240 if !nodes_to_avoid.iter().any(|x| x == next_id) {
3241 nodes_to_avoid[random_hop] = *next_id;
3242 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
3243 cur_hop = Some(*next_id);
3250 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
3251 .checked_add(random_hop_offset)
3252 .unwrap_or(shadow_ctlv_expiry_delta_offset);
3255 // Limit the total offset to reduce the worst-case locked liquidity timevalue
3256 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
3257 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
3259 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
3260 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3261 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
3262 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
3263 max_path_offset = cmp::max(
3264 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
3265 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
3266 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
3268 // Add 'shadow' CLTV offset to the final hop
3269 if let Some(tail) = path.blinded_tail.as_mut() {
3270 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
3271 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
3273 if let Some(last_hop) = path.hops.last_mut() {
3274 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
3275 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
3280 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
3281 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
3283 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
3284 pub fn build_route_from_hops<L: Deref, GL: Deref>(
3285 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3286 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
3287 ) -> Result<Route, LightningError>
3288 where L::Target: Logger, GL::Target: Logger {
3289 let graph_lock = network_graph.read_only();
3290 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
3291 &graph_lock, logger, random_seed_bytes)?;
3292 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
3296 fn build_route_from_hops_internal<L: Deref>(
3297 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3298 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
3299 ) -> Result<Route, LightningError> where L::Target: Logger {
3302 our_node_id: NodeId,
3303 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
3306 impl ScoreLookUp for HopScorer {
3307 type ScoreParams = ();
3308 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
3309 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
3311 let mut cur_id = self.our_node_id;
3312 for i in 0..self.hop_ids.len() {
3313 if let Some(next_id) = self.hop_ids[i] {
3314 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
3326 impl<'a> Writeable for HopScorer {
3328 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
3333 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
3334 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
3337 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
3338 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
3339 for i in 0..hops.len() {
3340 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
3343 let scorer = HopScorer { our_node_id, hop_ids };
3345 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
3350 use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode};
3351 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
3352 use crate::routing::utxo::UtxoResult;
3353 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
3354 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
3355 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop, PublicHopCandidate};
3356 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
3357 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
3358 use crate::chain::transaction::OutPoint;
3359 use crate::ln::channel_state::{ChannelCounterparty, ChannelDetails, ChannelShutdownState};
3360 use crate::ln::types::ChannelId;
3361 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
3362 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
3363 use crate::ln::channelmanager;
3364 use crate::offers::invoice::BlindedPayInfo;
3365 use crate::util::config::UserConfig;
3366 use crate::util::test_utils as ln_test_utils;
3367 use crate::crypto::chacha20::ChaCha20;
3368 use crate::util::ser::{Readable, Writeable};
3370 use crate::util::ser::Writer;
3372 use bitcoin::amount::Amount;
3373 use bitcoin::hashes::Hash;
3374 use bitcoin::network::Network;
3375 use bitcoin::blockdata::constants::ChainHash;
3376 use bitcoin::blockdata::script::Builder;
3377 use bitcoin::blockdata::opcodes;
3378 use bitcoin::blockdata::transaction::TxOut;
3379 use bitcoin::hashes::hex::FromHex;
3380 use bitcoin::secp256k1::{PublicKey,SecretKey};
3381 use bitcoin::secp256k1::Secp256k1;
3383 use crate::io::Cursor;
3384 use crate::prelude::*;
3385 use crate::sync::Arc;
3387 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3388 features: InitFeatures, outbound_capacity_msat: u64) -> ChannelDetails {
3390 channel_id: ChannelId::new_zero(),
3391 counterparty: ChannelCounterparty {
3394 unspendable_punishment_reserve: 0,
3395 forwarding_info: None,
3396 outbound_htlc_minimum_msat: None,
3397 outbound_htlc_maximum_msat: None,
3399 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3402 outbound_scid_alias: None,
3403 inbound_scid_alias: None,
3404 channel_value_satoshis: 0,
3407 outbound_capacity_msat,
3408 next_outbound_htlc_limit_msat: outbound_capacity_msat,
3409 next_outbound_htlc_minimum_msat: 0,
3410 inbound_capacity_msat: 42,
3411 unspendable_punishment_reserve: None,
3412 confirmations_required: None,
3413 confirmations: None,
3414 force_close_spend_delay: None,
3415 is_outbound: true, is_channel_ready: true,
3416 is_usable: true, is_public: true,
3417 inbound_htlc_minimum_msat: None,
3418 inbound_htlc_maximum_msat: None,
3420 feerate_sat_per_1000_weight: None,
3421 channel_shutdown_state: Some(ChannelShutdownState::NotShuttingDown),
3422 pending_inbound_htlcs: Vec::new(),
3423 pending_outbound_htlcs: Vec::new(),
3428 fn simple_route_test() {
3429 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3430 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3431 let mut payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3432 let scorer = ln_test_utils::TestScorer::new();
3433 let random_seed_bytes = [42; 32];
3435 // Simple route to 2 via 1
3437 let route_params = RouteParameters::from_payment_params_and_value(
3438 payment_params.clone(), 0);
3439 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3440 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3441 &Default::default(), &random_seed_bytes) {
3442 assert_eq!(err, "Cannot send a payment of 0 msat");
3443 } else { panic!(); }
3445 payment_params.max_path_length = 2;
3446 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3447 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3448 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3449 assert_eq!(route.paths[0].hops.len(), 2);
3451 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3452 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3453 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3454 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3455 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3456 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3458 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3459 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3460 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3461 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3462 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3463 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3465 route_params.payment_params.max_path_length = 1;
3466 get_route(&our_id, &route_params, &network_graph.read_only(), None,
3467 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap_err();
3471 fn invalid_first_hop_test() {
3472 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3473 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3474 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3475 let scorer = ln_test_utils::TestScorer::new();
3476 let random_seed_bytes = [42; 32];
3478 // Simple route to 2 via 1
3480 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3482 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3483 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3484 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3485 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3486 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3487 } else { panic!(); }
3489 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3490 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3491 assert_eq!(route.paths[0].hops.len(), 2);
3495 fn htlc_minimum_test() {
3496 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3497 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3498 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3499 let scorer = ln_test_utils::TestScorer::new();
3500 let random_seed_bytes = [42; 32];
3502 // Simple route to 2 via 1
3504 // Disable other paths
3505 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3506 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3507 short_channel_id: 12,
3509 flags: 2, // to disable
3510 cltv_expiry_delta: 0,
3511 htlc_minimum_msat: 0,
3512 htlc_maximum_msat: MAX_VALUE_MSAT,
3514 fee_proportional_millionths: 0,
3515 excess_data: Vec::new()
3517 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3518 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3519 short_channel_id: 3,
3521 flags: 2, // to disable
3522 cltv_expiry_delta: 0,
3523 htlc_minimum_msat: 0,
3524 htlc_maximum_msat: MAX_VALUE_MSAT,
3526 fee_proportional_millionths: 0,
3527 excess_data: Vec::new()
3529 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3530 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3531 short_channel_id: 13,
3533 flags: 2, // to disable
3534 cltv_expiry_delta: 0,
3535 htlc_minimum_msat: 0,
3536 htlc_maximum_msat: MAX_VALUE_MSAT,
3538 fee_proportional_millionths: 0,
3539 excess_data: Vec::new()
3541 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3542 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3543 short_channel_id: 6,
3545 flags: 2, // to disable
3546 cltv_expiry_delta: 0,
3547 htlc_minimum_msat: 0,
3548 htlc_maximum_msat: MAX_VALUE_MSAT,
3550 fee_proportional_millionths: 0,
3551 excess_data: Vec::new()
3553 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3554 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3555 short_channel_id: 7,
3557 flags: 2, // to disable
3558 cltv_expiry_delta: 0,
3559 htlc_minimum_msat: 0,
3560 htlc_maximum_msat: MAX_VALUE_MSAT,
3562 fee_proportional_millionths: 0,
3563 excess_data: Vec::new()
3566 // Check against amount_to_transfer_over_msat.
3567 // Set minimal HTLC of 200_000_000 msat.
3568 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3569 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3570 short_channel_id: 2,
3573 cltv_expiry_delta: 0,
3574 htlc_minimum_msat: 200_000_000,
3575 htlc_maximum_msat: MAX_VALUE_MSAT,
3577 fee_proportional_millionths: 0,
3578 excess_data: Vec::new()
3581 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3583 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3584 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3585 short_channel_id: 4,
3588 cltv_expiry_delta: 0,
3589 htlc_minimum_msat: 0,
3590 htlc_maximum_msat: 199_999_999,
3592 fee_proportional_millionths: 0,
3593 excess_data: Vec::new()
3596 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3597 let route_params = RouteParameters::from_payment_params_and_value(
3598 payment_params, 199_999_999);
3599 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3600 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3601 &Default::default(), &random_seed_bytes) {
3602 assert_eq!(err, "Failed to find a path to the given destination");
3603 } else { panic!(); }
3605 // Lift the restriction on the first hop.
3606 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3607 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3608 short_channel_id: 2,
3611 cltv_expiry_delta: 0,
3612 htlc_minimum_msat: 0,
3613 htlc_maximum_msat: MAX_VALUE_MSAT,
3615 fee_proportional_millionths: 0,
3616 excess_data: Vec::new()
3619 // A payment above the minimum should pass
3620 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3621 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3622 assert_eq!(route.paths[0].hops.len(), 2);
3626 fn htlc_minimum_overpay_test() {
3627 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3628 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3629 let config = UserConfig::default();
3630 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3631 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3633 let scorer = ln_test_utils::TestScorer::new();
3634 let random_seed_bytes = [42; 32];
3636 // A route to node#2 via two paths.
3637 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3638 // Thus, they can't send 60 without overpaying.
3639 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3640 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3641 short_channel_id: 2,
3644 cltv_expiry_delta: 0,
3645 htlc_minimum_msat: 35_000,
3646 htlc_maximum_msat: 40_000,
3648 fee_proportional_millionths: 0,
3649 excess_data: Vec::new()
3651 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3652 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3653 short_channel_id: 12,
3656 cltv_expiry_delta: 0,
3657 htlc_minimum_msat: 35_000,
3658 htlc_maximum_msat: 40_000,
3660 fee_proportional_millionths: 0,
3661 excess_data: Vec::new()
3665 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3666 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3667 short_channel_id: 13,
3670 cltv_expiry_delta: 0,
3671 htlc_minimum_msat: 0,
3672 htlc_maximum_msat: MAX_VALUE_MSAT,
3674 fee_proportional_millionths: 0,
3675 excess_data: Vec::new()
3677 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3678 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3679 short_channel_id: 4,
3682 cltv_expiry_delta: 0,
3683 htlc_minimum_msat: 0,
3684 htlc_maximum_msat: MAX_VALUE_MSAT,
3686 fee_proportional_millionths: 0,
3687 excess_data: Vec::new()
3690 // Disable other paths
3691 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3692 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3693 short_channel_id: 1,
3695 flags: 2, // to disable
3696 cltv_expiry_delta: 0,
3697 htlc_minimum_msat: 0,
3698 htlc_maximum_msat: MAX_VALUE_MSAT,
3700 fee_proportional_millionths: 0,
3701 excess_data: Vec::new()
3704 let mut route_params = RouteParameters::from_payment_params_and_value(
3705 payment_params.clone(), 60_000);
3706 route_params.max_total_routing_fee_msat = Some(15_000);
3707 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3708 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3709 // Overpay fees to hit htlc_minimum_msat.
3710 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3711 // TODO: this could be better balanced to overpay 10k and not 15k.
3712 assert_eq!(overpaid_fees, 15_000);
3714 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3715 // while taking even more fee to match htlc_minimum_msat.
3716 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3717 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3718 short_channel_id: 12,
3721 cltv_expiry_delta: 0,
3722 htlc_minimum_msat: 65_000,
3723 htlc_maximum_msat: 80_000,
3725 fee_proportional_millionths: 0,
3726 excess_data: Vec::new()
3728 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3729 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3730 short_channel_id: 2,
3733 cltv_expiry_delta: 0,
3734 htlc_minimum_msat: 0,
3735 htlc_maximum_msat: MAX_VALUE_MSAT,
3737 fee_proportional_millionths: 0,
3738 excess_data: Vec::new()
3740 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3741 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3742 short_channel_id: 4,
3745 cltv_expiry_delta: 0,
3746 htlc_minimum_msat: 0,
3747 htlc_maximum_msat: MAX_VALUE_MSAT,
3749 fee_proportional_millionths: 100_000,
3750 excess_data: Vec::new()
3753 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3754 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3755 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3756 assert_eq!(route.paths.len(), 1);
3757 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3758 let fees = route.paths[0].hops[0].fee_msat;
3759 assert_eq!(fees, 5_000);
3761 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3762 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3763 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3764 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3765 // the other channel.
3766 assert_eq!(route.paths.len(), 1);
3767 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3768 let fees = route.paths[0].hops[0].fee_msat;
3769 assert_eq!(fees, 5_000);
3773 fn htlc_minimum_recipient_overpay_test() {
3774 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3775 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3776 let config = UserConfig::default();
3777 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3778 let scorer = ln_test_utils::TestScorer::new();
3779 let random_seed_bytes = [42; 32];
3781 // Route to node2 over a single path which requires overpaying the recipient themselves.
3783 // First disable all paths except the us -> node1 -> node2 path
3784 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3785 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3786 short_channel_id: 13,
3789 cltv_expiry_delta: 0,
3790 htlc_minimum_msat: 0,
3791 htlc_maximum_msat: 0,
3793 fee_proportional_millionths: 0,
3794 excess_data: Vec::new()
3797 // Set channel 4 to free but with a high htlc_minimum_msat
3798 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3799 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3800 short_channel_id: 4,
3803 cltv_expiry_delta: 0,
3804 htlc_minimum_msat: 15_000,
3805 htlc_maximum_msat: MAX_VALUE_MSAT,
3807 fee_proportional_millionths: 0,
3808 excess_data: Vec::new()
3811 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3812 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3813 // what we try to find a route for, so this test only just happens to work out to exactly
3815 let mut route_params = RouteParameters::from_payment_params_and_value(
3816 payment_params.clone(), 5_000);
3817 route_params.max_total_routing_fee_msat = Some(9_999);
3818 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3819 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3820 &Default::default(), &random_seed_bytes) {
3821 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3822 } else { panic!(); }
3824 let mut route_params = RouteParameters::from_payment_params_and_value(
3825 payment_params.clone(), 5_000);
3826 route_params.max_total_routing_fee_msat = Some(10_000);
3827 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3828 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3829 assert_eq!(route.get_total_fees(), 10_000);
3833 fn disable_channels_test() {
3834 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3835 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3836 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3837 let scorer = ln_test_utils::TestScorer::new();
3838 let random_seed_bytes = [42; 32];
3840 // // Disable channels 4 and 12 by flags=2
3841 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3842 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3843 short_channel_id: 4,
3845 flags: 2, // to disable
3846 cltv_expiry_delta: 0,
3847 htlc_minimum_msat: 0,
3848 htlc_maximum_msat: MAX_VALUE_MSAT,
3850 fee_proportional_millionths: 0,
3851 excess_data: Vec::new()
3853 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3854 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3855 short_channel_id: 12,
3857 flags: 2, // to disable
3858 cltv_expiry_delta: 0,
3859 htlc_minimum_msat: 0,
3860 htlc_maximum_msat: MAX_VALUE_MSAT,
3862 fee_proportional_millionths: 0,
3863 excess_data: Vec::new()
3866 // If all the channels require some features we don't understand, route should fail
3867 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3868 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3869 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3870 &Default::default(), &random_seed_bytes) {
3871 assert_eq!(err, "Failed to find a path to the given destination");
3872 } else { panic!(); }
3874 // If we specify a channel to node7, that overrides our local channel view and that gets used
3875 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3876 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3877 route_params.payment_params.max_path_length = 2;
3878 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3879 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3880 &Default::default(), &random_seed_bytes).unwrap();
3881 assert_eq!(route.paths[0].hops.len(), 2);
3883 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3884 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3885 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3886 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3887 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3888 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3890 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3891 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3892 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3893 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3894 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3895 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3899 fn disable_node_test() {
3900 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3901 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3902 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3903 let scorer = ln_test_utils::TestScorer::new();
3904 let random_seed_bytes = [42; 32];
3906 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3907 let mut unknown_features = NodeFeatures::empty();
3908 unknown_features.set_unknown_feature_required();
3909 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3910 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3911 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3913 // If all nodes require some features we don't understand, route should fail
3914 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3915 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3916 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3917 &Default::default(), &random_seed_bytes) {
3918 assert_eq!(err, "Failed to find a path to the given destination");
3919 } else { panic!(); }
3921 // If we specify a channel to node7, that overrides our local channel view and that gets used
3922 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3923 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3924 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3925 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3926 &Default::default(), &random_seed_bytes).unwrap();
3927 assert_eq!(route.paths[0].hops.len(), 2);
3929 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3930 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3931 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3932 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3933 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3934 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3936 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3937 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3938 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3939 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3940 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3941 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3943 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3944 // naively) assume that the user checked the feature bits on the invoice, which override
3945 // the node_announcement.
3949 fn our_chans_test() {
3950 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3951 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3952 let scorer = ln_test_utils::TestScorer::new();
3953 let random_seed_bytes = [42; 32];
3955 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3956 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3957 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3958 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3959 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3960 assert_eq!(route.paths[0].hops.len(), 3);
3962 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3963 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3964 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3965 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3966 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3967 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3969 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3970 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3971 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3972 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3973 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3974 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3976 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3977 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3978 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3979 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3980 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3981 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3983 // If we specify a channel to node7, that overrides our local channel view and that gets used
3984 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3985 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3986 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3987 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3988 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3989 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3990 &Default::default(), &random_seed_bytes).unwrap();
3991 assert_eq!(route.paths[0].hops.len(), 2);
3993 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3994 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3995 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3996 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3997 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3998 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4000 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4001 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
4002 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4003 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4004 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4005 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
4008 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4009 let zero_fees = RoutingFees {
4011 proportional_millionths: 0,
4013 vec![RouteHint(vec![RouteHintHop {
4014 src_node_id: nodes[3],
4015 short_channel_id: 8,
4017 cltv_expiry_delta: (8 << 4) | 1,
4018 htlc_minimum_msat: None,
4019 htlc_maximum_msat: None,
4021 ]), RouteHint(vec![RouteHintHop {
4022 src_node_id: nodes[4],
4023 short_channel_id: 9,
4026 proportional_millionths: 0,
4028 cltv_expiry_delta: (9 << 4) | 1,
4029 htlc_minimum_msat: None,
4030 htlc_maximum_msat: None,
4031 }]), RouteHint(vec![RouteHintHop {
4032 src_node_id: nodes[5],
4033 short_channel_id: 10,
4035 cltv_expiry_delta: (10 << 4) | 1,
4036 htlc_minimum_msat: None,
4037 htlc_maximum_msat: None,
4041 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4042 let zero_fees = RoutingFees {
4044 proportional_millionths: 0,
4046 vec![RouteHint(vec![RouteHintHop {
4047 src_node_id: nodes[2],
4048 short_channel_id: 5,
4051 proportional_millionths: 0,
4053 cltv_expiry_delta: (5 << 4) | 1,
4054 htlc_minimum_msat: None,
4055 htlc_maximum_msat: None,
4057 src_node_id: nodes[3],
4058 short_channel_id: 8,
4060 cltv_expiry_delta: (8 << 4) | 1,
4061 htlc_minimum_msat: None,
4062 htlc_maximum_msat: None,
4064 ]), RouteHint(vec![RouteHintHop {
4065 src_node_id: nodes[4],
4066 short_channel_id: 9,
4069 proportional_millionths: 0,
4071 cltv_expiry_delta: (9 << 4) | 1,
4072 htlc_minimum_msat: None,
4073 htlc_maximum_msat: None,
4074 }]), RouteHint(vec![RouteHintHop {
4075 src_node_id: nodes[5],
4076 short_channel_id: 10,
4078 cltv_expiry_delta: (10 << 4) | 1,
4079 htlc_minimum_msat: None,
4080 htlc_maximum_msat: None,
4085 fn partial_route_hint_test() {
4086 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4087 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4088 let scorer = ln_test_utils::TestScorer::new();
4089 let random_seed_bytes = [42; 32];
4091 // Simple test across 2, 3, 5, and 4 via a last_hop channel
4092 // Tests the behaviour when the RouteHint contains a suboptimal hop.
4093 // RouteHint may be partially used by the algo to build the best path.
4095 // First check that last hop can't have its source as the payee.
4096 let invalid_last_hop = RouteHint(vec![RouteHintHop {
4097 src_node_id: nodes[6],
4098 short_channel_id: 8,
4101 proportional_millionths: 0,
4103 cltv_expiry_delta: (8 << 4) | 1,
4104 htlc_minimum_msat: None,
4105 htlc_maximum_msat: None,
4108 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
4109 invalid_last_hops.push(invalid_last_hop);
4111 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4112 .with_route_hints(invalid_last_hops).unwrap();
4113 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4114 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
4115 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
4116 &Default::default(), &random_seed_bytes) {
4117 assert_eq!(err, "Route hint cannot have the payee as the source.");
4118 } else { panic!(); }
4121 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4122 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
4123 payment_params.max_path_length = 5;
4124 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4125 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4126 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4127 assert_eq!(route.paths[0].hops.len(), 5);
4129 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4130 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4131 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4132 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4133 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4134 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4136 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4137 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4138 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4139 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4140 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4141 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4143 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4144 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4145 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4146 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4147 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4148 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4150 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4151 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4152 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4153 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4154 // If we have a peer in the node map, we'll use their features here since we don't have
4155 // a way of figuring out their features from the invoice:
4156 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4157 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4159 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4160 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4161 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4162 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4163 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4164 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4167 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4168 let zero_fees = RoutingFees {
4170 proportional_millionths: 0,
4172 vec![RouteHint(vec![RouteHintHop {
4173 src_node_id: nodes[3],
4174 short_channel_id: 8,
4176 cltv_expiry_delta: (8 << 4) | 1,
4177 htlc_minimum_msat: None,
4178 htlc_maximum_msat: None,
4179 }]), RouteHint(vec![
4181 ]), RouteHint(vec![RouteHintHop {
4182 src_node_id: nodes[5],
4183 short_channel_id: 10,
4185 cltv_expiry_delta: (10 << 4) | 1,
4186 htlc_minimum_msat: None,
4187 htlc_maximum_msat: None,
4192 fn ignores_empty_last_hops_test() {
4193 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4194 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4195 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
4196 let scorer = ln_test_utils::TestScorer::new();
4197 let random_seed_bytes = [42; 32];
4199 // Test handling of an empty RouteHint passed in Invoice.
4200 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4201 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4202 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4203 assert_eq!(route.paths[0].hops.len(), 5);
4205 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4206 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4207 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4208 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4209 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4210 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4212 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4213 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4214 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4215 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4216 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4217 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4219 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4220 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4221 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4222 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4223 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4224 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4226 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4227 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4228 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4229 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4230 // If we have a peer in the node map, we'll use their features here since we don't have
4231 // a way of figuring out their features from the invoice:
4232 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4233 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4235 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4236 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4237 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4238 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4239 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4240 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4243 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
4245 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
4246 let zero_fees = RoutingFees {
4248 proportional_millionths: 0,
4250 vec![RouteHint(vec![RouteHintHop {
4251 src_node_id: hint_hops[0],
4252 short_channel_id: 0xff00,
4255 proportional_millionths: 0,
4257 cltv_expiry_delta: (5 << 4) | 1,
4258 htlc_minimum_msat: None,
4259 htlc_maximum_msat: None,
4261 src_node_id: hint_hops[1],
4262 short_channel_id: 0xff01,
4264 cltv_expiry_delta: (8 << 4) | 1,
4265 htlc_minimum_msat: None,
4266 htlc_maximum_msat: None,
4271 fn multi_hint_last_hops_test() {
4272 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4273 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4274 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
4275 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4276 let scorer = ln_test_utils::TestScorer::new();
4277 let random_seed_bytes = [42; 32];
4279 // Test through channels 2, 3, 0xff00, 0xff01.
4280 // Test shows that multi-hop route hints are considered and factored correctly into the
4283 // Disabling channels 6 & 7 by flags=2
4284 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4285 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4286 short_channel_id: 6,
4288 flags: 2, // to disable
4289 cltv_expiry_delta: 0,
4290 htlc_minimum_msat: 0,
4291 htlc_maximum_msat: MAX_VALUE_MSAT,
4293 fee_proportional_millionths: 0,
4294 excess_data: Vec::new()
4296 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4297 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4298 short_channel_id: 7,
4300 flags: 2, // to disable
4301 cltv_expiry_delta: 0,
4302 htlc_minimum_msat: 0,
4303 htlc_maximum_msat: MAX_VALUE_MSAT,
4305 fee_proportional_millionths: 0,
4306 excess_data: Vec::new()
4309 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4310 route_params.payment_params.max_path_length = 4;
4311 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4312 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4313 assert_eq!(route.paths[0].hops.len(), 4);
4315 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4316 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4317 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4318 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4319 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4320 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4322 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4323 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4324 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4325 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4326 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4327 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4329 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4330 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4331 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4332 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4333 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4334 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4336 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4337 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4338 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4339 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4340 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4341 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4342 route_params.payment_params.max_path_length = 3;
4343 get_route(&our_id, &route_params, &network_graph.read_only(), None,
4344 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap_err();
4348 fn private_multi_hint_last_hops_test() {
4349 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4350 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4352 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4353 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4355 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4356 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4357 let scorer = ln_test_utils::TestScorer::new();
4358 // Test through channels 2, 3, 0xff00, 0xff01.
4359 // Test shows that multiple hop hints are considered.
4361 // Disabling channels 6 & 7 by flags=2
4362 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4363 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4364 short_channel_id: 6,
4366 flags: 2, // to disable
4367 cltv_expiry_delta: 0,
4368 htlc_minimum_msat: 0,
4369 htlc_maximum_msat: MAX_VALUE_MSAT,
4371 fee_proportional_millionths: 0,
4372 excess_data: Vec::new()
4374 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4375 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4376 short_channel_id: 7,
4378 flags: 2, // to disable
4379 cltv_expiry_delta: 0,
4380 htlc_minimum_msat: 0,
4381 htlc_maximum_msat: MAX_VALUE_MSAT,
4383 fee_proportional_millionths: 0,
4384 excess_data: Vec::new()
4387 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4388 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4389 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4390 assert_eq!(route.paths[0].hops.len(), 4);
4392 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4393 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4394 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4395 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4396 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4397 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4399 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4400 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4401 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4402 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4403 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4404 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4406 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4407 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4408 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4409 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4410 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4411 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4413 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4414 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4415 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4416 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4417 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4418 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4421 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4422 let zero_fees = RoutingFees {
4424 proportional_millionths: 0,
4426 vec![RouteHint(vec![RouteHintHop {
4427 src_node_id: nodes[4],
4428 short_channel_id: 11,
4430 cltv_expiry_delta: (11 << 4) | 1,
4431 htlc_minimum_msat: None,
4432 htlc_maximum_msat: None,
4434 src_node_id: nodes[3],
4435 short_channel_id: 8,
4437 cltv_expiry_delta: (8 << 4) | 1,
4438 htlc_minimum_msat: None,
4439 htlc_maximum_msat: None,
4440 }]), RouteHint(vec![RouteHintHop {
4441 src_node_id: nodes[4],
4442 short_channel_id: 9,
4445 proportional_millionths: 0,
4447 cltv_expiry_delta: (9 << 4) | 1,
4448 htlc_minimum_msat: None,
4449 htlc_maximum_msat: None,
4450 }]), RouteHint(vec![RouteHintHop {
4451 src_node_id: nodes[5],
4452 short_channel_id: 10,
4454 cltv_expiry_delta: (10 << 4) | 1,
4455 htlc_minimum_msat: None,
4456 htlc_maximum_msat: None,
4461 fn last_hops_with_public_channel_test() {
4462 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4463 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4464 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4465 let scorer = ln_test_utils::TestScorer::new();
4466 let random_seed_bytes = [42; 32];
4468 // This test shows that public routes can be present in the invoice
4469 // which would be handled in the same manner.
4471 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4472 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4473 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4474 assert_eq!(route.paths[0].hops.len(), 5);
4476 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4477 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4478 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4479 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4480 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4481 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4483 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4484 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4485 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4486 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4487 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4488 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4490 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4491 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4492 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4493 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4494 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4495 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4497 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4498 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4499 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4500 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4501 // If we have a peer in the node map, we'll use their features here since we don't have
4502 // a way of figuring out their features from the invoice:
4503 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4504 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4506 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4507 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4508 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4509 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4510 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4511 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4515 fn our_chans_last_hop_connect_test() {
4516 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4517 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4518 let scorer = ln_test_utils::TestScorer::new();
4519 let random_seed_bytes = [42; 32];
4521 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4522 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4523 let mut last_hops = last_hops(&nodes);
4524 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4525 .with_route_hints(last_hops.clone()).unwrap();
4526 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4527 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4528 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4529 &Default::default(), &random_seed_bytes).unwrap();
4530 assert_eq!(route.paths[0].hops.len(), 2);
4532 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4533 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4534 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4535 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4536 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4537 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4539 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4540 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4541 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4542 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4543 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4544 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4546 last_hops[0].0[0].fees.base_msat = 1000;
4548 // Revert to via 6 as the fee on 8 goes up
4549 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4550 .with_route_hints(last_hops).unwrap();
4551 let route_params = RouteParameters::from_payment_params_and_value(
4552 payment_params.clone(), 100);
4553 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4554 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4555 assert_eq!(route.paths[0].hops.len(), 4);
4557 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4558 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4559 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4560 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4561 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4562 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4564 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4565 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4566 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4567 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4568 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4569 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4571 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4572 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4573 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4574 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4575 // If we have a peer in the node map, we'll use their features here since we don't have
4576 // a way of figuring out their features from the invoice:
4577 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4578 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4580 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4581 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4582 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4583 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4584 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4585 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4587 // ...but still use 8 for larger payments as 6 has a variable feerate
4588 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4589 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4590 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4591 assert_eq!(route.paths[0].hops.len(), 5);
4593 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4594 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4595 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4596 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4597 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4598 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4600 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4601 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4602 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4603 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4604 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4605 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4607 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4608 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4609 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4610 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4611 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4612 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4614 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4615 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4616 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4617 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4618 // If we have a peer in the node map, we'll use their features here since we don't have
4619 // a way of figuring out their features from the invoice:
4620 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4621 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4623 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4624 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4625 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4626 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4627 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4628 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4631 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> {
4632 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4633 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4634 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4636 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4637 let last_hops = RouteHint(vec![RouteHintHop {
4638 src_node_id: middle_node_id,
4639 short_channel_id: 8,
4642 proportional_millionths: last_hop_fee_prop,
4644 cltv_expiry_delta: (8 << 4) | 1,
4645 htlc_minimum_msat: None,
4646 htlc_maximum_msat: last_hop_htlc_max,
4648 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4649 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4650 let scorer = ln_test_utils::TestScorer::new();
4651 let random_seed_bytes = [42; 32];
4652 let logger = ln_test_utils::TestLogger::new();
4653 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4654 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4655 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4656 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4657 &random_seed_bytes);
4662 fn unannounced_path_test() {
4663 // We should be able to send a payment to a destination without any help of a routing graph
4664 // if we have a channel with a common counterparty that appears in the first and last hop
4666 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4668 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4669 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4670 assert_eq!(route.paths[0].hops.len(), 2);
4672 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4673 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4674 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4675 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4676 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4677 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4679 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4680 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4681 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4682 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4683 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4684 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4688 fn overflow_unannounced_path_test_liquidity_underflow() {
4689 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4690 // the last-hop had a fee which overflowed a u64, we'd panic.
4691 // This was due to us adding the first-hop from us unconditionally, causing us to think
4692 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4693 // In this test, we previously hit a subtraction underflow due to having less available
4694 // liquidity at the last hop than 0.
4695 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());
4699 fn overflow_unannounced_path_test_feerate_overflow() {
4700 // This tests for the same case as above, except instead of hitting a subtraction
4701 // underflow, we hit a case where the fee charged at a hop overflowed.
4702 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());
4706 fn available_amount_while_routing_test() {
4707 // Tests whether we choose the correct available channel amount while routing.
4709 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4710 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4711 let scorer = ln_test_utils::TestScorer::new();
4712 let random_seed_bytes = [42; 32];
4713 let config = UserConfig::default();
4714 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4715 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4718 // We will use a simple single-path route from
4719 // our node to node2 via node0: channels {1, 3}.
4721 // First disable all other paths.
4722 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4723 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4724 short_channel_id: 2,
4727 cltv_expiry_delta: 0,
4728 htlc_minimum_msat: 0,
4729 htlc_maximum_msat: 100_000,
4731 fee_proportional_millionths: 0,
4732 excess_data: Vec::new()
4734 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4735 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4736 short_channel_id: 12,
4739 cltv_expiry_delta: 0,
4740 htlc_minimum_msat: 0,
4741 htlc_maximum_msat: 100_000,
4743 fee_proportional_millionths: 0,
4744 excess_data: Vec::new()
4747 // Make the first channel (#1) very permissive,
4748 // and we will be testing all limits on the second channel.
4749 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4750 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4751 short_channel_id: 1,
4754 cltv_expiry_delta: 0,
4755 htlc_minimum_msat: 0,
4756 htlc_maximum_msat: 1_000_000_000,
4758 fee_proportional_millionths: 0,
4759 excess_data: Vec::new()
4762 // First, let's see if routing works if we have absolutely no idea about the available amount.
4763 // In this case, it should be set to 250_000 sats.
4764 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4765 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4766 short_channel_id: 3,
4769 cltv_expiry_delta: 0,
4770 htlc_minimum_msat: 0,
4771 htlc_maximum_msat: 250_000_000,
4773 fee_proportional_millionths: 0,
4774 excess_data: Vec::new()
4778 // Attempt to route more than available results in a failure.
4779 let route_params = RouteParameters::from_payment_params_and_value(
4780 payment_params.clone(), 250_000_001);
4781 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4782 &our_id, &route_params, &network_graph.read_only(), None,
4783 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4784 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4785 } else { panic!(); }
4789 // Now, attempt to route an exact amount we have should be fine.
4790 let route_params = RouteParameters::from_payment_params_and_value(
4791 payment_params.clone(), 250_000_000);
4792 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4793 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4794 assert_eq!(route.paths.len(), 1);
4795 let path = route.paths.last().unwrap();
4796 assert_eq!(path.hops.len(), 2);
4797 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4798 assert_eq!(path.final_value_msat(), 250_000_000);
4801 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4802 // Disable channel #1 and use another first hop.
4803 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4804 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4805 short_channel_id: 1,
4808 cltv_expiry_delta: 0,
4809 htlc_minimum_msat: 0,
4810 htlc_maximum_msat: 1_000_000_000,
4812 fee_proportional_millionths: 0,
4813 excess_data: Vec::new()
4816 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4817 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4820 // Attempt to route more than available results in a failure.
4821 let route_params = RouteParameters::from_payment_params_and_value(
4822 payment_params.clone(), 200_000_001);
4823 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4824 &our_id, &route_params, &network_graph.read_only(),
4825 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4826 &Default::default(), &random_seed_bytes) {
4827 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4828 } else { panic!(); }
4832 // Now, attempt to route an exact amount we have should be fine.
4833 let route_params = RouteParameters::from_payment_params_and_value(
4834 payment_params.clone(), 200_000_000);
4835 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4836 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4837 &Default::default(), &random_seed_bytes).unwrap();
4838 assert_eq!(route.paths.len(), 1);
4839 let path = route.paths.last().unwrap();
4840 assert_eq!(path.hops.len(), 2);
4841 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4842 assert_eq!(path.final_value_msat(), 200_000_000);
4845 // Enable channel #1 back.
4846 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4847 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4848 short_channel_id: 1,
4851 cltv_expiry_delta: 0,
4852 htlc_minimum_msat: 0,
4853 htlc_maximum_msat: 1_000_000_000,
4855 fee_proportional_millionths: 0,
4856 excess_data: Vec::new()
4860 // Now let's see if routing works if we know only htlc_maximum_msat.
4861 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4862 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4863 short_channel_id: 3,
4866 cltv_expiry_delta: 0,
4867 htlc_minimum_msat: 0,
4868 htlc_maximum_msat: 15_000,
4870 fee_proportional_millionths: 0,
4871 excess_data: Vec::new()
4875 // Attempt to route more than available results in a failure.
4876 let route_params = RouteParameters::from_payment_params_and_value(
4877 payment_params.clone(), 15_001);
4878 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4879 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4880 &scorer, &Default::default(), &random_seed_bytes) {
4881 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4882 } else { panic!(); }
4886 // Now, attempt to route an exact amount we have should be fine.
4887 let route_params = RouteParameters::from_payment_params_and_value(
4888 payment_params.clone(), 15_000);
4889 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4890 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4891 assert_eq!(route.paths.len(), 1);
4892 let path = route.paths.last().unwrap();
4893 assert_eq!(path.hops.len(), 2);
4894 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4895 assert_eq!(path.final_value_msat(), 15_000);
4898 // Now let's see if routing works if we know only capacity from the UTXO.
4900 // We can't change UTXO capacity on the fly, so we'll disable
4901 // the existing channel and add another one with the capacity we need.
4902 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4903 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4904 short_channel_id: 3,
4907 cltv_expiry_delta: 0,
4908 htlc_minimum_msat: 0,
4909 htlc_maximum_msat: MAX_VALUE_MSAT,
4911 fee_proportional_millionths: 0,
4912 excess_data: Vec::new()
4915 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4916 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4917 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4918 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4919 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_p2wsh();
4921 *chain_monitor.utxo_ret.lock().unwrap() =
4922 UtxoResult::Sync(Ok(TxOut { value: Amount::from_sat(15), script_pubkey: good_script.clone() }));
4923 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4925 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4926 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4927 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4928 short_channel_id: 333,
4931 cltv_expiry_delta: (3 << 4) | 1,
4932 htlc_minimum_msat: 0,
4933 htlc_maximum_msat: 15_000,
4935 fee_proportional_millionths: 0,
4936 excess_data: Vec::new()
4938 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4939 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4940 short_channel_id: 333,
4943 cltv_expiry_delta: (3 << 4) | 2,
4944 htlc_minimum_msat: 0,
4945 htlc_maximum_msat: 15_000,
4947 fee_proportional_millionths: 0,
4948 excess_data: Vec::new()
4952 // Attempt to route more than available results in a failure.
4953 let route_params = RouteParameters::from_payment_params_and_value(
4954 payment_params.clone(), 15_001);
4955 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4956 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4957 &scorer, &Default::default(), &random_seed_bytes) {
4958 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4959 } else { panic!(); }
4963 // Now, attempt to route an exact amount we have should be fine.
4964 let route_params = RouteParameters::from_payment_params_and_value(
4965 payment_params.clone(), 15_000);
4966 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4967 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4968 assert_eq!(route.paths.len(), 1);
4969 let path = route.paths.last().unwrap();
4970 assert_eq!(path.hops.len(), 2);
4971 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4972 assert_eq!(path.final_value_msat(), 15_000);
4975 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4976 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4977 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4978 short_channel_id: 333,
4981 cltv_expiry_delta: 0,
4982 htlc_minimum_msat: 0,
4983 htlc_maximum_msat: 10_000,
4985 fee_proportional_millionths: 0,
4986 excess_data: Vec::new()
4990 // Attempt to route more than available results in a failure.
4991 let route_params = RouteParameters::from_payment_params_and_value(
4992 payment_params.clone(), 10_001);
4993 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4994 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4995 &scorer, &Default::default(), &random_seed_bytes) {
4996 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4997 } else { panic!(); }
5001 // Now, attempt to route an exact amount we have should be fine.
5002 let route_params = RouteParameters::from_payment_params_and_value(
5003 payment_params.clone(), 10_000);
5004 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5005 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5006 assert_eq!(route.paths.len(), 1);
5007 let path = route.paths.last().unwrap();
5008 assert_eq!(path.hops.len(), 2);
5009 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5010 assert_eq!(path.final_value_msat(), 10_000);
5015 fn available_liquidity_last_hop_test() {
5016 // Check that available liquidity properly limits the path even when only
5017 // one of the latter hops is limited.
5018 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5019 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5020 let scorer = ln_test_utils::TestScorer::new();
5021 let random_seed_bytes = [42; 32];
5022 let config = UserConfig::default();
5023 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5024 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5027 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5028 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
5029 // Total capacity: 50 sats.
5031 // Disable other potential paths.
5032 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5033 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5034 short_channel_id: 2,
5037 cltv_expiry_delta: 0,
5038 htlc_minimum_msat: 0,
5039 htlc_maximum_msat: 100_000,
5041 fee_proportional_millionths: 0,
5042 excess_data: Vec::new()
5044 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5045 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5046 short_channel_id: 7,
5049 cltv_expiry_delta: 0,
5050 htlc_minimum_msat: 0,
5051 htlc_maximum_msat: 100_000,
5053 fee_proportional_millionths: 0,
5054 excess_data: Vec::new()
5059 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5060 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5061 short_channel_id: 12,
5064 cltv_expiry_delta: 0,
5065 htlc_minimum_msat: 0,
5066 htlc_maximum_msat: 100_000,
5068 fee_proportional_millionths: 0,
5069 excess_data: Vec::new()
5071 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5072 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5073 short_channel_id: 13,
5076 cltv_expiry_delta: 0,
5077 htlc_minimum_msat: 0,
5078 htlc_maximum_msat: 100_000,
5080 fee_proportional_millionths: 0,
5081 excess_data: Vec::new()
5084 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5085 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5086 short_channel_id: 6,
5089 cltv_expiry_delta: 0,
5090 htlc_minimum_msat: 0,
5091 htlc_maximum_msat: 50_000,
5093 fee_proportional_millionths: 0,
5094 excess_data: Vec::new()
5096 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5097 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5098 short_channel_id: 11,
5101 cltv_expiry_delta: 0,
5102 htlc_minimum_msat: 0,
5103 htlc_maximum_msat: 100_000,
5105 fee_proportional_millionths: 0,
5106 excess_data: Vec::new()
5109 // Attempt to route more than available results in a failure.
5110 let route_params = RouteParameters::from_payment_params_and_value(
5111 payment_params.clone(), 60_000);
5112 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5113 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5114 &scorer, &Default::default(), &random_seed_bytes) {
5115 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5116 } else { panic!(); }
5120 // Now, attempt to route 49 sats (just a bit below the capacity).
5121 let route_params = RouteParameters::from_payment_params_and_value(
5122 payment_params.clone(), 49_000);
5123 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5124 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5125 assert_eq!(route.paths.len(), 1);
5126 let mut total_amount_paid_msat = 0;
5127 for path in &route.paths {
5128 assert_eq!(path.hops.len(), 4);
5129 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5130 total_amount_paid_msat += path.final_value_msat();
5132 assert_eq!(total_amount_paid_msat, 49_000);
5136 // Attempt to route an exact amount is also fine
5137 let route_params = RouteParameters::from_payment_params_and_value(
5138 payment_params, 50_000);
5139 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5140 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5141 assert_eq!(route.paths.len(), 1);
5142 let mut total_amount_paid_msat = 0;
5143 for path in &route.paths {
5144 assert_eq!(path.hops.len(), 4);
5145 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5146 total_amount_paid_msat += path.final_value_msat();
5148 assert_eq!(total_amount_paid_msat, 50_000);
5153 fn ignore_fee_first_hop_test() {
5154 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5155 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5156 let scorer = ln_test_utils::TestScorer::new();
5157 let random_seed_bytes = [42; 32];
5158 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5160 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5161 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5162 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5163 short_channel_id: 1,
5166 cltv_expiry_delta: 0,
5167 htlc_minimum_msat: 0,
5168 htlc_maximum_msat: 100_000,
5169 fee_base_msat: 1_000_000,
5170 fee_proportional_millionths: 0,
5171 excess_data: Vec::new()
5173 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5174 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5175 short_channel_id: 3,
5178 cltv_expiry_delta: 0,
5179 htlc_minimum_msat: 0,
5180 htlc_maximum_msat: 50_000,
5182 fee_proportional_millionths: 0,
5183 excess_data: Vec::new()
5187 let route_params = RouteParameters::from_payment_params_and_value(
5188 payment_params, 50_000);
5189 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5190 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5191 assert_eq!(route.paths.len(), 1);
5192 let mut total_amount_paid_msat = 0;
5193 for path in &route.paths {
5194 assert_eq!(path.hops.len(), 2);
5195 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5196 total_amount_paid_msat += path.final_value_msat();
5198 assert_eq!(total_amount_paid_msat, 50_000);
5203 fn simple_mpp_route_test() {
5204 let (secp_ctx, _, _, _, _) = build_graph();
5205 let (_, _, _, nodes) = get_nodes(&secp_ctx);
5206 let config = UserConfig::default();
5207 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5208 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5210 do_simple_mpp_route_test(clear_payment_params);
5212 // MPP to a 1-hop blinded path for nodes[2]
5213 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
5214 let blinded_path = BlindedPath {
5215 introduction_node: IntroductionNode::NodeId(nodes[2]),
5216 blinding_point: ln_test_utils::pubkey(42),
5217 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
5219 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
5221 fee_proportional_millionths: 0,
5222 htlc_minimum_msat: 0,
5223 htlc_maximum_msat: 0,
5224 cltv_expiry_delta: 0,
5225 features: BlindedHopFeatures::empty(),
5227 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
5228 .with_bolt12_features(bolt12_features.clone()).unwrap();
5229 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
5231 // MPP to 3 2-hop blinded paths
5232 let mut blinded_path_node_0 = blinded_path.clone();
5233 blinded_path_node_0.introduction_node = IntroductionNode::NodeId(nodes[0]);
5234 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
5235 let mut node_0_payinfo = blinded_payinfo.clone();
5236 node_0_payinfo.htlc_maximum_msat = 50_000;
5238 let mut blinded_path_node_7 = blinded_path_node_0.clone();
5239 blinded_path_node_7.introduction_node = IntroductionNode::NodeId(nodes[7]);
5240 let mut node_7_payinfo = blinded_payinfo.clone();
5241 node_7_payinfo.htlc_maximum_msat = 60_000;
5243 let mut blinded_path_node_1 = blinded_path_node_0.clone();
5244 blinded_path_node_1.introduction_node = IntroductionNode::NodeId(nodes[1]);
5245 let mut node_1_payinfo = blinded_payinfo.clone();
5246 node_1_payinfo.htlc_maximum_msat = 180_000;
5248 let two_hop_blinded_payment_params = PaymentParameters::blinded(
5250 (node_0_payinfo, blinded_path_node_0),
5251 (node_7_payinfo, blinded_path_node_7),
5252 (node_1_payinfo, blinded_path_node_1)
5254 .with_bolt12_features(bolt12_features).unwrap();
5255 do_simple_mpp_route_test(two_hop_blinded_payment_params);
5259 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
5260 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5261 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5262 let scorer = ln_test_utils::TestScorer::new();
5263 let random_seed_bytes = [42; 32];
5265 // We need a route consisting of 3 paths:
5266 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5267 // To achieve this, the amount being transferred should be around
5268 // the total capacity of these 3 paths.
5270 // First, we set limits on these (previously unlimited) channels.
5271 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
5273 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5274 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5275 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5276 short_channel_id: 1,
5279 cltv_expiry_delta: 0,
5280 htlc_minimum_msat: 0,
5281 htlc_maximum_msat: 100_000,
5283 fee_proportional_millionths: 0,
5284 excess_data: Vec::new()
5286 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5287 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5288 short_channel_id: 3,
5291 cltv_expiry_delta: 0,
5292 htlc_minimum_msat: 0,
5293 htlc_maximum_msat: 50_000,
5295 fee_proportional_millionths: 0,
5296 excess_data: Vec::new()
5299 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
5300 // (total limit 60).
5301 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5302 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5303 short_channel_id: 12,
5306 cltv_expiry_delta: 0,
5307 htlc_minimum_msat: 0,
5308 htlc_maximum_msat: 60_000,
5310 fee_proportional_millionths: 0,
5311 excess_data: Vec::new()
5313 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5314 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5315 short_channel_id: 13,
5318 cltv_expiry_delta: 0,
5319 htlc_minimum_msat: 0,
5320 htlc_maximum_msat: 60_000,
5322 fee_proportional_millionths: 0,
5323 excess_data: Vec::new()
5326 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5327 // (total capacity 180 sats).
5328 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5329 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5330 short_channel_id: 2,
5333 cltv_expiry_delta: 0,
5334 htlc_minimum_msat: 0,
5335 htlc_maximum_msat: 200_000,
5337 fee_proportional_millionths: 0,
5338 excess_data: Vec::new()
5340 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5341 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5342 short_channel_id: 4,
5345 cltv_expiry_delta: 0,
5346 htlc_minimum_msat: 0,
5347 htlc_maximum_msat: 180_000,
5349 fee_proportional_millionths: 0,
5350 excess_data: Vec::new()
5354 // Attempt to route more than available results in a failure.
5355 let route_params = RouteParameters::from_payment_params_and_value(
5356 payment_params.clone(), 300_000);
5357 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5358 &our_id, &route_params, &network_graph.read_only(), None,
5359 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5360 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5361 } else { panic!(); }
5365 // Attempt to route while setting max_path_count to 0 results in a failure.
5366 let zero_payment_params = payment_params.clone().with_max_path_count(0);
5367 let route_params = RouteParameters::from_payment_params_and_value(
5368 zero_payment_params, 100);
5369 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5370 &our_id, &route_params, &network_graph.read_only(), None,
5371 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5372 assert_eq!(err, "Can't find a route with no paths allowed.");
5373 } else { panic!(); }
5377 // Attempt to route while setting max_path_count to 3 results in a failure.
5378 // This is the case because the minimal_value_contribution_msat would require each path
5379 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5380 let fail_payment_params = payment_params.clone().with_max_path_count(3);
5381 let route_params = RouteParameters::from_payment_params_and_value(
5382 fail_payment_params, 250_000);
5383 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5384 &our_id, &route_params, &network_graph.read_only(), None,
5385 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5386 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5387 } else { panic!(); }
5391 // Now, attempt to route 250 sats (just a bit below the capacity).
5392 // Our algorithm should provide us with these 3 paths.
5393 let route_params = RouteParameters::from_payment_params_and_value(
5394 payment_params.clone(), 250_000);
5395 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5396 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5397 assert_eq!(route.paths.len(), 3);
5398 let mut total_amount_paid_msat = 0;
5399 for path in &route.paths {
5400 if let Some(bt) = &path.blinded_tail {
5401 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5403 assert_eq!(path.hops.len(), 2);
5404 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5406 total_amount_paid_msat += path.final_value_msat();
5408 assert_eq!(total_amount_paid_msat, 250_000);
5412 // Attempt to route an exact amount is also fine
5413 let route_params = RouteParameters::from_payment_params_and_value(
5414 payment_params.clone(), 290_000);
5415 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5416 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5417 assert_eq!(route.paths.len(), 3);
5418 let mut total_amount_paid_msat = 0;
5419 for path in &route.paths {
5420 if payment_params.payee.blinded_route_hints().len() != 0 {
5421 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5422 if let Some(bt) = &path.blinded_tail {
5423 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5424 if bt.hops.len() > 1 {
5425 let network_graph = network_graph.read_only();
5427 NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
5428 payment_params.payee.blinded_route_hints().iter()
5429 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5430 .and_then(|(_, p)| p.public_introduction_node_id(&network_graph))
5435 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5438 assert_eq!(path.hops.len(), 2);
5439 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5441 total_amount_paid_msat += path.final_value_msat();
5443 assert_eq!(total_amount_paid_msat, 290_000);
5448 fn long_mpp_route_test() {
5449 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5450 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5451 let scorer = ln_test_utils::TestScorer::new();
5452 let random_seed_bytes = [42; 32];
5453 let config = UserConfig::default();
5454 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5455 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5458 // We need a route consisting of 3 paths:
5459 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5460 // Note that these paths overlap (channels 5, 12, 13).
5461 // We will route 300 sats.
5462 // Each path will have 100 sats capacity, those channels which
5463 // are used twice will have 200 sats capacity.
5465 // Disable other potential paths.
5466 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5467 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5468 short_channel_id: 2,
5471 cltv_expiry_delta: 0,
5472 htlc_minimum_msat: 0,
5473 htlc_maximum_msat: 100_000,
5475 fee_proportional_millionths: 0,
5476 excess_data: Vec::new()
5478 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5479 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5480 short_channel_id: 7,
5483 cltv_expiry_delta: 0,
5484 htlc_minimum_msat: 0,
5485 htlc_maximum_msat: 100_000,
5487 fee_proportional_millionths: 0,
5488 excess_data: Vec::new()
5491 // Path via {node0, node2} is channels {1, 3, 5}.
5492 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5493 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5494 short_channel_id: 1,
5497 cltv_expiry_delta: 0,
5498 htlc_minimum_msat: 0,
5499 htlc_maximum_msat: 100_000,
5501 fee_proportional_millionths: 0,
5502 excess_data: Vec::new()
5504 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5505 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5506 short_channel_id: 3,
5509 cltv_expiry_delta: 0,
5510 htlc_minimum_msat: 0,
5511 htlc_maximum_msat: 100_000,
5513 fee_proportional_millionths: 0,
5514 excess_data: Vec::new()
5517 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5518 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5519 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5520 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5521 short_channel_id: 5,
5524 cltv_expiry_delta: 0,
5525 htlc_minimum_msat: 0,
5526 htlc_maximum_msat: 200_000,
5528 fee_proportional_millionths: 0,
5529 excess_data: Vec::new()
5531 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5532 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5533 short_channel_id: 5,
5535 flags: 3, // disable direction 1
5536 cltv_expiry_delta: 0,
5537 htlc_minimum_msat: 0,
5538 htlc_maximum_msat: 200_000,
5540 fee_proportional_millionths: 0,
5541 excess_data: Vec::new()
5544 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5545 // Add 100 sats to the capacities of {12, 13}, because these channels
5546 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5547 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5548 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5549 short_channel_id: 12,
5552 cltv_expiry_delta: 0,
5553 htlc_minimum_msat: 0,
5554 htlc_maximum_msat: 200_000,
5556 fee_proportional_millionths: 0,
5557 excess_data: Vec::new()
5559 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5560 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5561 short_channel_id: 13,
5564 cltv_expiry_delta: 0,
5565 htlc_minimum_msat: 0,
5566 htlc_maximum_msat: 200_000,
5568 fee_proportional_millionths: 0,
5569 excess_data: Vec::new()
5572 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5573 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5574 short_channel_id: 6,
5577 cltv_expiry_delta: 0,
5578 htlc_minimum_msat: 0,
5579 htlc_maximum_msat: 100_000,
5581 fee_proportional_millionths: 0,
5582 excess_data: Vec::new()
5584 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5585 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5586 short_channel_id: 11,
5589 cltv_expiry_delta: 0,
5590 htlc_minimum_msat: 0,
5591 htlc_maximum_msat: 100_000,
5593 fee_proportional_millionths: 0,
5594 excess_data: Vec::new()
5597 // Path via {node7, node2} is channels {12, 13, 5}.
5598 // We already limited them to 200 sats (they are used twice for 100 sats).
5599 // Nothing to do here.
5602 // Attempt to route more than available results in a failure.
5603 let route_params = RouteParameters::from_payment_params_and_value(
5604 payment_params.clone(), 350_000);
5605 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5606 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5607 &scorer, &Default::default(), &random_seed_bytes) {
5608 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5609 } else { panic!(); }
5613 // Now, attempt to route 300 sats (exact amount we can route).
5614 // Our algorithm should provide us with these 3 paths, 100 sats each.
5615 let route_params = RouteParameters::from_payment_params_and_value(
5616 payment_params, 300_000);
5617 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5618 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5619 assert_eq!(route.paths.len(), 3);
5621 let mut total_amount_paid_msat = 0;
5622 for path in &route.paths {
5623 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5624 total_amount_paid_msat += path.final_value_msat();
5626 assert_eq!(total_amount_paid_msat, 300_000);
5632 fn mpp_cheaper_route_test() {
5633 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5634 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5635 let scorer = ln_test_utils::TestScorer::new();
5636 let random_seed_bytes = [42; 32];
5637 let config = UserConfig::default();
5638 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5639 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5642 // This test checks that if we have two cheaper paths and one more expensive path,
5643 // so that liquidity-wise any 2 of 3 combination is sufficient,
5644 // two cheaper paths will be taken.
5645 // These paths have equal available liquidity.
5647 // We need a combination of 3 paths:
5648 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5649 // Note that these paths overlap (channels 5, 12, 13).
5650 // Each path will have 100 sats capacity, those channels which
5651 // are used twice will have 200 sats capacity.
5653 // Disable other potential paths.
5654 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5655 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5656 short_channel_id: 2,
5659 cltv_expiry_delta: 0,
5660 htlc_minimum_msat: 0,
5661 htlc_maximum_msat: 100_000,
5663 fee_proportional_millionths: 0,
5664 excess_data: Vec::new()
5666 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5667 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5668 short_channel_id: 7,
5671 cltv_expiry_delta: 0,
5672 htlc_minimum_msat: 0,
5673 htlc_maximum_msat: 100_000,
5675 fee_proportional_millionths: 0,
5676 excess_data: Vec::new()
5679 // Path via {node0, node2} is channels {1, 3, 5}.
5680 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5681 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5682 short_channel_id: 1,
5685 cltv_expiry_delta: 0,
5686 htlc_minimum_msat: 0,
5687 htlc_maximum_msat: 100_000,
5689 fee_proportional_millionths: 0,
5690 excess_data: Vec::new()
5692 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5693 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5694 short_channel_id: 3,
5697 cltv_expiry_delta: 0,
5698 htlc_minimum_msat: 0,
5699 htlc_maximum_msat: 100_000,
5701 fee_proportional_millionths: 0,
5702 excess_data: Vec::new()
5705 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5706 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5707 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5708 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5709 short_channel_id: 5,
5712 cltv_expiry_delta: 0,
5713 htlc_minimum_msat: 0,
5714 htlc_maximum_msat: 200_000,
5716 fee_proportional_millionths: 0,
5717 excess_data: Vec::new()
5719 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5720 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5721 short_channel_id: 5,
5723 flags: 3, // disable direction 1
5724 cltv_expiry_delta: 0,
5725 htlc_minimum_msat: 0,
5726 htlc_maximum_msat: 200_000,
5728 fee_proportional_millionths: 0,
5729 excess_data: Vec::new()
5732 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5733 // Add 100 sats to the capacities of {12, 13}, because these channels
5734 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5735 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5736 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5737 short_channel_id: 12,
5740 cltv_expiry_delta: 0,
5741 htlc_minimum_msat: 0,
5742 htlc_maximum_msat: 200_000,
5744 fee_proportional_millionths: 0,
5745 excess_data: Vec::new()
5747 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5748 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5749 short_channel_id: 13,
5752 cltv_expiry_delta: 0,
5753 htlc_minimum_msat: 0,
5754 htlc_maximum_msat: 200_000,
5756 fee_proportional_millionths: 0,
5757 excess_data: Vec::new()
5760 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5761 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5762 short_channel_id: 6,
5765 cltv_expiry_delta: 0,
5766 htlc_minimum_msat: 0,
5767 htlc_maximum_msat: 100_000,
5768 fee_base_msat: 1_000,
5769 fee_proportional_millionths: 0,
5770 excess_data: Vec::new()
5772 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5773 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5774 short_channel_id: 11,
5777 cltv_expiry_delta: 0,
5778 htlc_minimum_msat: 0,
5779 htlc_maximum_msat: 100_000,
5781 fee_proportional_millionths: 0,
5782 excess_data: Vec::new()
5785 // Path via {node7, node2} is channels {12, 13, 5}.
5786 // We already limited them to 200 sats (they are used twice for 100 sats).
5787 // Nothing to do here.
5790 // Now, attempt to route 180 sats.
5791 // Our algorithm should provide us with these 2 paths.
5792 let route_params = RouteParameters::from_payment_params_and_value(
5793 payment_params, 180_000);
5794 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5795 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5796 assert_eq!(route.paths.len(), 2);
5798 let mut total_value_transferred_msat = 0;
5799 let mut total_paid_msat = 0;
5800 for path in &route.paths {
5801 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5802 total_value_transferred_msat += path.final_value_msat();
5803 for hop in &path.hops {
5804 total_paid_msat += hop.fee_msat;
5807 // If we paid fee, this would be higher.
5808 assert_eq!(total_value_transferred_msat, 180_000);
5809 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5810 assert_eq!(total_fees_paid, 0);
5815 fn fees_on_mpp_route_test() {
5816 // This test makes sure that MPP algorithm properly takes into account
5817 // fees charged on the channels, by making the fees impactful:
5818 // if the fee is not properly accounted for, the behavior is different.
5819 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5820 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5821 let scorer = ln_test_utils::TestScorer::new();
5822 let random_seed_bytes = [42; 32];
5823 let config = UserConfig::default();
5824 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5825 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5828 // We need a route consisting of 2 paths:
5829 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5830 // We will route 200 sats, Each path will have 100 sats capacity.
5832 // This test is not particularly stable: e.g.,
5833 // there's a way to route via {node0, node2, node4}.
5834 // It works while pathfinding is deterministic, but can be broken otherwise.
5835 // It's fine to ignore this concern for now.
5837 // Disable other potential paths.
5838 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5839 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5840 short_channel_id: 2,
5843 cltv_expiry_delta: 0,
5844 htlc_minimum_msat: 0,
5845 htlc_maximum_msat: 100_000,
5847 fee_proportional_millionths: 0,
5848 excess_data: Vec::new()
5851 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5852 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5853 short_channel_id: 7,
5856 cltv_expiry_delta: 0,
5857 htlc_minimum_msat: 0,
5858 htlc_maximum_msat: 100_000,
5860 fee_proportional_millionths: 0,
5861 excess_data: Vec::new()
5864 // Path via {node0, node2} is channels {1, 3, 5}.
5865 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5866 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5867 short_channel_id: 1,
5870 cltv_expiry_delta: 0,
5871 htlc_minimum_msat: 0,
5872 htlc_maximum_msat: 100_000,
5874 fee_proportional_millionths: 0,
5875 excess_data: Vec::new()
5877 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5878 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5879 short_channel_id: 3,
5882 cltv_expiry_delta: 0,
5883 htlc_minimum_msat: 0,
5884 htlc_maximum_msat: 100_000,
5886 fee_proportional_millionths: 0,
5887 excess_data: Vec::new()
5890 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5891 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5892 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5893 short_channel_id: 5,
5896 cltv_expiry_delta: 0,
5897 htlc_minimum_msat: 0,
5898 htlc_maximum_msat: 100_000,
5900 fee_proportional_millionths: 0,
5901 excess_data: Vec::new()
5903 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5904 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5905 short_channel_id: 5,
5907 flags: 3, // Disable direction 1
5908 cltv_expiry_delta: 0,
5909 htlc_minimum_msat: 0,
5910 htlc_maximum_msat: 100_000,
5912 fee_proportional_millionths: 0,
5913 excess_data: Vec::new()
5916 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5917 // All channels should be 100 sats capacity. But for the fee experiment,
5918 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5919 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5920 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5921 // so no matter how large are other channels,
5922 // the whole path will be limited by 100 sats with just these 2 conditions:
5923 // - channel 12 capacity is 250 sats
5924 // - fee for channel 6 is 150 sats
5925 // Let's test this by enforcing these 2 conditions and removing other limits.
5926 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5927 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5928 short_channel_id: 12,
5931 cltv_expiry_delta: 0,
5932 htlc_minimum_msat: 0,
5933 htlc_maximum_msat: 250_000,
5935 fee_proportional_millionths: 0,
5936 excess_data: Vec::new()
5938 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5939 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5940 short_channel_id: 13,
5943 cltv_expiry_delta: 0,
5944 htlc_minimum_msat: 0,
5945 htlc_maximum_msat: MAX_VALUE_MSAT,
5947 fee_proportional_millionths: 0,
5948 excess_data: Vec::new()
5951 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5952 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5953 short_channel_id: 6,
5956 cltv_expiry_delta: 0,
5957 htlc_minimum_msat: 0,
5958 htlc_maximum_msat: MAX_VALUE_MSAT,
5959 fee_base_msat: 150_000,
5960 fee_proportional_millionths: 0,
5961 excess_data: Vec::new()
5963 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5964 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5965 short_channel_id: 11,
5968 cltv_expiry_delta: 0,
5969 htlc_minimum_msat: 0,
5970 htlc_maximum_msat: MAX_VALUE_MSAT,
5972 fee_proportional_millionths: 0,
5973 excess_data: Vec::new()
5977 // Attempt to route more than available results in a failure.
5978 let route_params = RouteParameters::from_payment_params_and_value(
5979 payment_params.clone(), 210_000);
5980 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5981 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5982 &scorer, &Default::default(), &random_seed_bytes) {
5983 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5984 } else { panic!(); }
5988 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5989 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5990 max_total_routing_fee_msat: Some(149_999) };
5991 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5992 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5993 &scorer, &Default::default(), &random_seed_bytes) {
5994 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5995 } else { panic!(); }
5999 // Now, attempt to route 200 sats (exact amount we can route).
6000 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
6001 max_total_routing_fee_msat: Some(150_000) };
6002 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6003 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6004 assert_eq!(route.paths.len(), 2);
6006 let mut total_amount_paid_msat = 0;
6007 for path in &route.paths {
6008 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
6009 total_amount_paid_msat += path.final_value_msat();
6011 assert_eq!(total_amount_paid_msat, 200_000);
6012 assert_eq!(route.get_total_fees(), 150_000);
6017 fn mpp_with_last_hops() {
6018 // Previously, if we tried to send an MPP payment to a destination which was only reachable
6019 // via a single last-hop route hint, we'd fail to route if we first collected routes
6020 // totaling close but not quite enough to fund the full payment.
6022 // This was because we considered last-hop hints to have exactly the sought payment amount
6023 // instead of the amount we were trying to collect, needlessly limiting our path searching
6024 // at the very first hop.
6026 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
6027 // criterion to cause us to refuse all routes at the last hop hint which would be considered
6028 // to only have the remaining to-collect amount in available liquidity.
6030 // This bug appeared in production in some specific channel configurations.
6031 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6032 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6033 let scorer = ln_test_utils::TestScorer::new();
6034 let random_seed_bytes = [42; 32];
6035 let config = UserConfig::default();
6036 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
6037 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
6038 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
6039 src_node_id: nodes[2],
6040 short_channel_id: 42,
6041 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
6042 cltv_expiry_delta: 42,
6043 htlc_minimum_msat: None,
6044 htlc_maximum_msat: None,
6045 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
6047 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
6048 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
6049 // would first use the no-fee route and then fail to find a path along the second route as
6050 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
6051 // under 5% of our payment amount.
6052 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6053 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6054 short_channel_id: 1,
6057 cltv_expiry_delta: (5 << 4) | 5,
6058 htlc_minimum_msat: 0,
6059 htlc_maximum_msat: 99_000,
6060 fee_base_msat: u32::max_value(),
6061 fee_proportional_millionths: u32::max_value(),
6062 excess_data: Vec::new()
6064 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6065 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6066 short_channel_id: 2,
6069 cltv_expiry_delta: (5 << 4) | 3,
6070 htlc_minimum_msat: 0,
6071 htlc_maximum_msat: 99_000,
6072 fee_base_msat: u32::max_value(),
6073 fee_proportional_millionths: u32::max_value(),
6074 excess_data: Vec::new()
6076 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6077 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6078 short_channel_id: 4,
6081 cltv_expiry_delta: (4 << 4) | 1,
6082 htlc_minimum_msat: 0,
6083 htlc_maximum_msat: MAX_VALUE_MSAT,
6085 fee_proportional_millionths: 0,
6086 excess_data: Vec::new()
6088 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6089 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6090 short_channel_id: 13,
6092 flags: 0|2, // Channel disabled
6093 cltv_expiry_delta: (13 << 4) | 1,
6094 htlc_minimum_msat: 0,
6095 htlc_maximum_msat: MAX_VALUE_MSAT,
6097 fee_proportional_millionths: 2000000,
6098 excess_data: Vec::new()
6101 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
6103 let route_params = RouteParameters::from_payment_params_and_value(
6104 payment_params, 100_000);
6105 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6106 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6107 assert_eq!(route.paths.len(), 2);
6108 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
6109 // Paths are manually ordered ordered by SCID, so:
6110 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
6111 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
6112 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
6113 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
6114 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
6115 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
6116 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
6117 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
6118 assert_eq!(route.get_total_fees(), 1);
6119 assert_eq!(route.get_total_amount(), 100_000);
6123 fn drop_lowest_channel_mpp_route_test() {
6124 // This test checks that low-capacity channel is dropped when after
6125 // path finding we realize that we found more capacity than we need.
6126 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6127 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6128 let scorer = ln_test_utils::TestScorer::new();
6129 let random_seed_bytes = [42; 32];
6130 let config = UserConfig::default();
6131 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6132 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6134 .with_max_channel_saturation_power_of_half(0);
6136 // We need a route consisting of 3 paths:
6137 // From our node to node2 via node0, node7, node1 (three paths one hop each).
6139 // The first and the second paths should be sufficient, but the third should be
6140 // cheaper, so that we select it but drop later.
6142 // First, we set limits on these (previously unlimited) channels.
6143 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
6145 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
6146 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6147 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6148 short_channel_id: 1,
6151 cltv_expiry_delta: 0,
6152 htlc_minimum_msat: 0,
6153 htlc_maximum_msat: 100_000,
6155 fee_proportional_millionths: 0,
6156 excess_data: Vec::new()
6158 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6159 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6160 short_channel_id: 3,
6163 cltv_expiry_delta: 0,
6164 htlc_minimum_msat: 0,
6165 htlc_maximum_msat: 50_000,
6167 fee_proportional_millionths: 0,
6168 excess_data: Vec::new()
6171 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
6172 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6173 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6174 short_channel_id: 12,
6177 cltv_expiry_delta: 0,
6178 htlc_minimum_msat: 0,
6179 htlc_maximum_msat: 60_000,
6181 fee_proportional_millionths: 0,
6182 excess_data: Vec::new()
6184 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6185 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6186 short_channel_id: 13,
6189 cltv_expiry_delta: 0,
6190 htlc_minimum_msat: 0,
6191 htlc_maximum_msat: 60_000,
6193 fee_proportional_millionths: 0,
6194 excess_data: Vec::new()
6197 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
6198 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6199 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6200 short_channel_id: 2,
6203 cltv_expiry_delta: 0,
6204 htlc_minimum_msat: 0,
6205 htlc_maximum_msat: 20_000,
6207 fee_proportional_millionths: 0,
6208 excess_data: Vec::new()
6210 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6211 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6212 short_channel_id: 4,
6215 cltv_expiry_delta: 0,
6216 htlc_minimum_msat: 0,
6217 htlc_maximum_msat: 20_000,
6219 fee_proportional_millionths: 0,
6220 excess_data: Vec::new()
6224 // Attempt to route more than available results in a failure.
6225 let route_params = RouteParameters::from_payment_params_and_value(
6226 payment_params.clone(), 150_000);
6227 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6228 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6229 &scorer, &Default::default(), &random_seed_bytes) {
6230 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6231 } else { panic!(); }
6235 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
6236 // Our algorithm should provide us with these 3 paths.
6237 let route_params = RouteParameters::from_payment_params_and_value(
6238 payment_params.clone(), 125_000);
6239 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6240 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6241 assert_eq!(route.paths.len(), 3);
6242 let mut total_amount_paid_msat = 0;
6243 for path in &route.paths {
6244 assert_eq!(path.hops.len(), 2);
6245 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6246 total_amount_paid_msat += path.final_value_msat();
6248 assert_eq!(total_amount_paid_msat, 125_000);
6252 // Attempt to route without the last small cheap channel
6253 let route_params = RouteParameters::from_payment_params_and_value(
6254 payment_params, 90_000);
6255 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6256 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6257 assert_eq!(route.paths.len(), 2);
6258 let mut total_amount_paid_msat = 0;
6259 for path in &route.paths {
6260 assert_eq!(path.hops.len(), 2);
6261 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6262 total_amount_paid_msat += path.final_value_msat();
6264 assert_eq!(total_amount_paid_msat, 90_000);
6269 fn min_criteria_consistency() {
6270 // Test that we don't use an inconsistent metric between updating and walking nodes during
6271 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
6272 // was updated with a different criterion from the heap sorting, resulting in loops in
6273 // calculated paths. We test for that specific case here.
6275 // We construct a network that looks like this:
6277 // node2 -1(3)2- node3
6281 // node1 -1(5)2- node4 -1(1)2- node6
6287 // We create a loop on the side of our real path - our destination is node 6, with a
6288 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
6289 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
6290 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
6291 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
6292 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
6293 // "previous hop" being set to node 3, creating a loop in the path.
6294 let secp_ctx = Secp256k1::new();
6295 let logger = Arc::new(ln_test_utils::TestLogger::new());
6296 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6297 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
6298 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6299 let scorer = ln_test_utils::TestScorer::new();
6300 let random_seed_bytes = [42; 32];
6301 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
6303 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
6304 for (key, flags) in [(&our_privkey, 0), (&privkeys[1], 3)] {
6305 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6306 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6307 short_channel_id: 6,
6310 cltv_expiry_delta: (6 << 4) | 0,
6311 htlc_minimum_msat: 0,
6312 htlc_maximum_msat: MAX_VALUE_MSAT,
6314 fee_proportional_millionths: 0,
6315 excess_data: Vec::new()
6318 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
6320 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6321 for (key, flags) in [(&privkeys[1], 0), (&privkeys[4], 3)] {
6322 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6323 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6324 short_channel_id: 5,
6327 cltv_expiry_delta: (5 << 4) | 0,
6328 htlc_minimum_msat: 0,
6329 htlc_maximum_msat: MAX_VALUE_MSAT,
6331 fee_proportional_millionths: 0,
6332 excess_data: Vec::new()
6335 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
6337 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
6338 for (key, flags) in [(&privkeys[4], 0), (&privkeys[3], 3)] {
6339 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6340 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6341 short_channel_id: 4,
6344 cltv_expiry_delta: (4 << 4) | 0,
6345 htlc_minimum_msat: 0,
6346 htlc_maximum_msat: MAX_VALUE_MSAT,
6348 fee_proportional_millionths: 0,
6349 excess_data: Vec::new()
6352 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6354 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6355 for (key, flags) in [(&privkeys[3], 0), (&privkeys[2], 3)] {
6356 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6357 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6358 short_channel_id: 3,
6361 cltv_expiry_delta: (3 << 4) | 0,
6362 htlc_minimum_msat: 0,
6363 htlc_maximum_msat: MAX_VALUE_MSAT,
6365 fee_proportional_millionths: 0,
6366 excess_data: Vec::new()
6369 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6371 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6372 for (key, flags) in [(&privkeys[2], 0), (&privkeys[4], 3)] {
6373 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6374 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6375 short_channel_id: 2,
6378 cltv_expiry_delta: (2 << 4) | 0,
6379 htlc_minimum_msat: 0,
6380 htlc_maximum_msat: MAX_VALUE_MSAT,
6382 fee_proportional_millionths: 0,
6383 excess_data: Vec::new()
6387 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6388 for (key, flags) in [(&privkeys[4], 0), (&privkeys[6], 3)] {
6389 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6390 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6391 short_channel_id: 1,
6394 cltv_expiry_delta: (1 << 4) | 0,
6395 htlc_minimum_msat: 100,
6396 htlc_maximum_msat: MAX_VALUE_MSAT,
6398 fee_proportional_millionths: 0,
6399 excess_data: Vec::new()
6402 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6405 // Now ensure the route flows simply over nodes 1 and 4 to 6.
6406 let route_params = RouteParameters::from_payment_params_and_value(
6407 payment_params, 10_000);
6408 let route = get_route(&our_id, &route_params, &network.read_only(), None,
6409 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6410 assert_eq!(route.paths.len(), 1);
6411 assert_eq!(route.paths[0].hops.len(), 3);
6413 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6414 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6415 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6416 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6417 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6418 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6420 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6421 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6422 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6423 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6424 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6425 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6427 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6428 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6429 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6430 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6431 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6432 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6438 fn exact_fee_liquidity_limit() {
6439 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6440 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6441 // we calculated fees on a higher value, resulting in us ignoring such paths.
6442 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6443 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6444 let scorer = ln_test_utils::TestScorer::new();
6445 let random_seed_bytes = [42; 32];
6446 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6448 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6450 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6451 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6452 short_channel_id: 2,
6455 cltv_expiry_delta: 0,
6456 htlc_minimum_msat: 0,
6457 htlc_maximum_msat: 85_000,
6459 fee_proportional_millionths: 0,
6460 excess_data: Vec::new()
6463 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6464 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6465 short_channel_id: 12,
6468 cltv_expiry_delta: (4 << 4) | 1,
6469 htlc_minimum_msat: 0,
6470 htlc_maximum_msat: 270_000,
6472 fee_proportional_millionths: 1000000,
6473 excess_data: Vec::new()
6477 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6478 // 200% fee charged channel 13 in the 1-to-2 direction.
6479 let mut route_params = RouteParameters::from_payment_params_and_value(
6480 payment_params, 90_000);
6481 route_params.max_total_routing_fee_msat = Some(90_000*2);
6482 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6483 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6484 assert_eq!(route.paths.len(), 1);
6485 assert_eq!(route.paths[0].hops.len(), 2);
6487 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6488 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6489 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6490 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6491 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6492 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6494 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6495 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6496 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6497 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6498 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6499 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6504 fn htlc_max_reduction_below_min() {
6505 // Test that if, while walking the graph, we reduce the value being sent to meet an
6506 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6507 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6508 // resulting in us thinking there is no possible path, even if other paths exist.
6509 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6510 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6511 let scorer = ln_test_utils::TestScorer::new();
6512 let random_seed_bytes = [42; 32];
6513 let config = UserConfig::default();
6514 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6515 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6518 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6519 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6520 // then try to send 90_000.
6521 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6522 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6523 short_channel_id: 2,
6526 cltv_expiry_delta: 0,
6527 htlc_minimum_msat: 0,
6528 htlc_maximum_msat: 80_000,
6530 fee_proportional_millionths: 0,
6531 excess_data: Vec::new()
6533 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6534 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6535 short_channel_id: 4,
6538 cltv_expiry_delta: (4 << 4) | 1,
6539 htlc_minimum_msat: 90_000,
6540 htlc_maximum_msat: MAX_VALUE_MSAT,
6542 fee_proportional_millionths: 0,
6543 excess_data: Vec::new()
6547 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6548 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6549 // expensive) channels 12-13 path.
6550 let mut route_params = RouteParameters::from_payment_params_and_value(
6551 payment_params, 90_000);
6552 route_params.max_total_routing_fee_msat = Some(90_000*2);
6553 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6554 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6555 assert_eq!(route.paths.len(), 1);
6556 assert_eq!(route.paths[0].hops.len(), 2);
6558 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6559 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6560 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6561 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6562 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6563 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6565 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6566 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6567 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6568 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6569 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6570 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6575 fn multiple_direct_first_hops() {
6576 // Previously we'd only ever considered one first hop path per counterparty.
6577 // However, as we don't restrict users to one channel per peer, we really need to support
6578 // looking at all first hop paths.
6579 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6580 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6581 // route over multiple channels with the same first hop.
6582 let secp_ctx = Secp256k1::new();
6583 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6584 let logger = Arc::new(ln_test_utils::TestLogger::new());
6585 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6586 let scorer = ln_test_utils::TestScorer::new();
6587 let config = UserConfig::default();
6588 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6589 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6591 let random_seed_bytes = [42; 32];
6594 let route_params = RouteParameters::from_payment_params_and_value(
6595 payment_params.clone(), 100_000);
6596 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6597 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6598 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6599 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6600 assert_eq!(route.paths.len(), 1);
6601 assert_eq!(route.paths[0].hops.len(), 1);
6603 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6604 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6605 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6608 let route_params = RouteParameters::from_payment_params_and_value(
6609 payment_params.clone(), 100_000);
6610 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6611 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6612 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6613 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6614 assert_eq!(route.paths.len(), 2);
6615 assert_eq!(route.paths[0].hops.len(), 1);
6616 assert_eq!(route.paths[1].hops.len(), 1);
6618 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6619 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6621 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6622 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6624 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6625 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6629 // If we have a bunch of outbound channels to the same node, where most are not
6630 // sufficient to pay the full payment, but one is, we should default to just using the
6631 // one single channel that has sufficient balance, avoiding MPP.
6633 // If we have several options above the 3xpayment value threshold, we should pick the
6634 // smallest of them, avoiding further fragmenting our available outbound balance to
6636 let route_params = RouteParameters::from_payment_params_and_value(
6637 payment_params, 100_000);
6638 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6639 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6640 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6641 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6642 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6643 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6644 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6645 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6646 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6647 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6648 assert_eq!(route.paths.len(), 1);
6649 assert_eq!(route.paths[0].hops.len(), 1);
6651 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6652 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6653 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6658 fn prefers_shorter_route_with_higher_fees() {
6659 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6660 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6661 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6663 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6664 let scorer = ln_test_utils::TestScorer::new();
6665 let random_seed_bytes = [42; 32];
6666 let route_params = RouteParameters::from_payment_params_and_value(
6667 payment_params.clone(), 100);
6668 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6669 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6670 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6672 assert_eq!(route.get_total_fees(), 100);
6673 assert_eq!(route.get_total_amount(), 100);
6674 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6676 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6677 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6678 let scorer = FixedPenaltyScorer::with_penalty(100);
6679 let route_params = RouteParameters::from_payment_params_and_value(
6680 payment_params, 100);
6681 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6682 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6683 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6685 assert_eq!(route.get_total_fees(), 300);
6686 assert_eq!(route.get_total_amount(), 100);
6687 assert_eq!(path, vec![2, 4, 7, 10]);
6690 struct BadChannelScorer {
6691 short_channel_id: u64,
6695 impl Writeable for BadChannelScorer {
6696 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6698 impl ScoreLookUp for BadChannelScorer {
6699 type ScoreParams = ();
6700 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6701 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6705 struct BadNodeScorer {
6710 impl Writeable for BadNodeScorer {
6711 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6714 impl ScoreLookUp for BadNodeScorer {
6715 type ScoreParams = ();
6716 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6717 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6722 fn avoids_routing_through_bad_channels_and_nodes() {
6723 let (secp_ctx, network, _, _, logger) = build_graph();
6724 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6725 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6726 let network_graph = network.read_only();
6728 // A path to nodes[6] exists when no penalties are applied to any channel.
6729 let scorer = ln_test_utils::TestScorer::new();
6730 let random_seed_bytes = [42; 32];
6731 let route_params = RouteParameters::from_payment_params_and_value(
6732 payment_params, 100);
6733 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6734 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6735 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6737 assert_eq!(route.get_total_fees(), 100);
6738 assert_eq!(route.get_total_amount(), 100);
6739 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6741 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6742 let scorer = BadChannelScorer { short_channel_id: 6 };
6743 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6744 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6745 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6747 assert_eq!(route.get_total_fees(), 300);
6748 assert_eq!(route.get_total_amount(), 100);
6749 assert_eq!(path, vec![2, 4, 7, 10]);
6751 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6752 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6753 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6754 &scorer, &Default::default(), &random_seed_bytes) {
6755 Err(LightningError { err, .. } ) => {
6756 assert_eq!(err, "Failed to find a path to the given destination");
6758 Ok(_) => panic!("Expected error"),
6763 fn total_fees_single_path() {
6765 paths: vec![Path { hops: vec![
6767 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6768 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6769 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6772 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6773 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6774 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6777 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6778 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6779 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6781 ], blinded_tail: None }],
6785 assert_eq!(route.get_total_fees(), 250);
6786 assert_eq!(route.get_total_amount(), 225);
6790 fn total_fees_multi_path() {
6792 paths: vec![Path { hops: vec![
6794 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6795 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6796 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6799 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6800 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6801 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6803 ], blinded_tail: None }, Path { hops: vec![
6805 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6806 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6807 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6810 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6811 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6812 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6814 ], blinded_tail: None }],
6818 assert_eq!(route.get_total_fees(), 200);
6819 assert_eq!(route.get_total_amount(), 300);
6823 fn total_empty_route_no_panic() {
6824 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6825 // would both panic if the route was completely empty. We test to ensure they return 0
6826 // here, even though its somewhat nonsensical as a route.
6827 let route = Route { paths: Vec::new(), route_params: None };
6829 assert_eq!(route.get_total_fees(), 0);
6830 assert_eq!(route.get_total_amount(), 0);
6834 fn limits_total_cltv_delta() {
6835 let (secp_ctx, network, _, _, logger) = build_graph();
6836 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6837 let network_graph = network.read_only();
6839 let scorer = ln_test_utils::TestScorer::new();
6841 // Make sure that generally there is at least one route available
6842 let feasible_max_total_cltv_delta = 1008;
6843 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6844 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6845 let random_seed_bytes = [42; 32];
6846 let route_params = RouteParameters::from_payment_params_and_value(
6847 feasible_payment_params, 100);
6848 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6849 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6850 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6851 assert_ne!(path.len(), 0);
6853 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6854 let fail_max_total_cltv_delta = 23;
6855 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6856 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6857 let route_params = RouteParameters::from_payment_params_and_value(
6858 fail_payment_params, 100);
6859 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6860 &Default::default(), &random_seed_bytes)
6862 Err(LightningError { err, .. } ) => {
6863 assert_eq!(err, "Failed to find a path to the given destination");
6865 Ok(_) => panic!("Expected error"),
6870 fn avoids_recently_failed_paths() {
6871 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6872 // randomly inserting channels into it until we can't find a route anymore.
6873 let (secp_ctx, network, _, _, logger) = build_graph();
6874 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6875 let network_graph = network.read_only();
6877 let scorer = ln_test_utils::TestScorer::new();
6878 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6879 .with_max_path_count(1);
6880 let random_seed_bytes = [42; 32];
6882 // We should be able to find a route initially, and then after we fail a few random
6883 // channels eventually we won't be able to any longer.
6884 let route_params = RouteParameters::from_payment_params_and_value(
6885 payment_params.clone(), 100);
6886 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6887 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6889 let route_params = RouteParameters::from_payment_params_and_value(
6890 payment_params.clone(), 100);
6891 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6892 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6894 for chan in route.paths[0].hops.iter() {
6895 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6897 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6898 % route.paths[0].hops.len();
6899 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6905 fn limits_path_length() {
6906 let (secp_ctx, network, _, _, logger) = build_line_graph();
6907 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6908 let network_graph = network.read_only();
6910 let scorer = ln_test_utils::TestScorer::new();
6911 let random_seed_bytes = [42; 32];
6913 // First check we can actually create a long route on this graph.
6914 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6915 let route_params = RouteParameters::from_payment_params_and_value(
6916 feasible_payment_params, 100);
6917 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6918 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6919 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6920 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6922 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6923 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6924 let route_params = RouteParameters::from_payment_params_and_value(
6925 fail_payment_params, 100);
6926 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6927 &Default::default(), &random_seed_bytes)
6929 Err(LightningError { err, .. } ) => {
6930 assert_eq!(err, "Failed to find a path to the given destination");
6932 Ok(_) => panic!("Expected error"),
6937 fn adds_and_limits_cltv_offset() {
6938 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6939 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6941 let scorer = ln_test_utils::TestScorer::new();
6943 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6944 let random_seed_bytes = [42; 32];
6945 let route_params = RouteParameters::from_payment_params_and_value(
6946 payment_params.clone(), 100);
6947 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6948 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6949 assert_eq!(route.paths.len(), 1);
6951 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6953 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6954 let mut route_default = route.clone();
6955 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6956 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6957 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6958 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6959 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6961 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6962 let mut route_limited = route.clone();
6963 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6964 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6965 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6966 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6967 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6971 fn adds_plausible_cltv_offset() {
6972 let (secp_ctx, network, _, _, logger) = build_graph();
6973 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6974 let network_graph = network.read_only();
6975 let network_nodes = network_graph.nodes();
6976 let network_channels = network_graph.channels();
6977 let scorer = ln_test_utils::TestScorer::new();
6978 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6979 let random_seed_bytes = [42; 32];
6981 let route_params = RouteParameters::from_payment_params_and_value(
6982 payment_params.clone(), 100);
6983 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6984 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6985 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6987 let mut path_plausibility = vec![];
6989 for p in route.paths {
6990 // 1. Select random observation point
6991 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6992 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6994 prng.process_in_place(&mut random_bytes);
6995 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6996 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6998 // 2. Calculate what CLTV expiry delta we would observe there
6999 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
7001 // 3. Starting from the observation point, find candidate paths
7002 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
7003 candidates.push_back((observation_point, vec![]));
7005 let mut found_plausible_candidate = false;
7007 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
7008 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
7009 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
7010 found_plausible_candidate = true;
7011 break 'candidate_loop;
7015 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
7016 for channel_id in &cur_node.channels {
7017 if let Some(channel_info) = network_channels.get(&channel_id) {
7018 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
7019 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
7020 if cur_path_cltv_deltas.iter().sum::<u32>()
7021 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
7022 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
7023 new_path_cltv_deltas.push(next_cltv_expiry_delta);
7024 candidates.push_back((*next_id, new_path_cltv_deltas));
7032 path_plausibility.push(found_plausible_candidate);
7034 assert!(path_plausibility.iter().all(|x| *x));
7038 fn builds_correct_path_from_hops() {
7039 let (secp_ctx, network, _, _, logger) = build_graph();
7040 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7041 let network_graph = network.read_only();
7043 let random_seed_bytes = [42; 32];
7044 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
7045 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
7046 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
7047 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
7048 Arc::clone(&logger), &random_seed_bytes).unwrap();
7049 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
7050 assert_eq!(hops.len(), route.paths[0].hops.len());
7051 for (idx, hop_pubkey) in hops.iter().enumerate() {
7052 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
7057 fn avoids_saturating_channels() {
7058 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
7059 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
7060 let decay_params = ProbabilisticScoringDecayParameters::default();
7061 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
7063 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
7064 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
7065 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7066 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7067 short_channel_id: 4,
7070 cltv_expiry_delta: (4 << 4) | 1,
7071 htlc_minimum_msat: 0,
7072 htlc_maximum_msat: 250_000_000,
7074 fee_proportional_millionths: 0,
7075 excess_data: Vec::new()
7077 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
7078 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7079 short_channel_id: 13,
7082 cltv_expiry_delta: (13 << 4) | 1,
7083 htlc_minimum_msat: 0,
7084 htlc_maximum_msat: 250_000_000,
7086 fee_proportional_millionths: 0,
7087 excess_data: Vec::new()
7090 let config = UserConfig::default();
7091 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
7092 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7094 let random_seed_bytes = [42; 32];
7096 // 100,000 sats is less than the available liquidity on each channel, set above.
7097 let route_params = RouteParameters::from_payment_params_and_value(
7098 payment_params, 100_000_000);
7099 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
7100 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
7101 assert_eq!(route.paths.len(), 2);
7102 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
7103 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
7106 #[cfg(feature = "std")]
7107 pub(super) fn random_init_seed() -> u64 {
7108 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
7109 use core::hash::{BuildHasher, Hasher};
7110 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
7111 println!("Using seed of {}", seed);
7116 #[cfg(feature = "std")]
7117 fn generate_routes() {
7118 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7120 let logger = ln_test_utils::TestLogger::new();
7121 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7129 let params = ProbabilisticScoringFeeParameters::default();
7130 let features = super::Bolt11InvoiceFeatures::empty();
7132 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7136 #[cfg(feature = "std")]
7137 fn generate_routes_mpp() {
7138 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7140 let logger = ln_test_utils::TestLogger::new();
7141 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7149 let params = ProbabilisticScoringFeeParameters::default();
7150 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7152 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7156 #[cfg(feature = "std")]
7157 fn generate_large_mpp_routes() {
7158 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7160 let logger = ln_test_utils::TestLogger::new();
7161 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7169 let params = ProbabilisticScoringFeeParameters::default();
7170 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7172 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
7176 fn honors_manual_penalties() {
7177 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
7178 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7180 let random_seed_bytes = [42; 32];
7181 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
7182 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
7184 // First check set manual penalties are returned by the scorer.
7185 let usage = ChannelUsage {
7187 inflight_htlc_msat: 0,
7188 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
7190 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
7191 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
7192 let network_graph = network_graph.read_only();
7193 let channels = network_graph.channels();
7194 let channel = channels.get(&5).unwrap();
7195 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
7196 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop(PublicHopCandidate {
7198 short_channel_id: 5,
7200 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
7202 // Then check we can get a normal route
7203 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
7204 let route_params = RouteParameters::from_payment_params_and_value(
7205 payment_params, 100);
7206 let route = get_route(&our_id, &route_params, &network_graph, None,
7207 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
7208 assert!(route.is_ok());
7210 // Then check that we can't get a route if we ban an intermediate node.
7211 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
7212 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7213 assert!(route.is_err());
7215 // Finally make sure we can route again, when we remove the ban.
7216 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
7217 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7218 assert!(route.is_ok());
7222 fn abide_by_route_hint_max_htlc() {
7223 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
7224 // params in the final route.
7225 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7226 let netgraph = network_graph.read_only();
7227 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7228 let scorer = ln_test_utils::TestScorer::new();
7229 let random_seed_bytes = [42; 32];
7230 let config = UserConfig::default();
7232 let max_htlc_msat = 50_000;
7233 let route_hint_1 = RouteHint(vec![RouteHintHop {
7234 src_node_id: nodes[2],
7235 short_channel_id: 42,
7238 proportional_millionths: 0,
7240 cltv_expiry_delta: 10,
7241 htlc_minimum_msat: None,
7242 htlc_maximum_msat: Some(max_htlc_msat),
7244 let dest_node_id = ln_test_utils::pubkey(42);
7245 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7246 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
7247 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7250 // Make sure we'll error if our route hints don't have enough liquidity according to their
7251 // htlc_maximum_msat.
7252 let mut route_params = RouteParameters::from_payment_params_and_value(
7253 payment_params, max_htlc_msat + 1);
7254 route_params.max_total_routing_fee_msat = None;
7255 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
7256 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
7259 assert_eq!(err, "Failed to find a sufficient route to the given destination");
7260 } else { panic!(); }
7262 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
7263 let mut route_hint_2 = route_hint_1.clone();
7264 route_hint_2.0[0].short_channel_id = 43;
7265 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7266 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7267 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7269 let mut route_params = RouteParameters::from_payment_params_and_value(
7270 payment_params, max_htlc_msat + 1);
7271 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
7272 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
7273 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7274 assert_eq!(route.paths.len(), 2);
7275 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7276 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7280 fn direct_channel_to_hints_with_max_htlc() {
7281 // Check that if we have a first hop channel peer that's connected to multiple provided route
7282 // hints, that we properly split the payment between the route hints if needed.
7283 let logger = Arc::new(ln_test_utils::TestLogger::new());
7284 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7285 let scorer = ln_test_utils::TestScorer::new();
7286 let random_seed_bytes = [42; 32];
7287 let config = UserConfig::default();
7289 let our_node_id = ln_test_utils::pubkey(42);
7290 let intermed_node_id = ln_test_utils::pubkey(43);
7291 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7293 let amt_msat = 900_000;
7294 let max_htlc_msat = 500_000;
7295 let route_hint_1 = RouteHint(vec![RouteHintHop {
7296 src_node_id: intermed_node_id,
7297 short_channel_id: 44,
7300 proportional_millionths: 0,
7302 cltv_expiry_delta: 10,
7303 htlc_minimum_msat: None,
7304 htlc_maximum_msat: Some(max_htlc_msat),
7306 src_node_id: intermed_node_id,
7307 short_channel_id: 45,
7310 proportional_millionths: 0,
7312 cltv_expiry_delta: 10,
7313 htlc_minimum_msat: None,
7314 // Check that later route hint max htlcs don't override earlier ones
7315 htlc_maximum_msat: Some(max_htlc_msat - 50),
7317 let mut route_hint_2 = route_hint_1.clone();
7318 route_hint_2.0[0].short_channel_id = 46;
7319 route_hint_2.0[1].short_channel_id = 47;
7320 let dest_node_id = ln_test_utils::pubkey(44);
7321 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7322 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7323 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7326 let route_params = RouteParameters::from_payment_params_and_value(
7327 payment_params, amt_msat);
7328 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7329 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7330 &Default::default(), &random_seed_bytes).unwrap();
7331 assert_eq!(route.paths.len(), 2);
7332 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7333 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7334 assert_eq!(route.get_total_amount(), amt_msat);
7336 // Re-run but with two first hop channels connected to the same route hint peers that must be
7338 let first_hops = vec![
7339 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7340 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7342 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7343 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7344 &Default::default(), &random_seed_bytes).unwrap();
7345 assert_eq!(route.paths.len(), 2);
7346 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7347 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7348 assert_eq!(route.get_total_amount(), amt_msat);
7350 // Make sure this works for blinded route hints.
7351 let blinded_path = BlindedPath {
7352 introduction_node: IntroductionNode::NodeId(intermed_node_id),
7353 blinding_point: ln_test_utils::pubkey(42),
7355 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
7356 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
7359 let blinded_payinfo = BlindedPayInfo {
7361 fee_proportional_millionths: 0,
7362 htlc_minimum_msat: 1,
7363 htlc_maximum_msat: max_htlc_msat,
7364 cltv_expiry_delta: 10,
7365 features: BlindedHopFeatures::empty(),
7367 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7368 let payment_params = PaymentParameters::blinded(vec![
7369 (blinded_payinfo.clone(), blinded_path.clone()),
7370 (blinded_payinfo.clone(), blinded_path.clone())])
7371 .with_bolt12_features(bolt12_features).unwrap();
7372 let route_params = RouteParameters::from_payment_params_and_value(
7373 payment_params, amt_msat);
7374 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7375 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7376 &Default::default(), &random_seed_bytes).unwrap();
7377 assert_eq!(route.paths.len(), 2);
7378 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7379 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7380 assert_eq!(route.get_total_amount(), amt_msat);
7384 fn blinded_route_ser() {
7385 let blinded_path_1 = BlindedPath {
7386 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(42)),
7387 blinding_point: ln_test_utils::pubkey(43),
7389 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7390 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7393 let blinded_path_2 = BlindedPath {
7394 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(46)),
7395 blinding_point: ln_test_utils::pubkey(47),
7397 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7398 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7401 // (De)serialize a Route with 1 blinded path out of two total paths.
7402 let mut route = Route { paths: vec![Path {
7403 hops: vec![RouteHop {
7404 pubkey: ln_test_utils::pubkey(50),
7405 node_features: NodeFeatures::empty(),
7406 short_channel_id: 42,
7407 channel_features: ChannelFeatures::empty(),
7409 cltv_expiry_delta: 0,
7410 maybe_announced_channel: true,
7412 blinded_tail: Some(BlindedTail {
7413 hops: blinded_path_1.blinded_hops,
7414 blinding_point: blinded_path_1.blinding_point,
7415 excess_final_cltv_expiry_delta: 40,
7416 final_value_msat: 100,
7418 hops: vec![RouteHop {
7419 pubkey: ln_test_utils::pubkey(51),
7420 node_features: NodeFeatures::empty(),
7421 short_channel_id: 43,
7422 channel_features: ChannelFeatures::empty(),
7424 cltv_expiry_delta: 0,
7425 maybe_announced_channel: true,
7426 }], blinded_tail: None }],
7429 let encoded_route = route.encode();
7430 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7431 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7432 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7434 // (De)serialize a Route with two paths, each containing a blinded tail.
7435 route.paths[1].blinded_tail = Some(BlindedTail {
7436 hops: blinded_path_2.blinded_hops,
7437 blinding_point: blinded_path_2.blinding_point,
7438 excess_final_cltv_expiry_delta: 41,
7439 final_value_msat: 101,
7441 let encoded_route = route.encode();
7442 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7443 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7444 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7448 fn blinded_path_inflight_processing() {
7449 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7450 // account for the blinded tail's final amount_msat.
7451 let mut inflight_htlcs = InFlightHtlcs::new();
7452 let blinded_path = BlindedPath {
7453 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(43)),
7454 blinding_point: ln_test_utils::pubkey(48),
7455 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7458 hops: vec![RouteHop {
7459 pubkey: ln_test_utils::pubkey(42),
7460 node_features: NodeFeatures::empty(),
7461 short_channel_id: 42,
7462 channel_features: ChannelFeatures::empty(),
7464 cltv_expiry_delta: 0,
7465 maybe_announced_channel: false,
7468 pubkey: ln_test_utils::pubkey(43),
7469 node_features: NodeFeatures::empty(),
7470 short_channel_id: 43,
7471 channel_features: ChannelFeatures::empty(),
7473 cltv_expiry_delta: 0,
7474 maybe_announced_channel: false,
7476 blinded_tail: Some(BlindedTail {
7477 hops: blinded_path.blinded_hops,
7478 blinding_point: blinded_path.blinding_point,
7479 excess_final_cltv_expiry_delta: 0,
7480 final_value_msat: 200,
7483 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7484 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7485 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7489 fn blinded_path_cltv_shadow_offset() {
7490 // Make sure we add a shadow offset when sending to blinded paths.
7491 let blinded_path = BlindedPath {
7492 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(43)),
7493 blinding_point: ln_test_utils::pubkey(44),
7495 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7496 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7499 let mut route = Route { paths: vec![Path {
7500 hops: vec![RouteHop {
7501 pubkey: ln_test_utils::pubkey(42),
7502 node_features: NodeFeatures::empty(),
7503 short_channel_id: 42,
7504 channel_features: ChannelFeatures::empty(),
7506 cltv_expiry_delta: 0,
7507 maybe_announced_channel: false,
7510 pubkey: ln_test_utils::pubkey(43),
7511 node_features: NodeFeatures::empty(),
7512 short_channel_id: 43,
7513 channel_features: ChannelFeatures::empty(),
7515 cltv_expiry_delta: 0,
7516 maybe_announced_channel: false,
7519 blinded_tail: Some(BlindedTail {
7520 hops: blinded_path.blinded_hops,
7521 blinding_point: blinded_path.blinding_point,
7522 excess_final_cltv_expiry_delta: 0,
7523 final_value_msat: 200,
7525 }], route_params: None};
7527 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7528 let (_, network_graph, _, _, _) = build_line_graph();
7529 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7530 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7531 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7535 fn simple_blinded_route_hints() {
7536 do_simple_blinded_route_hints(1);
7537 do_simple_blinded_route_hints(2);
7538 do_simple_blinded_route_hints(3);
7541 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7542 // Check that we can generate a route to a blinded path with the expected hops.
7543 let (secp_ctx, network, _, _, logger) = build_graph();
7544 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7545 let network_graph = network.read_only();
7547 let scorer = ln_test_utils::TestScorer::new();
7548 let random_seed_bytes = [42; 32];
7550 let mut blinded_path = BlindedPath {
7551 introduction_node: IntroductionNode::NodeId(nodes[2]),
7552 blinding_point: ln_test_utils::pubkey(42),
7553 blinded_hops: Vec::with_capacity(num_blinded_hops),
7555 for i in 0..num_blinded_hops {
7556 blinded_path.blinded_hops.push(
7557 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7560 let blinded_payinfo = BlindedPayInfo {
7562 fee_proportional_millionths: 500,
7563 htlc_minimum_msat: 1000,
7564 htlc_maximum_msat: 100_000_000,
7565 cltv_expiry_delta: 15,
7566 features: BlindedHopFeatures::empty(),
7569 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7570 let route_params = RouteParameters::from_payment_params_and_value(
7571 payment_params, 1001);
7572 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7573 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7574 assert_eq!(route.paths.len(), 1);
7575 assert_eq!(route.paths[0].hops.len(), 2);
7577 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7578 assert_eq!(tail.hops, blinded_path.blinded_hops);
7579 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7580 assert_eq!(tail.final_value_msat, 1001);
7582 let final_hop = route.paths[0].hops.last().unwrap();
7584 NodeId::from_pubkey(&final_hop.pubkey),
7585 *blinded_path.public_introduction_node_id(&network_graph).unwrap()
7587 if tail.hops.len() > 1 {
7588 assert_eq!(final_hop.fee_msat,
7589 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7590 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7592 assert_eq!(final_hop.fee_msat, 0);
7593 assert_eq!(final_hop.cltv_expiry_delta, 0);
7598 fn blinded_path_routing_errors() {
7599 // Check that we can generate a route to a blinded path with the expected hops.
7600 let (secp_ctx, network, _, _, logger) = build_graph();
7601 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7602 let network_graph = network.read_only();
7604 let scorer = ln_test_utils::TestScorer::new();
7605 let random_seed_bytes = [42; 32];
7607 let mut invalid_blinded_path = BlindedPath {
7608 introduction_node: IntroductionNode::NodeId(nodes[2]),
7609 blinding_point: ln_test_utils::pubkey(42),
7611 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7614 let blinded_payinfo = BlindedPayInfo {
7616 fee_proportional_millionths: 500,
7617 htlc_minimum_msat: 1000,
7618 htlc_maximum_msat: 100_000_000,
7619 cltv_expiry_delta: 15,
7620 features: BlindedHopFeatures::empty(),
7623 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7624 invalid_blinded_path_2.introduction_node = IntroductionNode::NodeId(ln_test_utils::pubkey(45));
7625 let payment_params = PaymentParameters::blinded(vec![
7626 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7627 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7628 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7629 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7630 &scorer, &Default::default(), &random_seed_bytes)
7632 Err(LightningError { err, .. }) => {
7633 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7635 _ => panic!("Expected error")
7638 invalid_blinded_path.introduction_node = IntroductionNode::NodeId(our_id);
7639 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7640 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7641 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7642 &Default::default(), &random_seed_bytes)
7644 Err(LightningError { err, .. }) => {
7645 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7647 _ => panic!("Expected error")
7650 invalid_blinded_path.introduction_node = IntroductionNode::NodeId(ln_test_utils::pubkey(46));
7651 invalid_blinded_path.blinded_hops.clear();
7652 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7653 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7654 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7655 &Default::default(), &random_seed_bytes)
7657 Err(LightningError { err, .. }) => {
7658 assert_eq!(err, "0-hop blinded path provided");
7660 _ => panic!("Expected error")
7665 fn matching_intro_node_paths_provided() {
7666 // Check that if multiple blinded paths with the same intro node are provided in payment
7667 // parameters, we'll return the correct paths in the resulting MPP route.
7668 let (secp_ctx, network, _, _, logger) = build_graph();
7669 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7670 let network_graph = network.read_only();
7672 let scorer = ln_test_utils::TestScorer::new();
7673 let random_seed_bytes = [42; 32];
7674 let config = UserConfig::default();
7676 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7677 let blinded_path_1 = BlindedPath {
7678 introduction_node: IntroductionNode::NodeId(nodes[2]),
7679 blinding_point: ln_test_utils::pubkey(42),
7681 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7682 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7685 let blinded_payinfo_1 = BlindedPayInfo {
7687 fee_proportional_millionths: 0,
7688 htlc_minimum_msat: 0,
7689 htlc_maximum_msat: 30_000,
7690 cltv_expiry_delta: 0,
7691 features: BlindedHopFeatures::empty(),
7694 let mut blinded_path_2 = blinded_path_1.clone();
7695 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7696 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7697 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7699 let blinded_hints = vec![
7700 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7701 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7703 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7704 .with_bolt12_features(bolt12_features).unwrap();
7706 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7707 route_params.max_total_routing_fee_msat = Some(100_000);
7708 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7709 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7710 assert_eq!(route.paths.len(), 2);
7711 let mut total_amount_paid_msat = 0;
7712 for path in route.paths.into_iter() {
7713 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7714 if let Some(bt) = &path.blinded_tail {
7715 assert_eq!(bt.blinding_point,
7716 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7717 .map(|(_, bp)| bp.blinding_point).unwrap());
7718 } else { panic!(); }
7719 total_amount_paid_msat += path.final_value_msat();
7721 assert_eq!(total_amount_paid_msat, 100_000);
7725 fn direct_to_intro_node() {
7726 // This previously caused a debug panic in the router when asserting
7727 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7728 // direct channels we failed to account for the fee charged for use of the blinded path.
7731 // node0 -1(1)2 - node1
7732 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7733 // doesn't account for the blinded path fee.
7735 let secp_ctx = Secp256k1::new();
7736 let logger = Arc::new(ln_test_utils::TestLogger::new());
7737 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7738 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7739 let scorer = ln_test_utils::TestScorer::new();
7740 let random_seed_bytes = [42; 32];
7742 let amt_msat = 10_000_000;
7743 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7744 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7745 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7746 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7747 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7748 short_channel_id: 1,
7751 cltv_expiry_delta: 42,
7752 htlc_minimum_msat: 1_000,
7753 htlc_maximum_msat: 10_000_000,
7755 fee_proportional_millionths: 0,
7756 excess_data: Vec::new()
7758 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7759 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7760 short_channel_id: 1,
7763 cltv_expiry_delta: 42,
7764 htlc_minimum_msat: 1_000,
7765 htlc_maximum_msat: 10_000_000,
7767 fee_proportional_millionths: 0,
7768 excess_data: Vec::new()
7770 let first_hops = vec![
7771 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7773 let blinded_path = BlindedPath {
7774 introduction_node: IntroductionNode::NodeId(nodes[1]),
7775 blinding_point: ln_test_utils::pubkey(42),
7777 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7778 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7781 let blinded_payinfo = BlindedPayInfo {
7782 fee_base_msat: 1000,
7783 fee_proportional_millionths: 0,
7784 htlc_minimum_msat: 1000,
7785 htlc_maximum_msat: MAX_VALUE_MSAT,
7786 cltv_expiry_delta: 0,
7787 features: BlindedHopFeatures::empty(),
7789 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7791 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7793 let netgraph = network_graph.read_only();
7794 let route_params = RouteParameters::from_payment_params_and_value(
7795 payment_params.clone(), amt_msat);
7796 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7797 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7798 &Default::default(), &random_seed_bytes) {
7799 assert_eq!(err, "Failed to find a path to the given destination");
7800 } else { panic!("Expected error") }
7802 // Sending an exact amount accounting for the blinded path fee works.
7803 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7804 let route_params = RouteParameters::from_payment_params_and_value(
7805 payment_params, amt_minus_blinded_path_fee);
7806 let route = get_route(&nodes[0], &route_params, &netgraph,
7807 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7808 &Default::default(), &random_seed_bytes).unwrap();
7809 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7810 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7814 fn direct_to_matching_intro_nodes() {
7815 // This previously caused us to enter `unreachable` code in the following situation:
7816 // 1. We add a route candidate for intro_node contributing a high amount
7817 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7818 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7819 // amount, and update our route candidate for intro_node for the lower amount
7820 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7821 // lower contribution amount, but fail (this was previously caused by failure to account for
7822 // blinded path fees when adding first_hop<>intro_node candidates)
7823 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7824 // candidate still thinks its path is contributing the original higher amount. This caused us
7825 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7827 let secp_ctx = Secp256k1::new();
7828 let logger = Arc::new(ln_test_utils::TestLogger::new());
7829 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7830 let scorer = ln_test_utils::TestScorer::new();
7831 let random_seed_bytes = [42; 32];
7832 let config = UserConfig::default();
7834 // Values are taken from the fuzz input that uncovered this panic.
7835 let amt_msat = 21_7020_5185_1403_2640;
7836 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7837 let first_hops = vec![
7838 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7839 18446744073709551615)];
7841 let blinded_path = BlindedPath {
7842 introduction_node: IntroductionNode::NodeId(nodes[1]),
7843 blinding_point: ln_test_utils::pubkey(42),
7845 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7846 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7849 let blinded_payinfo = BlindedPayInfo {
7850 fee_base_msat: 5046_2720,
7851 fee_proportional_millionths: 0,
7852 htlc_minimum_msat: 4503_5996_2737_0496,
7853 htlc_maximum_msat: 45_0359_9627_3704_9600,
7854 cltv_expiry_delta: 0,
7855 features: BlindedHopFeatures::empty(),
7857 let mut blinded_hints = vec![
7858 (blinded_payinfo.clone(), blinded_path.clone()),
7859 (blinded_payinfo.clone(), blinded_path.clone()),
7861 blinded_hints[1].0.fee_base_msat = 419_4304;
7862 blinded_hints[1].0.fee_proportional_millionths = 257;
7863 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7864 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7865 blinded_hints[1].0.cltv_expiry_delta = 0;
7867 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7868 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7869 .with_bolt12_features(bolt12_features).unwrap();
7871 let netgraph = network_graph.read_only();
7872 let route_params = RouteParameters::from_payment_params_and_value(
7873 payment_params, amt_msat);
7874 let route = get_route(&nodes[0], &route_params, &netgraph,
7875 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7876 &Default::default(), &random_seed_bytes).unwrap();
7877 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7878 assert_eq!(route.get_total_amount(), amt_msat);
7882 fn we_are_intro_node_candidate_hops() {
7883 // This previously led to a panic in the router because we'd generate a Path with only a
7884 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7885 // where the origin node is the intro node. We now fully disallow considering candidate hops
7886 // where the origin node is the intro node.
7887 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7888 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7889 let scorer = ln_test_utils::TestScorer::new();
7890 let random_seed_bytes = [42; 32];
7891 let config = UserConfig::default();
7893 // Values are taken from the fuzz input that uncovered this panic.
7894 let amt_msat = 21_7020_5185_1423_0019;
7896 let blinded_path = BlindedPath {
7897 introduction_node: IntroductionNode::NodeId(our_id),
7898 blinding_point: ln_test_utils::pubkey(42),
7900 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7901 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7904 let blinded_payinfo = BlindedPayInfo {
7905 fee_base_msat: 5052_9027,
7906 fee_proportional_millionths: 0,
7907 htlc_minimum_msat: 21_7020_5185_1423_0019,
7908 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7909 cltv_expiry_delta: 0,
7910 features: BlindedHopFeatures::empty(),
7912 let mut blinded_hints = vec![
7913 (blinded_payinfo.clone(), blinded_path.clone()),
7914 (blinded_payinfo.clone(), blinded_path.clone()),
7916 blinded_hints[1].1.introduction_node = IntroductionNode::NodeId(nodes[6]);
7918 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7919 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7920 .with_bolt12_features(bolt12_features.clone()).unwrap();
7922 let netgraph = network_graph.read_only();
7923 let route_params = RouteParameters::from_payment_params_and_value(
7924 payment_params, amt_msat);
7925 if let Err(LightningError { err, .. }) = get_route(
7926 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7928 assert_eq!(err, "Failed to find a path to the given destination");
7933 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7934 // This previously led to a debug panic in the router because we'd find an invalid Path with
7935 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7936 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7937 // the payment, when it was intended to only include the final value of the payment.
7938 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7939 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7940 let scorer = ln_test_utils::TestScorer::new();
7941 let random_seed_bytes = [42; 32];
7942 let config = UserConfig::default();
7944 // Values are taken from the fuzz input that uncovered this panic.
7945 let amt_msat = 21_7020_5185_1423_0019;
7947 let blinded_path = BlindedPath {
7948 introduction_node: IntroductionNode::NodeId(our_id),
7949 blinding_point: ln_test_utils::pubkey(42),
7951 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7952 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7955 let blinded_payinfo = BlindedPayInfo {
7956 fee_base_msat: 10_4425_1395,
7957 fee_proportional_millionths: 0,
7958 htlc_minimum_msat: 21_7301_9934_9094_0931,
7959 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7960 cltv_expiry_delta: 0,
7961 features: BlindedHopFeatures::empty(),
7963 let mut blinded_hints = vec![
7964 (blinded_payinfo.clone(), blinded_path.clone()),
7965 (blinded_payinfo.clone(), blinded_path.clone()),
7966 (blinded_payinfo.clone(), blinded_path.clone()),
7968 blinded_hints[1].0.fee_base_msat = 5052_9027;
7969 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7970 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7972 blinded_hints[2].1.introduction_node = IntroductionNode::NodeId(nodes[6]);
7974 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7975 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7976 .with_bolt12_features(bolt12_features.clone()).unwrap();
7978 let netgraph = network_graph.read_only();
7979 let route_params = RouteParameters::from_payment_params_and_value(
7980 payment_params, amt_msat);
7981 if let Err(LightningError { err, .. }) = get_route(
7982 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7984 assert_eq!(err, "Failed to find a path to the given destination");
7989 fn min_htlc_overpay_violates_max_htlc() {
7990 do_min_htlc_overpay_violates_max_htlc(true);
7991 do_min_htlc_overpay_violates_max_htlc(false);
7993 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7994 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7995 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7996 // to `targets` and build an invalid path with it, and subsequently hit a debug panic asserting
7997 // that the used liquidity for a hop was less than its available liquidity limit.
7998 let secp_ctx = Secp256k1::new();
7999 let logger = Arc::new(ln_test_utils::TestLogger::new());
8000 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8001 let scorer = ln_test_utils::TestScorer::new();
8002 let random_seed_bytes = [42; 32];
8003 let config = UserConfig::default();
8005 // Values are taken from the fuzz input that uncovered this panic.
8006 let amt_msat = 7_4009_8048;
8007 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8008 let first_hop_outbound_capacity = 2_7345_2000;
8009 let first_hops = vec![get_channel_details(
8010 Some(200), nodes[0], channelmanager::provided_init_features(&config),
8011 first_hop_outbound_capacity
8014 let base_fee = 1_6778_3453;
8015 let htlc_min = 2_5165_8240;
8016 let payment_params = if blinded_payee {
8017 let blinded_path = BlindedPath {
8018 introduction_node: IntroductionNode::NodeId(nodes[0]),
8019 blinding_point: ln_test_utils::pubkey(42),
8021 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8022 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8025 let blinded_payinfo = BlindedPayInfo {
8026 fee_base_msat: base_fee,
8027 fee_proportional_millionths: 0,
8028 htlc_minimum_msat: htlc_min,
8029 htlc_maximum_msat: htlc_min * 1000,
8030 cltv_expiry_delta: 0,
8031 features: BlindedHopFeatures::empty(),
8033 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8034 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
8035 .with_bolt12_features(bolt12_features.clone()).unwrap()
8037 let route_hint = RouteHint(vec![RouteHintHop {
8038 src_node_id: nodes[0],
8039 short_channel_id: 42,
8041 base_msat: base_fee,
8042 proportional_millionths: 0,
8044 cltv_expiry_delta: 10,
8045 htlc_minimum_msat: Some(htlc_min),
8046 htlc_maximum_msat: None,
8049 PaymentParameters::from_node_id(nodes[1], 42)
8050 .with_route_hints(vec![route_hint]).unwrap()
8051 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8054 let netgraph = network_graph.read_only();
8055 let route_params = RouteParameters::from_payment_params_and_value(
8056 payment_params, amt_msat);
8057 if let Err(LightningError { err, .. }) = get_route(
8058 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8059 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8061 assert_eq!(err, "Failed to find a path to the given destination");
8066 fn previously_used_liquidity_violates_max_htlc() {
8067 do_previously_used_liquidity_violates_max_htlc(true);
8068 do_previously_used_liquidity_violates_max_htlc(false);
8071 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
8072 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
8073 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
8074 // candidate. In this case, the candidate does not have enough due to a previous path taking up
8075 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
8076 // asserting that the used liquidity for a hop was less than its available liquidity limit.
8077 let secp_ctx = Secp256k1::new();
8078 let logger = Arc::new(ln_test_utils::TestLogger::new());
8079 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8080 let scorer = ln_test_utils::TestScorer::new();
8081 let random_seed_bytes = [42; 32];
8082 let config = UserConfig::default();
8084 // Values are taken from the fuzz input that uncovered this panic.
8085 let amt_msat = 52_4288;
8086 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8087 let first_hops = vec![get_channel_details(
8088 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
8089 ), get_channel_details(
8090 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
8093 let base_fees = [0, 425_9840, 0, 0];
8094 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
8095 let payment_params = if blinded_payee {
8096 let blinded_path = BlindedPath {
8097 introduction_node: IntroductionNode::NodeId(nodes[0]),
8098 blinding_point: ln_test_utils::pubkey(42),
8100 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8101 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8104 let mut blinded_hints = Vec::new();
8105 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
8106 blinded_hints.push((BlindedPayInfo {
8107 fee_base_msat: *base_fee,
8108 fee_proportional_millionths: 0,
8109 htlc_minimum_msat: *htlc_min,
8110 htlc_maximum_msat: htlc_min * 100,
8111 cltv_expiry_delta: 10,
8112 features: BlindedHopFeatures::empty(),
8113 }, blinded_path.clone()));
8115 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8116 PaymentParameters::blinded(blinded_hints.clone())
8117 .with_bolt12_features(bolt12_features.clone()).unwrap()
8119 let mut route_hints = Vec::new();
8120 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
8121 route_hints.push(RouteHint(vec![RouteHintHop {
8122 src_node_id: nodes[0],
8123 short_channel_id: 42 + idx as u64,
8125 base_msat: *base_fee,
8126 proportional_millionths: 0,
8128 cltv_expiry_delta: 10,
8129 htlc_minimum_msat: Some(*htlc_min),
8130 htlc_maximum_msat: Some(htlc_min * 100),
8133 PaymentParameters::from_node_id(nodes[1], 42)
8134 .with_route_hints(route_hints).unwrap()
8135 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8138 let netgraph = network_graph.read_only();
8139 let route_params = RouteParameters::from_payment_params_and_value(
8140 payment_params, amt_msat);
8142 let route = get_route(
8143 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8144 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8146 assert_eq!(route.paths.len(), 1);
8147 assert_eq!(route.get_total_amount(), amt_msat);
8151 fn candidate_path_min() {
8152 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
8153 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
8154 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
8155 // would add a connecting first_hop node that did not have enough contribution amount, leading
8156 // to a debug panic upon invalid path construction.
8157 let secp_ctx = Secp256k1::new();
8158 let logger = Arc::new(ln_test_utils::TestLogger::new());
8159 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8160 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
8161 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8162 let random_seed_bytes = [42; 32];
8163 let config = UserConfig::default();
8165 // Values are taken from the fuzz input that uncovered this panic.
8166 let amt_msat = 7_4009_8048;
8167 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
8168 let first_hops = vec![get_channel_details(
8169 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
8172 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
8173 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8174 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8175 short_channel_id: 6,
8178 cltv_expiry_delta: (6 << 4) | 0,
8179 htlc_minimum_msat: 0,
8180 htlc_maximum_msat: MAX_VALUE_MSAT,
8182 fee_proportional_millionths: 0,
8183 excess_data: Vec::new()
8185 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
8187 let htlc_min = 2_5165_8240;
8188 let blinded_hints = vec![
8190 fee_base_msat: 1_6778_3453,
8191 fee_proportional_millionths: 0,
8192 htlc_minimum_msat: htlc_min,
8193 htlc_maximum_msat: htlc_min * 100,
8194 cltv_expiry_delta: 10,
8195 features: BlindedHopFeatures::empty(),
8197 introduction_node: IntroductionNode::NodeId(nodes[0]),
8198 blinding_point: ln_test_utils::pubkey(42),
8200 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8201 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8205 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8206 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8207 .with_bolt12_features(bolt12_features.clone()).unwrap();
8208 let route_params = RouteParameters::from_payment_params_and_value(
8209 payment_params, amt_msat);
8210 let netgraph = network_graph.read_only();
8212 if let Err(LightningError { err, .. }) = get_route(
8213 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8214 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8217 assert_eq!(err, "Failed to find a path to the given destination");
8222 fn path_contribution_includes_min_htlc_overpay() {
8223 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
8224 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
8225 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
8226 // selection, both tested here.
8227 let secp_ctx = Secp256k1::new();
8228 let logger = Arc::new(ln_test_utils::TestLogger::new());
8229 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8230 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8231 let random_seed_bytes = [42; 32];
8232 let config = UserConfig::default();
8234 // Values are taken from the fuzz input that uncovered this panic.
8235 let amt_msat = 562_0000;
8236 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8237 let first_hops = vec![
8238 get_channel_details(
8239 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
8243 let htlc_mins = [49_0000, 1125_0000];
8244 let payment_params = {
8245 let blinded_path = BlindedPath {
8246 introduction_node: IntroductionNode::NodeId(nodes[0]),
8247 blinding_point: ln_test_utils::pubkey(42),
8249 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8250 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8253 let mut blinded_hints = Vec::new();
8254 for htlc_min in htlc_mins.iter() {
8255 blinded_hints.push((BlindedPayInfo {
8257 fee_proportional_millionths: 0,
8258 htlc_minimum_msat: *htlc_min,
8259 htlc_maximum_msat: *htlc_min * 100,
8260 cltv_expiry_delta: 10,
8261 features: BlindedHopFeatures::empty(),
8262 }, blinded_path.clone()));
8264 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8265 PaymentParameters::blinded(blinded_hints.clone())
8266 .with_bolt12_features(bolt12_features.clone()).unwrap()
8269 let netgraph = network_graph.read_only();
8270 let route_params = RouteParameters::from_payment_params_and_value(
8271 payment_params, amt_msat);
8272 let route = get_route(
8273 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8274 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8277 assert_eq!(route.paths.len(), 1);
8278 assert_eq!(route.get_total_amount(), amt_msat);
8282 fn first_hop_preferred_over_hint() {
8283 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
8284 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
8285 let secp_ctx = Secp256k1::new();
8286 let logger = Arc::new(ln_test_utils::TestLogger::new());
8287 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8288 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
8289 let scorer = ln_test_utils::TestScorer::new();
8290 let random_seed_bytes = [42; 32];
8291 let config = UserConfig::default();
8293 let amt_msat = 1_000_000;
8294 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
8296 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
8297 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
8298 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8299 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8300 short_channel_id: 1,
8303 cltv_expiry_delta: 42,
8304 htlc_minimum_msat: 1_000,
8305 htlc_maximum_msat: 10_000_000,
8307 fee_proportional_millionths: 0,
8308 excess_data: Vec::new()
8310 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8311 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8312 short_channel_id: 1,
8315 cltv_expiry_delta: 42,
8316 htlc_minimum_msat: 1_000,
8317 htlc_maximum_msat: 10_000_000,
8319 fee_proportional_millionths: 0,
8320 excess_data: Vec::new()
8323 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
8324 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
8325 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8326 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8327 short_channel_id: 2,
8330 cltv_expiry_delta: 42,
8331 htlc_minimum_msat: 1_000,
8332 htlc_maximum_msat: 10_000_000,
8334 fee_proportional_millionths: 0,
8335 excess_data: Vec::new()
8337 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8338 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8339 short_channel_id: 2,
8342 cltv_expiry_delta: 42,
8343 htlc_minimum_msat: 1_000,
8344 htlc_maximum_msat: 10_000_000,
8346 fee_proportional_millionths: 0,
8347 excess_data: Vec::new()
8350 let dest_node_id = nodes[2];
8352 let route_hint = RouteHint(vec![RouteHintHop {
8353 src_node_id: our_node_id,
8354 short_channel_id: 44,
8357 proportional_millionths: 0,
8359 cltv_expiry_delta: 10,
8360 htlc_minimum_msat: None,
8361 htlc_maximum_msat: Some(5_000_000),
8364 src_node_id: nodes[0],
8365 short_channel_id: 45,
8368 proportional_millionths: 0,
8370 cltv_expiry_delta: 10,
8371 htlc_minimum_msat: None,
8372 htlc_maximum_msat: None,
8375 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8376 .with_route_hints(vec![route_hint]).unwrap()
8377 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8378 let route_params = RouteParameters::from_payment_params_and_value(
8379 payment_params, amt_msat);
8381 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8383 let first_hop = get_channel_details(Some(1), nodes[0],
8384 channelmanager::provided_init_features(&config), 999_999);
8385 let first_hops = vec![first_hop];
8387 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8388 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8389 &Default::default(), &random_seed_bytes).unwrap();
8390 assert_eq!(route.paths.len(), 1);
8391 assert_eq!(route.get_total_amount(), amt_msat);
8392 assert_eq!(route.paths[0].hops.len(), 2);
8393 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8394 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8395 assert_eq!(route.get_total_fees(), 123);
8397 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8398 // for a first hop channel.
8399 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8400 first_hop.outbound_scid_alias = Some(44);
8401 let first_hops = vec![first_hop];
8403 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8404 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8405 &Default::default(), &random_seed_bytes);
8406 assert!(route_res.is_err());
8408 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8409 // use the cheaper second hop of the route hint.
8410 let mut first_hop = get_channel_details(Some(1), nodes[0],
8411 channelmanager::provided_init_features(&config), 10_000_000);
8412 first_hop.outbound_scid_alias = Some(44);
8413 let first_hops = vec![first_hop];
8415 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8416 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8417 &Default::default(), &random_seed_bytes).unwrap();
8418 assert_eq!(route.paths.len(), 1);
8419 assert_eq!(route.get_total_amount(), amt_msat);
8420 assert_eq!(route.paths[0].hops.len(), 2);
8421 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8422 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8423 assert_eq!(route.get_total_fees(), 123);
8427 fn allow_us_being_first_hint() {
8428 // Check that we consider a route hint even if we are the src of the first hop.
8429 let secp_ctx = Secp256k1::new();
8430 let logger = Arc::new(ln_test_utils::TestLogger::new());
8431 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8432 let scorer = ln_test_utils::TestScorer::new();
8433 let random_seed_bytes = [42; 32];
8434 let config = UserConfig::default();
8436 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8438 let amt_msat = 1_000_000;
8439 let dest_node_id = nodes[1];
8441 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8442 let first_hops = vec![first_hop];
8444 let route_hint = RouteHint(vec![RouteHintHop {
8445 src_node_id: our_node_id,
8446 short_channel_id: 44,
8449 proportional_millionths: 0,
8451 cltv_expiry_delta: 10,
8452 htlc_minimum_msat: None,
8453 htlc_maximum_msat: None,
8456 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8457 .with_route_hints(vec![route_hint]).unwrap()
8458 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8460 let route_params = RouteParameters::from_payment_params_and_value(
8461 payment_params, amt_msat);
8464 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8465 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8466 &Default::default(), &random_seed_bytes).unwrap();
8468 assert_eq!(route.paths.len(), 1);
8469 assert_eq!(route.get_total_amount(), amt_msat);
8470 assert_eq!(route.get_total_fees(), 0);
8471 assert_eq!(route.paths[0].hops.len(), 1);
8473 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8477 #[cfg(all(any(test, ldk_bench), feature = "std"))]
8478 pub(crate) mod bench_utils {
8482 use bitcoin::hashes::Hash;
8483 use bitcoin::secp256k1::SecretKey;
8485 use crate::chain::transaction::OutPoint;
8486 use crate::routing::scoring::{ProbabilisticScorer, ScoreUpdate};
8487 use crate::ln::channel_state::{ChannelCounterparty, ChannelShutdownState};
8488 use crate::ln::channelmanager;
8489 use crate::ln::types::ChannelId;
8490 use crate::util::config::UserConfig;
8491 use crate::util::test_utils::TestLogger;
8492 use crate::sync::Arc;
8494 /// Tries to open a network graph file, or panics with a URL to fetch it.
8495 pub(crate) fn get_graph_scorer_file() -> Result<(std::fs::File, std::fs::File), &'static str> {
8496 let load_file = |fname, err_str| {
8497 File::open(fname) // By default we're run in RL/lightning
8498 .or_else(|_| File::open(&format!("lightning/{}", fname))) // We may be run manually in RL/
8499 .or_else(|_| { // Fall back to guessing based on the binary location
8500 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8501 let mut path = std::env::current_exe().unwrap();
8502 path.pop(); // lightning-...
8504 path.pop(); // debug
8505 path.pop(); // target
8506 path.push("lightning");
8510 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8511 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8512 let mut path = std::env::current_exe().unwrap();
8513 path.pop(); // bench...
8515 path.pop(); // debug
8516 path.pop(); // target
8517 path.pop(); // bench
8518 path.push("lightning");
8522 .map_err(|_| err_str)
8524 let graph_res = load_file(
8525 "net_graph-2023-12-10.bin",
8526 "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"
8528 let scorer_res = load_file(
8529 "scorer-2023-12-10.bin",
8530 "Please fetch https://bitcoin.ninja/ldk-scorer-v0.0.118-2023-12-10.bin and place it at lightning/scorer-2023-12-10.bin"
8532 #[cfg(require_route_graph_test)]
8533 return Ok((graph_res.unwrap(), scorer_res.unwrap()));
8534 #[cfg(not(require_route_graph_test))]
8535 return Ok((graph_res?, scorer_res?));
8538 pub(crate) fn read_graph_scorer(logger: &TestLogger)
8539 -> Result<(Arc<NetworkGraph<&TestLogger>>, ProbabilisticScorer<Arc<NetworkGraph<&TestLogger>>, &TestLogger>), &'static str> {
8540 let (mut graph_file, mut scorer_file) = get_graph_scorer_file()?;
8541 let graph = Arc::new(NetworkGraph::read(&mut graph_file, logger).unwrap());
8542 let scorer_args = (Default::default(), Arc::clone(&graph), logger);
8543 let scorer = ProbabilisticScorer::read(&mut scorer_file, scorer_args).unwrap();
8547 pub(crate) fn payer_pubkey() -> PublicKey {
8548 let secp_ctx = Secp256k1::new();
8549 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8553 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8555 channel_id: ChannelId::new_zero(),
8556 counterparty: ChannelCounterparty {
8557 features: channelmanager::provided_init_features(&UserConfig::default()),
8559 unspendable_punishment_reserve: 0,
8560 forwarding_info: None,
8561 outbound_htlc_minimum_msat: None,
8562 outbound_htlc_maximum_msat: None,
8564 funding_txo: Some(OutPoint {
8565 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8568 short_channel_id: Some(1),
8569 inbound_scid_alias: None,
8570 outbound_scid_alias: None,
8571 channel_value_satoshis: 10_000_000_000,
8573 balance_msat: 10_000_000_000,
8574 outbound_capacity_msat: 10_000_000_000,
8575 next_outbound_htlc_minimum_msat: 0,
8576 next_outbound_htlc_limit_msat: 10_000_000_000,
8577 inbound_capacity_msat: 0,
8578 unspendable_punishment_reserve: None,
8579 confirmations_required: None,
8580 confirmations: None,
8581 force_close_spend_delay: None,
8583 is_channel_ready: true,
8586 inbound_htlc_minimum_msat: None,
8587 inbound_htlc_maximum_msat: None,
8589 feerate_sat_per_1000_weight: None,
8590 channel_shutdown_state: Some(ChannelShutdownState::NotShuttingDown),
8591 pending_inbound_htlcs: Vec::new(),
8592 pending_outbound_htlcs: Vec::new(),
8596 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8597 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8598 starting_amount: u64, route_count: usize,
8599 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8600 let payer = payer_pubkey();
8601 let random_seed_bytes = [42; 32];
8603 let nodes = graph.read_only().nodes().clone();
8604 let mut route_endpoints = Vec::new();
8605 for _ in 0..route_count {
8607 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8608 let src = PublicKey::from_slice(nodes.unordered_keys()
8609 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8610 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8611 let dst = PublicKey::from_slice(nodes.unordered_keys()
8612 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8613 let params = PaymentParameters::from_node_id(dst, 42)
8614 .with_bolt11_features(features.clone()).unwrap();
8615 let first_hop = first_hop(src);
8616 let amt_msat = starting_amount + seed % 1_000_000;
8617 let route_params = RouteParameters::from_payment_params_and_value(
8618 params.clone(), amt_msat);
8620 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8621 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8623 route_endpoints.push((first_hop, params, amt_msat));
8636 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8637 use crate::ln::channelmanager;
8638 use crate::ln::features::Bolt11InvoiceFeatures;
8639 use crate::routing::gossip::NetworkGraph;
8640 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScoringFeeParameters};
8641 use crate::util::config::UserConfig;
8642 use crate::util::logger::{Logger, Record};
8643 use crate::util::test_utils::TestLogger;
8645 use criterion::Criterion;
8647 struct DummyLogger {}
8648 impl Logger for DummyLogger {
8649 fn log(&self, _record: Record) {}
8652 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8653 let logger = TestLogger::new();
8654 let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap();
8655 let scorer = FixedPenaltyScorer::with_penalty(0);
8656 generate_routes(bench, &network_graph, scorer, &Default::default(),
8657 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8660 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8661 let logger = TestLogger::new();
8662 let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap();
8663 let scorer = FixedPenaltyScorer::with_penalty(0);
8664 generate_routes(bench, &network_graph, scorer, &Default::default(),
8665 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8666 "generate_mpp_routes_with_zero_penalty_scorer");
8669 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8670 let logger = TestLogger::new();
8671 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8672 let params = ProbabilisticScoringFeeParameters::default();
8673 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8674 "generate_routes_with_probabilistic_scorer");
8677 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8678 let logger = TestLogger::new();
8679 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8680 let params = ProbabilisticScoringFeeParameters::default();
8681 generate_routes(bench, &network_graph, scorer, ¶ms,
8682 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8683 "generate_mpp_routes_with_probabilistic_scorer");
8686 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8687 let logger = TestLogger::new();
8688 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8689 let params = ProbabilisticScoringFeeParameters::default();
8690 generate_routes(bench, &network_graph, scorer, ¶ms,
8691 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8692 "generate_large_mpp_routes_with_probabilistic_scorer");
8695 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8696 let logger = TestLogger::new();
8697 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8698 let mut params = ProbabilisticScoringFeeParameters::default();
8699 params.linear_success_probability = false;
8700 generate_routes(bench, &network_graph, scorer, ¶ms,
8701 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8702 "generate_routes_with_nonlinear_probabilistic_scorer");
8705 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8706 let logger = TestLogger::new();
8707 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8708 let mut params = ProbabilisticScoringFeeParameters::default();
8709 params.linear_success_probability = false;
8710 generate_routes(bench, &network_graph, scorer, ¶ms,
8711 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8712 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8715 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8716 let logger = TestLogger::new();
8717 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8718 let mut params = ProbabilisticScoringFeeParameters::default();
8719 params.linear_success_probability = false;
8720 generate_routes(bench, &network_graph, scorer, ¶ms,
8721 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8722 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8725 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8726 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8727 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8728 bench_name: &'static str,
8730 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8731 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8733 // ...then benchmark finding paths between the nodes we learned.
8734 do_route_bench(bench, graph, scorer, score_params, bench_name, route_endpoints);
8738 fn do_route_bench<S: ScoreLookUp + ScoreUpdate>(
8739 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, scorer: S,
8740 score_params: &S::ScoreParams, bench_name: &'static str,
8741 route_endpoints: Vec<(ChannelDetails, PaymentParameters, u64)>,
8743 let payer = bench_utils::payer_pubkey();
8744 let random_seed_bytes = [42; 32];
8747 bench.bench_function(bench_name, |b| b.iter(|| {
8748 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8749 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8750 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8751 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());