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::payment::{ForwardNode, ForwardTlvs, PaymentConstraints, PaymentRelay, ReceiveTlvs};
16 use crate::ln::types::PaymentHash;
17 use crate::ln::channelmanager::{ChannelDetails, PaymentId, MIN_FINAL_CLTV_EXPIRY_DELTA};
18 use crate::ln::features::{BlindedHopFeatures, Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
19 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice};
21 use crate::onion_message::messenger::{DefaultMessageRouter, Destination, MessageRouter, OnionMessagePath};
22 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
23 use crate::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp};
24 use crate::sign::EntropySource;
25 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
26 use crate::util::logger::{Level, Logger};
27 use crate::crypto::chacha20::ChaCha20;
30 use crate::prelude::*;
31 use alloc::collections::BinaryHeap;
35 /// A [`Router`] implemented using [`find_route`].
36 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> where
38 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
39 ES::Target: EntropySource,
46 message_router: DefaultMessageRouter<G, L, ES>,
49 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
51 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
52 ES::Target: EntropySource,
54 /// Creates a new router.
55 pub fn new(network_graph: G, logger: L, entropy_source: ES, scorer: S, score_params: SP) -> Self {
56 let message_router = DefaultMessageRouter::new(network_graph.clone(), entropy_source.clone());
57 Self { network_graph, logger, entropy_source, scorer, score_params, message_router }
61 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
63 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
64 ES::Target: EntropySource,
69 params: &RouteParameters,
70 first_hops: Option<&[&ChannelDetails]>,
71 inflight_htlcs: InFlightHtlcs
72 ) -> Result<Route, LightningError> {
73 let random_seed_bytes = self.entropy_source.get_secure_random_bytes();
75 payer, params, &self.network_graph, first_hops, &*self.logger,
76 &ScorerAccountingForInFlightHtlcs::new(self.scorer.read_lock(), &inflight_htlcs),
82 fn create_blinded_payment_paths<
83 T: secp256k1::Signing + secp256k1::Verification
85 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
86 amount_msats: u64, secp_ctx: &Secp256k1<T>
87 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
88 // Limit the number of blinded paths that are computed.
89 const MAX_PAYMENT_PATHS: usize = 3;
91 // Ensure peers have at least three channels so that it is more difficult to infer the
92 // recipient's node_id.
93 const MIN_PEER_CHANNELS: usize = 3;
95 let network_graph = self.network_graph.deref().read_only();
96 let paths = first_hops.into_iter()
97 .filter(|details| details.counterparty.features.supports_route_blinding())
98 .filter(|details| amount_msats <= details.inbound_capacity_msat)
99 .filter(|details| amount_msats >= details.inbound_htlc_minimum_msat.unwrap_or(0))
100 .filter(|details| amount_msats <= details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX))
101 .filter(|details| network_graph
102 .node(&NodeId::from_pubkey(&details.counterparty.node_id))
103 .map(|node_info| node_info.channels.len() >= MIN_PEER_CHANNELS)
106 .filter_map(|details| {
107 let short_channel_id = match details.get_inbound_payment_scid() {
108 Some(short_channel_id) => short_channel_id,
111 let payment_relay: PaymentRelay = match details.counterparty.forwarding_info {
112 Some(forwarding_info) => match forwarding_info.try_into() {
113 Ok(payment_relay) => payment_relay,
114 Err(()) => return None,
119 let cltv_expiry_delta = payment_relay.cltv_expiry_delta as u32;
120 let payment_constraints = PaymentConstraints {
121 max_cltv_expiry: tlvs.payment_constraints.max_cltv_expiry + cltv_expiry_delta,
122 htlc_minimum_msat: details.inbound_htlc_minimum_msat.unwrap_or(0),
129 features: BlindedHopFeatures::empty(),
131 node_id: details.counterparty.node_id,
132 htlc_maximum_msat: details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX),
135 .map(|forward_node| {
136 BlindedPath::new_for_payment(
137 &[forward_node], recipient, tlvs.clone(), u64::MAX, MIN_FINAL_CLTV_EXPIRY_DELTA,
138 &*self.entropy_source, secp_ctx
141 .take(MAX_PAYMENT_PATHS)
142 .collect::<Result<Vec<_>, _>>();
145 Ok(paths) if !paths.is_empty() => Ok(paths),
147 if network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient)) {
148 BlindedPath::one_hop_for_payment(
149 recipient, tlvs, MIN_FINAL_CLTV_EXPIRY_DELTA, &*self.entropy_source, secp_ctx
150 ).map(|path| vec![path])
159 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
161 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
162 ES::Target: EntropySource,
165 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
166 ) -> Result<OnionMessagePath, ()> {
167 self.message_router.find_path(sender, peers, destination)
170 fn create_blinded_paths<
171 T: secp256k1::Signing + secp256k1::Verification
173 &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
174 ) -> Result<Vec<BlindedPath>, ()> {
175 self.message_router.create_blinded_paths(recipient, peers, secp_ctx)
179 /// A trait defining behavior for routing a payment.
180 pub trait Router: MessageRouter {
181 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
183 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
184 /// and [`RouteParameters::final_value_msat`], respectively.
186 &self, payer: &PublicKey, route_params: &RouteParameters,
187 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
188 ) -> Result<Route, LightningError>;
190 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
192 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
193 /// and [`RouteParameters::final_value_msat`], respectively.
195 /// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
197 fn find_route_with_id(
198 &self, payer: &PublicKey, route_params: &RouteParameters,
199 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
200 _payment_hash: PaymentHash, _payment_id: PaymentId
201 ) -> Result<Route, LightningError> {
202 self.find_route(payer, route_params, first_hops, inflight_htlcs)
205 /// Creates [`BlindedPath`]s for payment to the `recipient` node. The channels in `first_hops`
206 /// are assumed to be with the `recipient`'s peers. The payment secret and any constraints are
208 fn create_blinded_payment_paths<
209 T: secp256k1::Signing + secp256k1::Verification
211 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
212 amount_msats: u64, secp_ctx: &Secp256k1<T>
213 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()>;
216 /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
218 /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
221 /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
222 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> where S::Target: ScoreLookUp {
224 // Maps a channel's short channel id and its direction to the liquidity used up.
225 inflight_htlcs: &'a InFlightHtlcs,
227 impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
228 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
229 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
230 ScorerAccountingForInFlightHtlcs {
237 impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
238 type ScoreParams = <S::Target as ScoreLookUp>::ScoreParams;
239 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
240 let target = match candidate.target() {
241 Some(target) => target,
242 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
244 let short_channel_id = match candidate.short_channel_id() {
245 Some(short_channel_id) => short_channel_id,
246 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
248 let source = candidate.source();
249 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
250 &source, &target, short_channel_id
252 let usage = ChannelUsage {
253 inflight_htlc_msat: usage.inflight_htlc_msat.saturating_add(used_liquidity),
257 self.scorer.channel_penalty_msat(candidate, usage, score_params)
259 self.scorer.channel_penalty_msat(candidate, usage, score_params)
264 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
265 /// in-use channel liquidity.
267 pub struct InFlightHtlcs(
268 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
269 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
270 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
272 HashMap<(u64, bool), u64>
276 /// Constructs an empty `InFlightHtlcs`.
277 pub fn new() -> Self { InFlightHtlcs(new_hash_map()) }
279 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
280 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
281 if path.hops.is_empty() { return };
283 let mut cumulative_msat = 0;
284 if let Some(tail) = &path.blinded_tail {
285 cumulative_msat += tail.final_value_msat;
288 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
289 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
290 // the router excludes the payer node. In the following lines, the payer's information is
291 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
292 // in our sliding window of two.
293 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
294 .map(|hop| hop.pubkey)
295 .chain(core::iter::once(payer_node_id));
297 // Taking the reversed vector from above, we zip it with just the reversed hops list to
298 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
299 // the total amount sent.
300 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
301 cumulative_msat += next_hop.fee_msat;
303 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
304 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
305 .or_insert(cumulative_msat);
309 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
311 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
313 .entry((channel_scid, source < target))
314 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
315 .or_insert(used_msat);
318 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
320 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
321 self.0.get(&(channel_scid, source < target)).map(|v| *v)
325 impl Writeable for InFlightHtlcs {
326 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
329 impl Readable for InFlightHtlcs {
330 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
331 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
332 Ok(Self(infight_map))
336 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
337 /// that leads to it.
338 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
339 pub struct RouteHop {
340 /// The node_id of the node at this hop.
341 pub pubkey: PublicKey,
342 /// The node_announcement features of the node at this hop. For the last hop, these may be
343 /// amended to match the features present in the invoice this node generated.
344 pub node_features: NodeFeatures,
345 /// The channel that should be used from the previous hop to reach this node.
346 pub short_channel_id: u64,
347 /// The channel_announcement features of the channel that should be used from the previous hop
348 /// to reach this node.
349 pub channel_features: ChannelFeatures,
350 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
351 /// If this is the last hop in [`Path::hops`]:
352 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
353 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
355 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
357 /// The CLTV delta added for this hop.
358 /// If this is the last hop in [`Path::hops`]:
359 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
360 /// * otherwise, this is the CLTV delta expected at the destination
362 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
363 pub cltv_expiry_delta: u32,
364 /// Indicates whether this hop is possibly announced in the public network graph.
366 /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
367 /// either know for sure it's announced in the public graph, or if any public channels exist
368 /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
369 /// the channel to be unannounced.
371 /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
372 pub maybe_announced_channel: bool,
375 impl_writeable_tlv_based!(RouteHop, {
376 (0, pubkey, required),
377 (1, maybe_announced_channel, (default_value, true)),
378 (2, node_features, required),
379 (4, short_channel_id, required),
380 (6, channel_features, required),
381 (8, fee_msat, required),
382 (10, cltv_expiry_delta, required),
385 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
386 /// their [`Bolt12Invoice`].
388 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
389 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
390 pub struct BlindedTail {
391 /// The hops of the [`BlindedPath`] provided by the recipient.
393 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
394 pub hops: Vec<BlindedHop>,
395 /// The blinding point of the [`BlindedPath`] provided by the recipient.
397 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
398 pub blinding_point: PublicKey,
399 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
400 /// inferring the destination. May be 0.
401 pub excess_final_cltv_expiry_delta: u32,
402 /// The total amount paid on this [`Path`], excluding the fees.
403 pub final_value_msat: u64,
406 impl_writeable_tlv_based!(BlindedTail, {
407 (0, hops, required_vec),
408 (2, blinding_point, required),
409 (4, excess_final_cltv_expiry_delta, required),
410 (6, final_value_msat, required),
413 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
414 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
415 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
417 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
418 pub hops: Vec<RouteHop>,
419 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
420 pub blinded_tail: Option<BlindedTail>,
424 /// Gets the fees for a given path, excluding any excess paid to the recipient.
425 pub fn fee_msat(&self) -> u64 {
426 match &self.blinded_tail {
427 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
429 // Do not count last hop of each path since that's the full value of the payment
430 self.hops.split_last().map_or(0,
431 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
436 /// Gets the total amount paid on this [`Path`], excluding the fees.
437 pub fn final_value_msat(&self) -> u64 {
438 match &self.blinded_tail {
439 Some(blinded_tail) => blinded_tail.final_value_msat,
440 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
444 /// Gets the final hop's CLTV expiry delta.
445 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
446 match &self.blinded_tail {
448 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
453 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
454 /// it can take multiple paths. Each path is composed of one or more hops through the network.
455 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
457 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
458 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
460 pub paths: Vec<Path>,
461 /// The `route_params` parameter passed to [`find_route`].
463 /// This is used by `ChannelManager` to track information which may be required for retries.
465 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
466 pub route_params: Option<RouteParameters>,
470 /// Returns the total amount of fees paid on this [`Route`].
472 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
473 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
474 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
476 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
477 pub fn get_total_fees(&self) -> u64 {
478 let overpaid_value_msat = self.route_params.as_ref()
479 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
480 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
483 /// Returns the total amount paid on this [`Route`], excluding the fees.
485 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
486 /// we had to reach the [`htlc_minimum_msat`] limits.
488 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
489 pub fn get_total_amount(&self) -> u64 {
490 self.paths.iter().map(|path| path.final_value_msat()).sum()
494 impl fmt::Display for Route {
495 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
496 log_route!(self).fmt(f)
500 const SERIALIZATION_VERSION: u8 = 1;
501 const MIN_SERIALIZATION_VERSION: u8 = 1;
503 impl Writeable for Route {
504 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
505 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
506 (self.paths.len() as u64).write(writer)?;
507 let mut blinded_tails = Vec::new();
508 for (idx, path) in self.paths.iter().enumerate() {
509 (path.hops.len() as u8).write(writer)?;
510 for hop in path.hops.iter() {
513 if let Some(blinded_tail) = &path.blinded_tail {
514 if blinded_tails.is_empty() {
515 blinded_tails = Vec::with_capacity(path.hops.len());
517 blinded_tails.push(None);
520 blinded_tails.push(Some(blinded_tail));
521 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
523 write_tlv_fields!(writer, {
524 // For compatibility with LDK versions prior to 0.0.117, we take the individual
525 // RouteParameters' fields and reconstruct them on read.
526 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
527 (2, blinded_tails, optional_vec),
528 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
529 (5, self.route_params.as_ref().and_then(|p| p.max_total_routing_fee_msat), option),
535 impl Readable for Route {
536 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
537 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
538 let path_count: u64 = Readable::read(reader)?;
539 if path_count == 0 { return Err(DecodeError::InvalidValue); }
540 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
541 let mut min_final_cltv_expiry_delta = u32::max_value();
542 for _ in 0..path_count {
543 let hop_count: u8 = Readable::read(reader)?;
544 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
545 for _ in 0..hop_count {
546 hops.push(Readable::read(reader)?);
548 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
549 min_final_cltv_expiry_delta =
550 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
551 paths.push(Path { hops, blinded_tail: None });
553 _init_and_read_len_prefixed_tlv_fields!(reader, {
554 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
555 (2, blinded_tails, optional_vec),
556 (3, final_value_msat, option),
557 (5, max_total_routing_fee_msat, option)
559 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
560 if blinded_tails.len() != 0 {
561 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
562 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
563 path.blinded_tail = blinded_tail_opt;
567 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
568 let route_params = match (payment_params, final_value_msat) {
569 (Some(payment_params), Some(final_value_msat)) => {
570 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
575 Ok(Route { paths, route_params })
579 /// Parameters needed to find a [`Route`].
581 /// Passed to [`find_route`] and [`build_route_from_hops`].
582 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
583 pub struct RouteParameters {
584 /// The parameters of the failed payment path.
585 pub payment_params: PaymentParameters,
587 /// The amount in msats sent on the failed payment path.
588 pub final_value_msat: u64,
590 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
592 /// This limit also applies to the total fees that may arise while retrying failed payment
595 /// Note that values below a few sats may result in some paths being spuriously ignored.
596 pub max_total_routing_fee_msat: Option<u64>,
599 impl RouteParameters {
600 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
602 /// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
603 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
604 Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
608 impl Writeable for RouteParameters {
609 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
610 write_tlv_fields!(writer, {
611 (0, self.payment_params, required),
612 (1, self.max_total_routing_fee_msat, option),
613 (2, self.final_value_msat, required),
614 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
615 // `RouteParameters` directly. For compatibility, we write it here.
616 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
622 impl Readable for RouteParameters {
623 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
624 _init_and_read_len_prefixed_tlv_fields!(reader, {
625 (0, payment_params, (required: ReadableArgs, 0)),
626 (1, max_total_routing_fee_msat, option),
627 (2, final_value_msat, required),
628 (4, final_cltv_delta, option),
630 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
631 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
632 if final_cltv_expiry_delta == &0 {
633 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
638 final_value_msat: final_value_msat.0.unwrap(),
639 max_total_routing_fee_msat,
644 /// Maximum total CTLV difference we allow for a full payment path.
645 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
647 /// Maximum number of paths we allow an (MPP) payment to have.
648 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
649 // limits, but for now more than 10 paths likely carries too much one-path failure.
650 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
652 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
654 // The median hop CLTV expiry delta currently seen in the network.
655 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
657 /// Estimated maximum number of hops that can be included in a payment path. May be inaccurate if
658 /// payment metadata, custom TLVs, or blinded paths are included in the payment.
659 // During routing, we only consider paths shorter than our maximum length estimate.
660 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
661 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
662 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
664 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
665 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
666 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
667 // (payment_secret and total_msat) = 93 bytes for the final hop.
668 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
669 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
670 pub const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
672 /// Information used to route a payment.
673 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
674 pub struct PaymentParameters {
675 /// Information about the payee, such as their features and route hints for their channels.
678 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
679 pub expiry_time: Option<u64>,
681 /// The maximum total CLTV delta we accept for the route.
682 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
683 pub max_total_cltv_expiry_delta: u32,
685 /// The maximum number of paths that may be used by (MPP) payments.
686 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
687 pub max_path_count: u8,
689 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
690 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
691 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
692 /// increasing failure probability for those paths.
694 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
695 /// restriction have been found. While paths which meet this criteria will be searched for, it
696 /// is ultimately up to the scorer to select them over other paths.
698 /// A value of 0 will allow payments up to and including a channel's total announced usable
699 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
702 pub max_channel_saturation_power_of_half: u8,
704 /// A list of SCIDs which this payment was previously attempted over and which caused the
705 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
707 pub previously_failed_channels: Vec<u64>,
709 /// A list of indices corresponding to blinded paths in [`Payee::Blinded::route_hints`] which this
710 /// payment was previously attempted over and which caused the payment to fail. Future attempts
711 /// for the same payment shouldn't be relayed through any of these blinded paths.
712 pub previously_failed_blinded_path_idxs: Vec<u64>,
715 impl Writeable for PaymentParameters {
716 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
717 let mut clear_hints = &vec![];
718 let mut blinded_hints = &vec![];
720 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
721 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
723 write_tlv_fields!(writer, {
724 (0, self.payee.node_id(), option),
725 (1, self.max_total_cltv_expiry_delta, required),
726 (2, self.payee.features(), option),
727 (3, self.max_path_count, required),
728 (4, *clear_hints, required_vec),
729 (5, self.max_channel_saturation_power_of_half, required),
730 (6, self.expiry_time, option),
731 (7, self.previously_failed_channels, required_vec),
732 (8, *blinded_hints, optional_vec),
733 (9, self.payee.final_cltv_expiry_delta(), option),
734 (11, self.previously_failed_blinded_path_idxs, required_vec),
740 impl ReadableArgs<u32> for PaymentParameters {
741 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
742 _init_and_read_len_prefixed_tlv_fields!(reader, {
743 (0, payee_pubkey, option),
744 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
745 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
746 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
747 (4, clear_route_hints, required_vec),
748 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
749 (6, expiry_time, option),
750 (7, previously_failed_channels, optional_vec),
751 (8, blinded_route_hints, optional_vec),
752 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
753 (11, previously_failed_blinded_path_idxs, optional_vec),
755 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
756 let payee = if blinded_route_hints.len() != 0 {
757 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
759 route_hints: blinded_route_hints,
760 features: features.and_then(|f: Features| f.bolt12()),
764 route_hints: clear_route_hints,
765 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
766 features: features.and_then(|f| f.bolt11()),
767 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
771 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
772 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
774 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
776 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
777 previously_failed_blinded_path_idxs: previously_failed_blinded_path_idxs.unwrap_or(Vec::new()),
783 impl PaymentParameters {
784 /// Creates a payee with the node id of the given `pubkey`.
786 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
788 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
790 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
792 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
793 max_path_count: DEFAULT_MAX_PATH_COUNT,
794 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
795 previously_failed_channels: Vec::new(),
796 previously_failed_blinded_path_idxs: Vec::new(),
800 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
802 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
805 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
806 /// whether your router will be allowed to find a multi-part route for this payment. If you
807 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
808 /// [`RecipientOnionFields::secret_only`].
810 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
811 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
812 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
813 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
814 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
817 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
818 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
819 /// [`PaymentParameters::expiry_time`].
820 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
821 Self::blinded(invoice.payment_paths().to_vec())
822 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
823 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
826 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
827 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
829 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
831 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
832 max_path_count: DEFAULT_MAX_PATH_COUNT,
833 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
834 previously_failed_channels: Vec::new(),
835 previously_failed_blinded_path_idxs: Vec::new(),
839 /// Includes the payee's features. Errors if the parameters were not initialized with
840 /// [`PaymentParameters::from_bolt12_invoice`].
842 /// This is not exported to bindings users since bindings don't support move semantics
843 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
845 Payee::Clear { .. } => Err(()),
846 Payee::Blinded { route_hints, .. } =>
847 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
851 /// Includes the payee's features. Errors if the parameters were initialized with
852 /// [`PaymentParameters::from_bolt12_invoice`].
854 /// This is not exported to bindings users since bindings don't support move semantics
855 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
857 Payee::Blinded { .. } => Err(()),
858 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
860 payee: Payee::Clear {
861 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
867 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
868 /// [`PaymentParameters::from_bolt12_invoice`].
870 /// This is not exported to bindings users since bindings don't support move semantics
871 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
873 Payee::Blinded { .. } => Err(()),
874 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
876 payee: Payee::Clear {
877 route_hints, node_id, features, final_cltv_expiry_delta,
883 /// Includes a payment expiration in seconds relative to the UNIX epoch.
885 /// This is not exported to bindings users since bindings don't support move semantics
886 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
887 Self { expiry_time: Some(expiry_time), ..self }
890 /// Includes a limit for the total CLTV expiry delta which is considered during routing
892 /// This is not exported to bindings users since bindings don't support move semantics
893 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
894 Self { max_total_cltv_expiry_delta, ..self }
897 /// Includes a limit for the maximum number of payment paths that may be used.
899 /// This is not exported to bindings users since bindings don't support move semantics
900 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
901 Self { max_path_count, ..self }
904 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
905 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
907 /// This is not exported to bindings users since bindings don't support move semantics
908 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
909 Self { max_channel_saturation_power_of_half, ..self }
912 pub(crate) fn insert_previously_failed_blinded_path(&mut self, failed_blinded_tail: &BlindedTail) {
913 let mut found_blinded_tail = false;
914 for (idx, (_, path)) in self.payee.blinded_route_hints().iter().enumerate() {
915 if failed_blinded_tail.hops == path.blinded_hops &&
916 failed_blinded_tail.blinding_point == path.blinding_point
918 self.previously_failed_blinded_path_idxs.push(idx as u64);
919 found_blinded_tail = true;
922 debug_assert!(found_blinded_tail);
926 /// The recipient of a payment, differing based on whether they've hidden their identity with route
928 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
930 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
931 /// will be included in the final [`Route`].
933 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
935 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
936 /// Features supported by the payee.
938 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
940 features: Option<Bolt12InvoiceFeatures>,
942 /// The recipient included these route hints in their BOLT11 invoice.
944 /// The node id of the payee.
946 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
947 route_hints: Vec<RouteHint>,
948 /// Features supported by the payee.
950 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
951 /// does not contain any features.
953 /// [`for_keysend`]: PaymentParameters::for_keysend
954 features: Option<Bolt11InvoiceFeatures>,
955 /// The minimum CLTV delta at the end of the route. This value must not be zero.
956 final_cltv_expiry_delta: u32,
961 fn node_id(&self) -> Option<PublicKey> {
963 Self::Clear { node_id, .. } => Some(*node_id),
967 fn node_features(&self) -> Option<NodeFeatures> {
969 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
970 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
973 fn supports_basic_mpp(&self) -> bool {
975 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
976 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
979 fn features(&self) -> Option<FeaturesRef> {
981 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
982 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
985 fn final_cltv_expiry_delta(&self) -> Option<u32> {
987 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
991 pub(crate) fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
993 Self::Blinded { route_hints, .. } => &route_hints[..],
994 Self::Clear { .. } => &[]
998 fn unblinded_route_hints(&self) -> &[RouteHint] {
1000 Self::Blinded { .. } => &[],
1001 Self::Clear { route_hints, .. } => &route_hints[..]
1006 enum FeaturesRef<'a> {
1007 Bolt11(&'a Bolt11InvoiceFeatures),
1008 Bolt12(&'a Bolt12InvoiceFeatures),
1011 Bolt11(Bolt11InvoiceFeatures),
1012 Bolt12(Bolt12InvoiceFeatures),
1016 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
1018 Self::Bolt12(f) => Some(f),
1022 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
1024 Self::Bolt11(f) => Some(f),
1030 impl<'a> Writeable for FeaturesRef<'a> {
1031 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1033 Self::Bolt11(f) => Ok(f.write(w)?),
1034 Self::Bolt12(f) => Ok(f.write(w)?),
1039 impl ReadableArgs<bool> for Features {
1040 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
1041 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
1042 Ok(Self::Bolt12(Readable::read(reader)?))
1046 /// A list of hops along a payment path terminating with a channel to the recipient.
1047 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1048 pub struct RouteHint(pub Vec<RouteHintHop>);
1050 impl Writeable for RouteHint {
1051 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1052 (self.0.len() as u64).write(writer)?;
1053 for hop in self.0.iter() {
1060 impl Readable for RouteHint {
1061 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1062 let hop_count: u64 = Readable::read(reader)?;
1063 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
1064 for _ in 0..hop_count {
1065 hops.push(Readable::read(reader)?);
1071 /// A channel descriptor for a hop along a payment path.
1073 /// While this generally comes from BOLT 11's `r` field, this struct includes more fields than are
1074 /// available in BOLT 11. Thus, encoding and decoding this via `lightning-invoice` is lossy, as
1075 /// fields not supported in BOLT 11 will be stripped.
1076 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1077 pub struct RouteHintHop {
1078 /// The node_id of the non-target end of the route
1079 pub src_node_id: PublicKey,
1080 /// The short_channel_id of this channel
1081 pub short_channel_id: u64,
1082 /// The fees which must be paid to use this channel
1083 pub fees: RoutingFees,
1084 /// The difference in CLTV values between this node and the next node.
1085 pub cltv_expiry_delta: u16,
1086 /// The minimum value, in msat, which must be relayed to the next hop.
1087 pub htlc_minimum_msat: Option<u64>,
1088 /// The maximum value in msat available for routing with a single HTLC.
1089 pub htlc_maximum_msat: Option<u64>,
1092 impl_writeable_tlv_based!(RouteHintHop, {
1093 (0, src_node_id, required),
1094 (1, htlc_minimum_msat, option),
1095 (2, short_channel_id, required),
1096 (3, htlc_maximum_msat, option),
1097 (4, fees, required),
1098 (6, cltv_expiry_delta, required),
1101 #[derive(Eq, PartialEq)]
1102 #[repr(align(64))] // Force the size to 64 bytes
1103 struct RouteGraphNode {
1106 // The maximum value a yet-to-be-constructed payment path might flow through this node.
1107 // This value is upper-bounded by us by:
1108 // - how much is needed for a path being constructed
1109 // - how much value can channels following this node (up to the destination) can contribute,
1110 // considering their capacity and fees
1111 value_contribution_msat: u64,
1112 total_cltv_delta: u32,
1113 /// The number of hops walked up to this node.
1114 path_length_to_node: u8,
1117 impl cmp::Ord for RouteGraphNode {
1118 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
1119 other.score.cmp(&self.score).then_with(|| other.node_id.cmp(&self.node_id))
1123 impl cmp::PartialOrd for RouteGraphNode {
1124 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
1125 Some(self.cmp(other))
1129 // While RouteGraphNode can be laid out with fewer bytes, performance appears to be improved
1130 // substantially when it is laid out at exactly 64 bytes.
1132 // Thus, we use `#[repr(C)]` on the struct to force a suboptimal layout and check that it stays 64
1134 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1135 const _GRAPH_NODE_SMALL: usize = 64 - core::mem::size_of::<RouteGraphNode>();
1136 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1137 const _GRAPH_NODE_FIXED_SIZE: usize = core::mem::size_of::<RouteGraphNode>() - 64;
1139 /// A [`CandidateRouteHop::FirstHop`] entry.
1140 #[derive(Clone, Debug)]
1141 pub struct FirstHopCandidate<'a> {
1142 /// Channel details of the first hop
1144 /// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1145 /// has been funded and is able to pay), and accessor methods may panic otherwise.
1147 /// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1149 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1150 pub details: &'a ChannelDetails,
1151 /// The node id of the payer, which is also the source side of this candidate route hop.
1153 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1154 pub payer_node_id: &'a NodeId,
1157 /// A [`CandidateRouteHop::PublicHop`] entry.
1158 #[derive(Clone, Debug)]
1159 pub struct PublicHopCandidate<'a> {
1160 /// Information about the channel, including potentially its capacity and
1161 /// direction-specific information.
1163 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1164 pub info: DirectedChannelInfo<'a>,
1165 /// The short channel ID of the channel, i.e. the identifier by which we refer to this
1167 pub short_channel_id: u64,
1170 /// A [`CandidateRouteHop::PrivateHop`] entry.
1171 #[derive(Clone, Debug)]
1172 pub struct PrivateHopCandidate<'a> {
1173 /// Information about the private hop communicated via BOLT 11.
1175 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1176 pub hint: &'a RouteHintHop,
1177 /// Node id of the next hop in BOLT 11 route hint.
1179 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1180 pub target_node_id: &'a NodeId
1183 /// A [`CandidateRouteHop::Blinded`] entry.
1184 #[derive(Clone, Debug)]
1185 pub struct BlindedPathCandidate<'a> {
1186 /// The node id of the introduction node, resolved from either the [`NetworkGraph`] or first
1189 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1190 pub source_node_id: &'a NodeId,
1191 /// Information about the blinded path including the fee, HTLC amount limits, and
1192 /// cryptographic material required to build an HTLC through the given path.
1194 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1195 pub hint: &'a (BlindedPayInfo, BlindedPath),
1196 /// Index of the hint in the original list of blinded hints.
1198 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1199 /// a short channel ID for this hop.
1203 /// A [`CandidateRouteHop::OneHopBlinded`] entry.
1204 #[derive(Clone, Debug)]
1205 pub struct OneHopBlindedPathCandidate<'a> {
1206 /// The node id of the introduction node, resolved from either the [`NetworkGraph`] or first
1209 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1210 pub source_node_id: &'a NodeId,
1211 /// Information about the blinded path including the fee, HTLC amount limits, and
1212 /// cryptographic material required to build an HTLC terminating with the given path.
1214 /// Note that the [`BlindedPayInfo`] is ignored here.
1216 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1217 pub hint: &'a (BlindedPayInfo, BlindedPath),
1218 /// Index of the hint in the original list of blinded hints.
1220 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1221 /// a short channel ID for this hop.
1225 /// A wrapper around the various hop representations.
1227 /// Can be used to examine the properties of a hop,
1228 /// potentially to decide whether to include it in a route.
1229 #[derive(Clone, Debug)]
1230 pub enum CandidateRouteHop<'a> {
1231 /// A hop from the payer, where the outbound liquidity is known.
1232 FirstHop(FirstHopCandidate<'a>),
1233 /// A hop found in the [`ReadOnlyNetworkGraph`].
1234 PublicHop(PublicHopCandidate<'a>),
1235 /// A private hop communicated by the payee, generally via a BOLT 11 invoice.
1237 /// Because BOLT 11 route hints can take multiple hops to get to the destination, this may not
1238 /// terminate at the payee.
1239 PrivateHop(PrivateHopCandidate<'a>),
1240 /// A blinded path which starts with an introduction point and ultimately terminates with the
1243 /// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1244 /// `None` in this state.
1246 /// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1247 /// path, the full path is treated as a single [`CandidateRouteHop`].
1248 Blinded(BlindedPathCandidate<'a>),
1249 /// Similar to [`Self::Blinded`], but the path here only has one hop.
1251 /// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1252 /// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1253 /// payee's identity - it's the introduction point!
1255 /// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1256 /// to the hops *between* the introduction node and the destination.
1258 /// This primarily exists to track that we need to included a blinded path at the end of our
1259 /// [`Route`], even though it doesn't actually add an additional hop in the payment.
1260 OneHopBlinded(OneHopBlindedPathCandidate<'a>),
1263 impl<'a> CandidateRouteHop<'a> {
1264 /// Returns the short channel ID for this hop, if one is known.
1266 /// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1267 /// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1269 /// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1270 /// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1271 /// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1272 /// (which is always true for channels which are funded and ready for use).
1274 /// In other words, this should always return `Some` as long as the candidate hop is not a
1275 /// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1277 /// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1278 /// define a global namespace.
1280 fn short_channel_id(&self) -> Option<u64> {
1282 CandidateRouteHop::FirstHop(hop) => hop.details.get_outbound_payment_scid(),
1283 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1284 CandidateRouteHop::PrivateHop(hop) => Some(hop.hint.short_channel_id),
1285 CandidateRouteHop::Blinded(_) => None,
1286 CandidateRouteHop::OneHopBlinded(_) => None,
1290 /// Returns the globally unique short channel ID for this hop, if one is known.
1292 /// This only returns `Some` if the channel is public (either our own, or one we've learned
1293 /// from the public network graph), and thus the short channel ID we have for this channel is
1294 /// globally unique and identifies this channel in a global namespace.
1296 pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1298 CandidateRouteHop::FirstHop(hop) => if hop.details.is_public { hop.details.short_channel_id } else { None },
1299 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1300 CandidateRouteHop::PrivateHop(_) => None,
1301 CandidateRouteHop::Blinded(_) => None,
1302 CandidateRouteHop::OneHopBlinded(_) => None,
1306 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1307 fn features(&self) -> ChannelFeatures {
1309 CandidateRouteHop::FirstHop(hop) => hop.details.counterparty.features.to_context(),
1310 CandidateRouteHop::PublicHop(hop) => hop.info.channel().features.clone(),
1311 CandidateRouteHop::PrivateHop(_) => ChannelFeatures::empty(),
1312 CandidateRouteHop::Blinded(_) => ChannelFeatures::empty(),
1313 CandidateRouteHop::OneHopBlinded(_) => ChannelFeatures::empty(),
1317 /// Returns the required difference in HTLC CLTV expiry between the [`Self::source`] and the
1318 /// next-hop for an HTLC taking this hop.
1320 /// This is the time that the node(s) in this hop have to claim the HTLC on-chain if the
1321 /// next-hop goes on chain with a payment preimage.
1323 pub fn cltv_expiry_delta(&self) -> u32 {
1325 CandidateRouteHop::FirstHop(_) => 0,
1326 CandidateRouteHop::PublicHop(hop) => hop.info.direction().cltv_expiry_delta as u32,
1327 CandidateRouteHop::PrivateHop(hop) => hop.hint.cltv_expiry_delta as u32,
1328 CandidateRouteHop::Blinded(hop) => hop.hint.0.cltv_expiry_delta as u32,
1329 CandidateRouteHop::OneHopBlinded(_) => 0,
1333 /// Returns the minimum amount that can be sent over this hop, in millisatoshis.
1335 pub fn htlc_minimum_msat(&self) -> u64 {
1337 CandidateRouteHop::FirstHop(hop) => hop.details.next_outbound_htlc_minimum_msat,
1338 CandidateRouteHop::PublicHop(hop) => hop.info.direction().htlc_minimum_msat,
1339 CandidateRouteHop::PrivateHop(hop) => hop.hint.htlc_minimum_msat.unwrap_or(0),
1340 CandidateRouteHop::Blinded(hop) => hop.hint.0.htlc_minimum_msat,
1341 CandidateRouteHop::OneHopBlinded { .. } => 0,
1345 /// Returns the fees that must be paid to route an HTLC over this channel.
1347 pub fn fees(&self) -> RoutingFees {
1349 CandidateRouteHop::FirstHop(_) => RoutingFees {
1350 base_msat: 0, proportional_millionths: 0,
1352 CandidateRouteHop::PublicHop(hop) => hop.info.direction().fees,
1353 CandidateRouteHop::PrivateHop(hop) => hop.hint.fees,
1354 CandidateRouteHop::Blinded(hop) => {
1356 base_msat: hop.hint.0.fee_base_msat,
1357 proportional_millionths: hop.hint.0.fee_proportional_millionths
1360 CandidateRouteHop::OneHopBlinded(_) =>
1361 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1365 /// Fetch the effective capacity of this hop.
1367 /// Note that this may be somewhat expensive, so calls to this should be limited and results
1369 fn effective_capacity(&self) -> EffectiveCapacity {
1371 CandidateRouteHop::FirstHop(hop) => EffectiveCapacity::ExactLiquidity {
1372 liquidity_msat: hop.details.next_outbound_htlc_limit_msat,
1374 CandidateRouteHop::PublicHop(hop) => hop.info.effective_capacity(),
1375 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. }) =>
1376 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1377 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. }) =>
1378 EffectiveCapacity::Infinite,
1379 CandidateRouteHop::Blinded(hop) =>
1380 EffectiveCapacity::HintMaxHTLC { amount_msat: hop.hint.0.htlc_maximum_msat },
1381 CandidateRouteHop::OneHopBlinded(_) => EffectiveCapacity::Infinite,
1385 /// Returns an ID describing the given hop.
1387 /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1389 fn id(&self) -> CandidateHopId {
1391 CandidateRouteHop::Blinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1392 CandidateRouteHop::OneHopBlinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1393 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1396 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1398 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1404 fn blinded_hint_idx(&self) -> Option<usize> {
1406 Self::Blinded(BlindedPathCandidate { hint_idx, .. }) |
1407 Self::OneHopBlinded(OneHopBlindedPathCandidate { hint_idx, .. }) => {
1413 /// Returns the source node id of current hop.
1415 /// Source node id refers to the node forwarding the HTLC through this hop.
1417 /// For [`Self::FirstHop`] we return payer's node id.
1419 pub fn source(&self) -> NodeId {
1421 CandidateRouteHop::FirstHop(hop) => *hop.payer_node_id,
1422 CandidateRouteHop::PublicHop(hop) => *hop.info.source(),
1423 CandidateRouteHop::PrivateHop(hop) => hop.hint.src_node_id.into(),
1424 CandidateRouteHop::Blinded(hop) => *hop.source_node_id,
1425 CandidateRouteHop::OneHopBlinded(hop) => *hop.source_node_id,
1428 /// Returns the target node id of this hop, if known.
1430 /// Target node id refers to the node receiving the HTLC after this hop.
1432 /// For [`Self::Blinded`] we return `None` because the ultimate destination after the blinded
1433 /// path is unknown.
1435 /// For [`Self::OneHopBlinded`] we return `None` because the target is the same as the source,
1436 /// and such a return value would be somewhat nonsensical.
1438 pub fn target(&self) -> Option<NodeId> {
1440 CandidateRouteHop::FirstHop(hop) => Some(hop.details.counterparty.node_id.into()),
1441 CandidateRouteHop::PublicHop(hop) => Some(*hop.info.target()),
1442 CandidateRouteHop::PrivateHop(hop) => Some(*hop.target_node_id),
1443 CandidateRouteHop::Blinded(_) => None,
1444 CandidateRouteHop::OneHopBlinded(_) => None,
1449 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1451 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1453 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1454 /// isn't guaranteed to be unique at all.
1456 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1457 /// difficult-to-use API.
1458 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1459 enum CandidateHopId {
1460 /// Contains (scid, src_node_id < target_node_id)
1462 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1467 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1468 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1470 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1471 EffectiveCapacity::Infinite => u64::max_value(),
1472 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1473 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1474 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1475 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1476 // expected to have been generated from up-to-date capacity information.
1477 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1478 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1479 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1483 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1484 -> bool where I1::Item: PartialEq<I2::Item> {
1486 let a = iter_a.next();
1487 let b = iter_b.next();
1488 if a.is_none() && b.is_none() { return true; }
1489 if a.is_none() || b.is_none() { return false; }
1490 if a.unwrap().ne(&b.unwrap()) { return false; }
1494 /// It's useful to keep track of the hops associated with the fees required to use them,
1495 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1496 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1497 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1499 #[repr(C)] // Force fields to appear in the order we define them.
1500 struct PathBuildingHop<'a> {
1501 candidate: CandidateRouteHop<'a>,
1502 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1503 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1504 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1505 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1506 /// avoid processing them again.
1507 was_processed: bool,
1508 /// Used to compare channels when choosing the for routing.
1509 /// Includes paying for the use of a hop and the following hops, as well as
1510 /// an estimated cost of reaching this hop.
1511 /// Might get stale when fees are recomputed. Primarily for internal use.
1512 total_fee_msat: u64,
1513 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1514 /// walk and may be invalid thereafter.
1515 path_htlc_minimum_msat: u64,
1516 /// All penalties incurred from this channel on the way to the destination, as calculated using
1517 /// channel scoring.
1518 path_penalty_msat: u64,
1520 // The last 16 bytes are on the next cache line by default in glibc's malloc. Thus, we should
1521 // only place fields which are not hot there. Luckily, the next three fields are only read if
1522 // we end up on the selected path, and only in the final path layout phase, so we don't care
1523 // too much if reading them is slow.
1527 /// All the fees paid *after* this channel on the way to the destination
1528 next_hops_fee_msat: u64,
1529 /// Fee paid for the use of the current channel (see candidate.fees()).
1530 /// The value will be actually deducted from the counterparty balance on the previous link.
1531 hop_use_fee_msat: u64,
1533 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1534 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1535 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1536 // value_contribution_msat, which requires tracking it here. See comments below where it is
1537 // used for more info.
1538 value_contribution_msat: u64,
1541 // Checks that the entries in the `find_route` `dist` map fit in (exactly) two standard x86-64
1542 // cache lines. Sadly, they're not guaranteed to actually lie on a cache line (and in fact,
1543 // generally won't, because at least glibc's malloc will align to a nice, big, round
1544 // boundary...plus 16), but at least it will reduce the amount of data we'll need to load.
1546 // Note that these assertions only pass on somewhat recent rustc, and thus are gated on the
1549 const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::<(NodeId, PathBuildingHop)>();
1551 const _NODE_MAP_SIZE_EXACTLY_CACHE_LINES: usize = core::mem::size_of::<(NodeId, PathBuildingHop)>() - 128;
1553 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1554 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1555 let mut debug_struct = f.debug_struct("PathBuildingHop");
1557 .field("node_id", &self.candidate.target())
1558 .field("short_channel_id", &self.candidate.short_channel_id())
1559 .field("total_fee_msat", &self.total_fee_msat)
1560 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1561 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1562 .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)))
1563 .field("path_penalty_msat", &self.path_penalty_msat)
1564 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1565 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1566 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1567 let debug_struct = debug_struct
1568 .field("value_contribution_msat", &self.value_contribution_msat);
1569 debug_struct.finish()
1573 // Instantiated with a list of hops with correct data in them collected during path finding,
1574 // an instance of this struct should be further modified only via given methods.
1576 struct PaymentPath<'a> {
1577 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1580 impl<'a> PaymentPath<'a> {
1581 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1582 fn get_value_msat(&self) -> u64 {
1583 self.hops.last().unwrap().0.fee_msat
1586 fn get_path_penalty_msat(&self) -> u64 {
1587 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1590 fn get_total_fee_paid_msat(&self) -> u64 {
1591 if self.hops.len() < 1 {
1595 // Can't use next_hops_fee_msat because it gets outdated.
1596 for (i, (hop, _)) in self.hops.iter().enumerate() {
1597 if i != self.hops.len() - 1 {
1598 result += hop.fee_msat;
1604 fn get_cost_msat(&self) -> u64 {
1605 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1608 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1609 // to change fees may result in an inconsistency.
1611 // Sometimes we call this function right after constructing a path which is inconsistent in
1612 // that it the value being transferred has decreased while we were doing path finding, leading
1613 // to the fees being paid not lining up with the actual limits.
1615 // Note that this function is not aware of the available_liquidity limit, and thus does not
1616 // support increasing the value being transferred beyond what was selected during the initial
1619 // Returns the amount that this path contributes to the total payment value, which may be greater
1620 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1621 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1622 let mut extra_contribution_msat = 0;
1623 let mut total_fee_paid_msat = 0 as u64;
1624 for i in (0..self.hops.len()).rev() {
1625 let last_hop = i == self.hops.len() - 1;
1627 // For non-last-hop, this value will represent the fees paid on the current hop. It
1628 // will consist of the fees for the use of the next hop, and extra fees to match
1629 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1630 let mut cur_hop_fees_msat = 0;
1632 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1635 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1636 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1637 cur_hop.path_penalty_msat += extra_contribution_msat;
1638 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1639 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1640 // set it too high just to maliciously take more fees by exploiting this
1641 // match htlc_minimum_msat logic.
1642 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1643 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1644 // Note that there is a risk that *previous hops* (those closer to us, as we go
1645 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1647 // This might make us end up with a broken route, although this should be super-rare
1648 // in practice, both because of how healthy channels look like, and how we pick
1649 // channels in add_entry.
1650 // Also, this can't be exploited more heavily than *announce a free path and fail
1652 cur_hop_transferred_amount_msat += extra_fees_msat;
1654 // We remember and return the extra fees on the final hop to allow accounting for
1655 // them in the path's value contribution.
1657 extra_contribution_msat = extra_fees_msat;
1659 total_fee_paid_msat += extra_fees_msat;
1660 cur_hop_fees_msat += extra_fees_msat;
1665 // Final hop is a special case: it usually has just value_msat (by design), but also
1666 // it still could overpay for the htlc_minimum_msat.
1667 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1669 // Propagate updated fees for the use of the channels to one hop back, where they
1670 // will be actually paid (fee_msat). The last hop is handled above separately.
1671 cur_hop.fee_msat = cur_hop_fees_msat;
1674 // Fee for the use of the current hop which will be deducted on the previous hop.
1675 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1676 // this channel is free for us.
1678 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1679 cur_hop.hop_use_fee_msat = new_fee;
1680 total_fee_paid_msat += new_fee;
1682 // It should not be possible because this function is called only to reduce the
1683 // value. In that case, compute_fee was already called with the same fees for
1684 // larger amount and there was no overflow.
1689 value_msat + extra_contribution_msat
1694 /// Calculate the fees required to route the given amount over a channel with the given fees.
1695 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1696 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1697 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1701 /// Calculate the fees required to route the given amount over a channel with the given fees,
1702 /// saturating to [`u64::max_value`].
1703 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1704 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1705 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1706 .saturating_add(channel_fees.base_msat as u64)
1709 /// The default `features` we assume for a node in a route, when no `features` are known about that
1712 /// Default features are:
1713 /// * variable_length_onion_optional
1714 fn default_node_features() -> NodeFeatures {
1715 let mut features = NodeFeatures::empty();
1716 features.set_variable_length_onion_optional();
1720 struct LoggedPayeePubkey(Option<PublicKey>);
1721 impl fmt::Display for LoggedPayeePubkey {
1722 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1725 "payee node id ".fmt(f)?;
1729 "blinded payee".fmt(f)
1735 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1736 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1737 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1739 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1740 "blinded route hint with introduction node ".fmt(f)?;
1741 match &hint.1.introduction_node {
1742 IntroductionNode::NodeId(pubkey) => write!(f, "id {}", pubkey)?,
1743 IntroductionNode::DirectedShortChannelId(direction, scid) => {
1745 Direction::NodeOne => {
1746 write!(f, "one on channel with SCID {}", scid)?;
1748 Direction::NodeTwo => {
1749 write!(f, "two on channel with SCID {}", scid)?;
1754 " and blinding point ".fmt(f)?;
1755 hint.1.blinding_point.fmt(f)
1757 CandidateRouteHop::FirstHop(_) => {
1758 "first hop with SCID ".fmt(f)?;
1759 self.0.short_channel_id().unwrap().fmt(f)
1761 CandidateRouteHop::PrivateHop(_) => {
1762 "route hint with SCID ".fmt(f)?;
1763 self.0.short_channel_id().unwrap().fmt(f)
1767 self.0.short_channel_id().unwrap().fmt(f)
1774 fn sort_first_hop_channels(
1775 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1776 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1778 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1779 // most like to use.
1781 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1782 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1785 // Second, because simply always sorting in descending order would always use our largest
1786 // available outbound capacity, needlessly fragmenting our available channel capacities,
1787 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1788 // which have enough, but not too much, capacity for the payment.
1790 // Available outbound balances factor in liquidity already reserved for previously found paths.
1791 channels.sort_unstable_by(|chan_a, chan_b| {
1792 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1793 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1794 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1795 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1796 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1797 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1798 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1799 // Sort in descending order
1800 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1802 // Sort in ascending order
1803 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1808 /// Finds a route from us (payer) to the given target node (payee).
1810 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1811 /// in the given [`RouteParameters::payment_params`].
1812 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1814 /// Private routing paths between a public node and the target may be included in the `payee` field
1815 /// of [`RouteParameters::payment_params`].
1817 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1818 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1819 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1821 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1822 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1823 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1827 /// Panics if first_hops contains channels without `short_channel_id`s;
1828 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1830 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1831 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1832 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1833 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1834 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1835 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1836 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1837 ) -> Result<Route, LightningError>
1838 where L::Target: Logger, GL::Target: Logger {
1839 let graph_lock = network_graph.read_only();
1840 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1841 scorer, score_params, random_seed_bytes)?;
1842 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1846 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1847 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1848 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1849 _random_seed_bytes: &[u8; 32]
1850 ) -> Result<Route, LightningError>
1851 where L::Target: Logger {
1853 let payment_params = &route_params.payment_params;
1854 let final_value_msat = route_params.final_value_msat;
1855 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1856 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1857 // so use a dummy id for this in the blinded case.
1858 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1859 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1860 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1861 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1862 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1864 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1865 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1867 if our_node_id == maybe_dummy_payee_node_id {
1868 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1871 if final_value_msat > MAX_VALUE_MSAT {
1872 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1875 if final_value_msat == 0 {
1876 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1879 let introduction_node_id_cache = payment_params.payee.blinded_route_hints().iter()
1880 .map(|(_, path)| path.public_introduction_node_id(network_graph))
1881 .collect::<Vec<_>>();
1882 match &payment_params.payee {
1883 Payee::Clear { route_hints, node_id, .. } => {
1884 for route in route_hints.iter() {
1885 for hop in &route.0 {
1886 if hop.src_node_id == *node_id {
1887 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1892 Payee::Blinded { route_hints, .. } => {
1893 if introduction_node_id_cache.iter().all(|introduction_node_id| *introduction_node_id == Some(&our_node_id)) {
1894 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});
1896 for ((_, blinded_path), introduction_node_id) in route_hints.iter().zip(introduction_node_id_cache.iter()) {
1897 if blinded_path.blinded_hops.len() == 0 {
1898 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1899 } else if *introduction_node_id == Some(&our_node_id) {
1900 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1901 } else if blinded_path.blinded_hops.len() == 1 &&
1903 .iter().zip(introduction_node_id_cache.iter())
1904 .filter(|((_, p), _)| p.blinded_hops.len() == 1)
1905 .any(|(_, p_introduction_node_id)| p_introduction_node_id != introduction_node_id)
1907 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1912 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1913 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1914 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});
1917 // The general routing idea is the following:
1918 // 1. Fill first/last hops communicated by the caller.
1919 // 2. Attempt to construct a path from payer to payee for transferring
1920 // any ~sufficient (described later) value.
1921 // If succeed, remember which channels were used and how much liquidity they have available,
1922 // so that future paths don't rely on the same liquidity.
1923 // 3. Proceed to the next step if:
1924 // - we hit the recommended target value;
1925 // - OR if we could not construct a new path. Any next attempt will fail too.
1926 // Otherwise, repeat step 2.
1927 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1928 // (not recommended value).
1929 // 5. If yes, proceed. If not, fail routing.
1930 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1931 // transferred up to the transfer target value.
1932 // 7. Reduce the value of the last path until we are sending only the target value.
1933 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1934 // them so that we're not sending two HTLCs along the same path.
1936 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1937 // distance from the payee
1939 // We are not a faithful Dijkstra's implementation because we can change values which impact
1940 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1941 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1942 // the value we are currently attempting to send over a path, we simply reduce the value being
1943 // sent along the path for any hops after that channel. This may imply that later fees (which
1944 // we've already tabulated) are lower because a smaller value is passing through the channels
1945 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1946 // channels which were selected earlier (and which may still be used for other paths without a
1947 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1950 // One potentially problematic case for this algorithm would be if there are many
1951 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1952 // graph walking), we may never find a path which is not liquidity-limited and has lower
1953 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1954 // Because we only consider paths with at least 5% of the total value being sent, the damage
1955 // from such a case should be limited, however this could be further reduced in the future by
1956 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1957 // limits for the purposes of fee calculation.
1959 // Alternatively, we could store more detailed path information in the heap (targets, below)
1960 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1961 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1962 // and practically (as we would need to store dynamically-allocated path information in heap
1963 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1964 // results of such an algorithm would likely be biased towards lower-value paths.
1966 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1967 // outside of our current search value, running a path search more times to gather candidate
1968 // paths at different values. While this may be acceptable, further path searches may increase
1969 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1970 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1971 // the same time, remaining generic across different payment values.
1973 let network_channels = network_graph.channels();
1974 let network_nodes = network_graph.nodes();
1976 if payment_params.max_path_count == 0 {
1977 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1980 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1981 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1983 let allow_mpp = if payment_params.max_path_count == 1 {
1985 } else if payment_params.payee.supports_basic_mpp() {
1987 } else if let Some(payee) = payee_node_id_opt {
1988 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1989 |info| info.features.supports_basic_mpp()))
1992 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1994 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph with a fee limit of {} msat",
1995 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
1996 if allow_mpp { "with" } else { "without" },
1997 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " },
1998 max_total_routing_fee_msat);
2001 // Prepare the data we'll use for payee-to-payer search by
2002 // inserting first hops suggested by the caller as targets.
2003 // Our search will then attempt to reach them while traversing from the payee node.
2004 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
2005 hash_map_with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
2006 if let Some(hops) = first_hops {
2008 if chan.get_outbound_payment_scid().is_none() {
2009 panic!("first_hops should be filled in with usable channels, not pending ones");
2011 if chan.counterparty.node_id == *our_node_pubkey {
2012 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
2015 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
2016 .or_insert(Vec::new())
2019 if first_hop_targets.is_empty() {
2020 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
2024 let mut private_hop_key_cache = hash_map_with_capacity(
2025 payment_params.payee.unblinded_route_hints().iter().map(|path| path.0.len()).sum()
2028 // Because we store references to private hop node_ids in `dist`, below, we need them to exist
2029 // (as `NodeId`, not `PublicKey`) for the lifetime of `dist`. Thus, we calculate all the keys
2030 // we'll need here and simply fetch them when routing.
2031 private_hop_key_cache.insert(maybe_dummy_payee_pk, NodeId::from_pubkey(&maybe_dummy_payee_pk));
2032 for route in payment_params.payee.unblinded_route_hints().iter() {
2033 for hop in route.0.iter() {
2034 private_hop_key_cache.insert(hop.src_node_id, NodeId::from_pubkey(&hop.src_node_id));
2038 // The main heap containing all candidate next-hops sorted by their score (max(fee,
2039 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
2040 // adding duplicate entries when we find a better path to a given node.
2041 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
2043 // Map from node_id to information about the best current path to that node, including feerate
2045 let mut dist: HashMap<NodeId, PathBuildingHop> = hash_map_with_capacity(network_nodes.len());
2047 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
2048 // indicating that we may wish to try again with a higher value, potentially paying to meet an
2049 // htlc_minimum with extra fees while still finding a cheaper path.
2050 let mut hit_minimum_limit;
2052 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
2053 // We start with a path_value of the exact amount we want, and if that generates a route we may
2054 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
2055 // amount we want in total across paths, selecting the best subset at the end.
2056 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
2057 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
2058 let mut path_value_msat = final_value_msat;
2060 // Routing Fragmentation Mitigation heuristic:
2062 // Routing fragmentation across many payment paths increases the overall routing
2063 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
2064 // Taking too many smaller paths also increases the chance of payment failure.
2065 // Thus to avoid this effect, we require from our collected links to provide
2066 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
2067 // This requirement is currently set to be 1/max_path_count of the payment
2068 // value to ensure we only ever return routes that do not violate this limit.
2069 let minimal_value_contribution_msat: u64 = if allow_mpp {
2070 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
2075 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
2076 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
2077 // drop the requirement by setting this to 0.
2078 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
2080 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
2081 // determine if the channel can be used by additional MPP paths or to inform path finding
2082 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
2083 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
2085 let mut used_liquidities: HashMap<CandidateHopId, u64> =
2086 hash_map_with_capacity(network_nodes.len());
2088 // Keeping track of how much value we already collected across other paths. Helps to decide
2089 // when we want to stop looking for new paths.
2090 let mut already_collected_value_msat = 0;
2092 for (_, channels) in first_hop_targets.iter_mut() {
2093 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
2097 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
2098 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
2100 // Remember how many candidates we ignored to allow for some logging afterwards.
2101 let mut num_ignored_value_contribution: u32 = 0;
2102 let mut num_ignored_path_length_limit: u32 = 0;
2103 let mut num_ignored_cltv_delta_limit: u32 = 0;
2104 let mut num_ignored_previously_failed: u32 = 0;
2105 let mut num_ignored_total_fee_limit: u32 = 0;
2106 let mut num_ignored_avoid_overpayment: u32 = 0;
2107 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
2109 macro_rules! add_entry {
2110 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
2111 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
2112 // since that value has to be transferred over this channel.
2113 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
2114 ( $candidate: expr, $next_hops_fee_msat: expr,
2115 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
2116 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
2117 // We "return" whether we updated the path at the end, and how much we can route via
2118 // this channel, via this:
2119 let mut hop_contribution_amt_msat = None;
2120 // Channels to self should not be used. This is more of belt-and-suspenders, because in
2121 // practice these cases should be caught earlier:
2122 // - for regular channels at channel announcement (TODO)
2123 // - for first and last hops early in get_route
2124 let src_node_id = $candidate.source();
2125 if Some(src_node_id) != $candidate.target() {
2126 let scid_opt = $candidate.short_channel_id();
2127 let effective_capacity = $candidate.effective_capacity();
2128 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
2130 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
2131 // It may be misleading because we might later choose to reduce the value transferred
2132 // over these channels, and the channel which was insufficient might become sufficient.
2133 // Worst case: we drop a good channel here because it can't cover the high following
2134 // fees caused by one expensive channel, but then this channel could have been used
2135 // if the amount being transferred over this path is lower.
2136 // We do this for now, but this is a subject for removal.
2137 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
2138 let used_liquidity_msat = used_liquidities
2139 .get(&$candidate.id())
2140 .map_or(0, |used_liquidity_msat| {
2141 available_value_contribution_msat = available_value_contribution_msat
2142 .saturating_sub(*used_liquidity_msat);
2143 *used_liquidity_msat
2146 // Verify the liquidity offered by this channel complies to the minimal contribution.
2147 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
2148 // Do not consider candidate hops that would exceed the maximum path length.
2149 let path_length_to_node = $next_hops_path_length + 1;
2150 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
2152 // Do not consider candidates that exceed the maximum total cltv expiry limit.
2153 // In order to already account for some of the privacy enhancing random CLTV
2154 // expiry delta offset we add on top later, we subtract a rough estimate
2155 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
2156 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
2157 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
2158 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
2159 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
2160 .saturating_add($candidate.cltv_expiry_delta());
2161 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
2163 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
2164 // Includes paying fees for the use of the following channels.
2165 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
2166 Some(result) => result,
2167 // Can't overflow due to how the values were computed right above.
2168 None => unreachable!(),
2170 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2171 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
2172 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
2174 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2175 let may_overpay_to_meet_path_minimum_msat =
2176 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
2177 recommended_value_msat >= $candidate.htlc_minimum_msat()) ||
2178 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
2179 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
2181 let payment_failed_on_this_channel = match scid_opt {
2182 Some(scid) => payment_params.previously_failed_channels.contains(&scid),
2183 None => match $candidate.blinded_hint_idx() {
2185 payment_params.previously_failed_blinded_path_idxs.contains(&(idx as u64))
2191 let (should_log_candidate, first_hop_details) = match $candidate {
2192 CandidateRouteHop::FirstHop(hop) => (true, Some(hop.details)),
2193 CandidateRouteHop::PrivateHop(_) => (true, None),
2194 CandidateRouteHop::Blinded(_) => (true, None),
2195 CandidateRouteHop::OneHopBlinded(_) => (true, None),
2199 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
2200 // bother considering this channel. If retrying with recommended_value_msat may
2201 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
2202 // around again with a higher amount.
2203 if !contributes_sufficient_value {
2204 if should_log_candidate {
2205 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
2207 if let Some(details) = first_hop_details {
2209 "First hop candidate next_outbound_htlc_limit_msat: {}",
2210 details.next_outbound_htlc_limit_msat,
2214 num_ignored_value_contribution += 1;
2215 } else if exceeds_max_path_length {
2216 if should_log_candidate {
2217 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
2219 num_ignored_path_length_limit += 1;
2220 } else if exceeds_cltv_delta_limit {
2221 if should_log_candidate {
2222 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
2224 if let Some(_) = first_hop_details {
2226 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
2227 hop_total_cltv_delta,
2228 max_total_cltv_expiry_delta,
2232 num_ignored_cltv_delta_limit += 1;
2233 } else if payment_failed_on_this_channel {
2234 if should_log_candidate {
2235 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
2237 num_ignored_previously_failed += 1;
2238 } else if may_overpay_to_meet_path_minimum_msat {
2239 if should_log_candidate {
2241 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit.",
2242 LoggedCandidateHop(&$candidate));
2244 if let Some(details) = first_hop_details {
2246 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2247 details.next_outbound_htlc_minimum_msat,
2251 num_ignored_avoid_overpayment += 1;
2252 hit_minimum_limit = true;
2253 } else if over_path_minimum_msat {
2254 // Note that low contribution here (limited by available_liquidity_msat)
2255 // might violate htlc_minimum_msat on the hops which are next along the
2256 // payment path (upstream to the payee). To avoid that, we recompute
2257 // path fees knowing the final path contribution after constructing it.
2258 let curr_min = cmp::max(
2259 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
2261 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
2262 .saturating_add(curr_min);
2263 let hm_entry = dist.entry(src_node_id);
2264 let old_entry = hm_entry.or_insert_with(|| {
2265 // If there was previously no known way to access the source node
2266 // (recall it goes payee-to-payer) of short_channel_id, first add a
2267 // semi-dummy record just to compute the fees to reach the source node.
2268 // This will affect our decision on selecting short_channel_id
2269 // as a way to reach the $candidate.target() node.
2271 candidate: $candidate.clone(),
2273 next_hops_fee_msat: u64::max_value(),
2274 hop_use_fee_msat: u64::max_value(),
2275 total_fee_msat: u64::max_value(),
2276 path_htlc_minimum_msat,
2277 path_penalty_msat: u64::max_value(),
2278 was_processed: false,
2279 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2280 value_contribution_msat,
2284 #[allow(unused_mut)] // We only use the mut in cfg(test)
2285 let mut should_process = !old_entry.was_processed;
2286 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2288 // In test/fuzzing builds, we do extra checks to make sure the skipping
2289 // of already-seen nodes only happens in cases we expect (see below).
2290 if !should_process { should_process = true; }
2294 let mut hop_use_fee_msat = 0;
2295 let mut total_fee_msat: u64 = $next_hops_fee_msat;
2297 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2298 // will have the same effective-fee
2299 if src_node_id != our_node_id {
2300 // Note that `u64::max_value` means we'll always fail the
2301 // `old_entry.total_fee_msat > total_fee_msat` check below
2302 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
2303 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2306 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2307 if total_fee_msat > max_total_routing_fee_msat {
2308 if should_log_candidate {
2309 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2311 if let Some(_) = first_hop_details {
2313 "First hop candidate routing fee: {}. Limit: {}",
2315 max_total_routing_fee_msat,
2319 num_ignored_total_fee_limit += 1;
2321 let channel_usage = ChannelUsage {
2322 amount_msat: amount_to_transfer_over_msat,
2323 inflight_htlc_msat: used_liquidity_msat,
2326 let channel_penalty_msat =
2327 scorer.channel_penalty_msat($candidate,
2330 let path_penalty_msat = $next_hops_path_penalty_msat
2331 .saturating_add(channel_penalty_msat);
2333 // Update the way of reaching $candidate.source()
2334 // with the given short_channel_id (from $candidate.target()),
2335 // if this way is cheaper than the already known
2336 // (considering the cost to "reach" this channel from the route destination,
2337 // the cost of using this channel,
2338 // and the cost of routing to the source node of this channel).
2339 // Also, consider that htlc_minimum_msat_difference, because we might end up
2340 // paying it. Consider the following exploit:
2341 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2342 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2343 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2344 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2346 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2347 // but it may require additional tracking - we don't want to double-count
2348 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2349 // can't use something that may decrease on future hops.
2350 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2351 .saturating_add(old_entry.path_penalty_msat);
2352 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2353 .saturating_add(path_penalty_msat);
2355 if !old_entry.was_processed && new_cost < old_cost {
2356 let new_graph_node = RouteGraphNode {
2357 node_id: src_node_id,
2358 score: cmp::max(total_fee_msat, path_htlc_minimum_msat).saturating_add(path_penalty_msat),
2359 total_cltv_delta: hop_total_cltv_delta,
2360 value_contribution_msat,
2361 path_length_to_node,
2363 targets.push(new_graph_node);
2364 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2365 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2366 old_entry.total_fee_msat = total_fee_msat;
2367 old_entry.candidate = $candidate.clone();
2368 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2369 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2370 old_entry.path_penalty_msat = path_penalty_msat;
2371 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2373 old_entry.value_contribution_msat = value_contribution_msat;
2375 hop_contribution_amt_msat = Some(value_contribution_msat);
2376 } else if old_entry.was_processed && new_cost < old_cost {
2377 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2379 // If we're skipping processing a node which was previously
2380 // processed even though we found another path to it with a
2381 // cheaper fee, check that it was because the second path we
2382 // found (which we are processing now) has a lower value
2383 // contribution due to an HTLC minimum limit.
2385 // e.g. take a graph with two paths from node 1 to node 2, one
2386 // through channel A, and one through channel B. Channel A and
2387 // B are both in the to-process heap, with their scores set by
2388 // a higher htlc_minimum than fee.
2389 // Channel A is processed first, and the channels onwards from
2390 // node 1 are added to the to-process heap. Thereafter, we pop
2391 // Channel B off of the heap, note that it has a much more
2392 // restrictive htlc_maximum_msat, and recalculate the fees for
2393 // all of node 1's channels using the new, reduced, amount.
2395 // This would be bogus - we'd be selecting a higher-fee path
2396 // with a lower htlc_maximum_msat instead of the one we'd
2397 // already decided to use.
2398 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2400 value_contribution_msat + path_penalty_msat <
2401 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2408 if should_log_candidate {
2410 "Ignoring {} due to its htlc_minimum_msat limit.",
2411 LoggedCandidateHop(&$candidate));
2413 if let Some(details) = first_hop_details {
2415 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2416 details.next_outbound_htlc_minimum_msat,
2420 num_ignored_htlc_minimum_msat_limit += 1;
2424 hop_contribution_amt_msat
2428 let default_node_features = default_node_features();
2430 // Find ways (channels with destination) to reach a given node and store them
2431 // in the corresponding data structures (routing graph etc).
2432 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2433 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2434 // This data can later be helpful to optimize routing (pay lower fees).
2435 macro_rules! add_entries_to_cheapest_to_target_node {
2436 ( $node: expr, $node_id: expr, $next_hops_value_contribution: expr,
2437 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2438 let fee_to_target_msat;
2439 let next_hops_path_htlc_minimum_msat;
2440 let next_hops_path_penalty_msat;
2441 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
2442 let was_processed = elem.was_processed;
2443 elem.was_processed = true;
2444 fee_to_target_msat = elem.total_fee_msat;
2445 next_hops_path_htlc_minimum_msat = elem.path_htlc_minimum_msat;
2446 next_hops_path_penalty_msat = elem.path_penalty_msat;
2449 // Entries are added to dist in add_entry!() when there is a channel from a node.
2450 // Because there are no channels from payee, it will not have a dist entry at this point.
2451 // If we're processing any other node, it is always be the result of a channel from it.
2452 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2453 fee_to_target_msat = 0;
2454 next_hops_path_htlc_minimum_msat = 0;
2455 next_hops_path_penalty_msat = 0;
2460 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
2461 for details in first_channels {
2462 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2463 details, payer_node_id: &our_node_id,
2465 add_entry!(&candidate, fee_to_target_msat,
2466 $next_hops_value_contribution,
2467 next_hops_path_htlc_minimum_msat, next_hops_path_penalty_msat,
2468 $next_hops_cltv_delta, $next_hops_path_length);
2472 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2475 &default_node_features
2478 if !features.requires_unknown_bits() {
2479 for chan_id in $node.channels.iter() {
2480 let chan = network_channels.get(chan_id).unwrap();
2481 if !chan.features.requires_unknown_bits() {
2482 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2483 if first_hops.is_none() || *source != our_node_id {
2484 if directed_channel.direction().enabled {
2485 let candidate = CandidateRouteHop::PublicHop(PublicHopCandidate {
2486 info: directed_channel,
2487 short_channel_id: *chan_id,
2489 add_entry!(&candidate,
2491 $next_hops_value_contribution,
2492 next_hops_path_htlc_minimum_msat,
2493 next_hops_path_penalty_msat,
2494 $next_hops_cltv_delta, $next_hops_path_length);
2505 let mut payment_paths = Vec::<PaymentPath>::new();
2507 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2508 'paths_collection: loop {
2509 // For every new path, start from scratch, except for used_liquidities, which
2510 // helps to avoid reusing previously selected paths in future iterations.
2513 hit_minimum_limit = false;
2515 // If first hop is a private channel and the only way to reach the payee, this is the only
2516 // place where it could be added.
2517 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2518 for details in first_channels {
2519 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2520 details, payer_node_id: &our_node_id,
2522 let added = add_entry!(&candidate, 0, path_value_msat,
2523 0, 0u64, 0, 0).is_some();
2524 log_trace!(logger, "{} direct route to payee via {}",
2525 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2529 // Add the payee as a target, so that the payee-to-payer
2530 // search algorithm knows what to start with.
2531 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2532 // The payee is not in our network graph, so nothing to add here.
2533 // There is still a chance of reaching them via last_hops though,
2534 // so don't yet fail the payment here.
2535 // If not, targets.pop() will not even let us enter the loop in step 2.
2538 add_entries_to_cheapest_to_target_node!(node, payee, path_value_msat, 0, 0);
2543 // If a caller provided us with last hops, add them to routing targets. Since this happens
2544 // earlier than general path finding, they will be somewhat prioritized, although currently
2545 // it matters only if the fees are exactly the same.
2546 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2547 // Only add the hops in this route to our candidate set if either
2548 // we have a direct channel to the first hop or the first hop is
2549 // in the regular network graph.
2550 let source_node_id = match introduction_node_id_cache[hint_idx] {
2551 Some(node_id) => node_id,
2552 None => match &hint.1.introduction_node {
2553 IntroductionNode::NodeId(pubkey) => {
2554 let node_id = NodeId::from_pubkey(&pubkey);
2555 match first_hop_targets.get_key_value(&node_id).map(|(key, _)| key) {
2556 Some(node_id) => node_id,
2560 IntroductionNode::DirectedShortChannelId(direction, scid) => {
2561 let first_hop = first_hop_targets.iter().find(|(_, channels)|
2564 .any(|details| Some(*scid) == details.get_outbound_payment_scid())
2567 Some((counterparty_node_id, _)) => {
2568 direction.select_node_id(&our_node_id, counterparty_node_id)
2575 if our_node_id == *source_node_id { continue }
2576 let candidate = if hint.1.blinded_hops.len() == 1 {
2577 CandidateRouteHop::OneHopBlinded(
2578 OneHopBlindedPathCandidate { source_node_id, hint, hint_idx }
2581 CandidateRouteHop::Blinded(BlindedPathCandidate { source_node_id, hint, hint_idx })
2583 let mut path_contribution_msat = path_value_msat;
2584 if let Some(hop_used_msat) = add_entry!(&candidate,
2585 0, path_contribution_msat, 0, 0_u64, 0, 0)
2587 path_contribution_msat = hop_used_msat;
2589 if let Some(first_channels) = first_hop_targets.get(source_node_id) {
2590 let mut first_channels = first_channels.clone();
2591 sort_first_hop_channels(
2592 &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2594 for details in first_channels {
2595 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2596 details, payer_node_id: &our_node_id,
2598 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2602 let path_min = candidate.htlc_minimum_msat().saturating_add(
2603 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2604 add_entry!(&first_hop_candidate, blinded_path_fee,
2605 path_contribution_msat, path_min, 0_u64, candidate.cltv_expiry_delta(),
2606 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2610 for route in payment_params.payee.unblinded_route_hints().iter()
2611 .filter(|route| !route.0.is_empty())
2613 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2614 let first_hop_src_is_reachable =
2615 // Only add the hops in this route to our candidate set if either we are part of
2616 // the first hop, we have a direct channel to the first hop, or the first hop is in
2617 // the regular network graph.
2618 our_node_id == first_hop_src_id ||
2619 first_hop_targets.get(&first_hop_src_id).is_some() ||
2620 network_nodes.get(&first_hop_src_id).is_some();
2621 if first_hop_src_is_reachable {
2622 // We start building the path from reverse, i.e., from payee
2623 // to the first RouteHintHop in the path.
2624 let hop_iter = route.0.iter().rev();
2625 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2626 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2627 let mut hop_used = true;
2628 let mut aggregate_next_hops_fee_msat: u64 = 0;
2629 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2630 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2631 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2632 let mut aggregate_next_hops_path_length: u8 = 0;
2633 let mut aggregate_path_contribution_msat = path_value_msat;
2635 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2636 let target = private_hop_key_cache.get(prev_hop_id).unwrap();
2638 if let Some(first_channels) = first_hop_targets.get(target) {
2639 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2640 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2641 hop.short_channel_id);
2646 let candidate = network_channels
2647 .get(&hop.short_channel_id)
2648 .and_then(|channel| channel.as_directed_to(target))
2649 .map(|(info, _)| CandidateRouteHop::PublicHop(PublicHopCandidate {
2651 short_channel_id: hop.short_channel_id,
2653 .unwrap_or_else(|| CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: hop, target_node_id: target }));
2655 if let Some(hop_used_msat) = add_entry!(&candidate,
2656 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2657 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2658 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2660 aggregate_path_contribution_msat = hop_used_msat;
2662 // If this hop was not used then there is no use checking the preceding
2663 // hops in the RouteHint. We can break by just searching for a direct
2664 // channel between last checked hop and first_hop_targets.
2668 let used_liquidity_msat = used_liquidities
2669 .get(&candidate.id()).copied()
2671 let channel_usage = ChannelUsage {
2672 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2673 inflight_htlc_msat: used_liquidity_msat,
2674 effective_capacity: candidate.effective_capacity(),
2676 let channel_penalty_msat = scorer.channel_penalty_msat(
2677 &candidate, channel_usage, score_params
2679 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2680 .saturating_add(channel_penalty_msat);
2682 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2683 .saturating_add(hop.cltv_expiry_delta as u32);
2685 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2688 // Searching for a direct channel between last checked hop and first_hop_targets
2689 if let Some(first_channels) = first_hop_targets.get(target) {
2690 let mut first_channels = first_channels.clone();
2691 sort_first_hop_channels(
2692 &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2694 for details in first_channels {
2695 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2696 details, payer_node_id: &our_node_id,
2698 add_entry!(&first_hop_candidate,
2699 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2700 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2701 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2709 // In the next values of the iterator, the aggregate fees already reflects
2710 // the sum of value sent from payer (final_value_msat) and routing fees
2711 // for the last node in the RouteHint. We need to just add the fees to
2712 // route through the current node so that the preceding node (next iteration)
2714 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2715 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2716 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2718 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2719 // this route hint's source node to forward said min over this channel.
2720 aggregate_next_hops_path_htlc_minimum_msat = {
2721 let curr_htlc_min = cmp::max(
2722 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2724 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2725 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2728 if idx == route.0.len() - 1 {
2729 // The last hop in this iterator is the first hop in
2730 // overall RouteHint.
2731 // If this hop connects to a node with which we have a direct channel,
2732 // ignore the network graph and, if the last hop was added, add our
2733 // direct channel to the candidate set.
2735 // Note that we *must* check if the last hop was added as `add_entry`
2736 // always assumes that the third argument is a node to which we have a
2738 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
2739 let mut first_channels = first_channels.clone();
2740 sort_first_hop_channels(
2741 &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2743 for details in first_channels {
2744 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2745 details, payer_node_id: &our_node_id,
2747 add_entry!(&first_hop_candidate,
2748 aggregate_next_hops_fee_msat,
2749 aggregate_path_contribution_msat,
2750 aggregate_next_hops_path_htlc_minimum_msat,
2751 aggregate_next_hops_path_penalty_msat,
2752 aggregate_next_hops_cltv_delta,
2753 aggregate_next_hops_path_length);
2761 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2763 // At this point, targets are filled with the data from first and
2764 // last hops communicated by the caller, and the payment receiver.
2765 let mut found_new_path = false;
2768 // If this loop terminates due the exhaustion of targets, two situations are possible:
2769 // - not enough outgoing liquidity:
2770 // 0 < already_collected_value_msat < final_value_msat
2771 // - enough outgoing liquidity:
2772 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2773 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2774 // paths_collection will be stopped because found_new_path==false.
2775 // This is not necessarily a routing failure.
2776 'path_construction: while let Some(RouteGraphNode { node_id, total_cltv_delta, mut value_contribution_msat, path_length_to_node, .. }) = targets.pop() {
2778 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2779 // traversing the graph and arrange the path out of what we found.
2780 if node_id == our_node_id {
2781 let mut new_entry = dist.remove(&our_node_id).unwrap();
2782 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2785 let mut features_set = false;
2786 let target = ordered_hops.last().unwrap().0.candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2787 if let Some(first_channels) = first_hop_targets.get(&target) {
2788 for details in first_channels {
2789 if let CandidateRouteHop::FirstHop(FirstHopCandidate { details: last_hop_details, .. })
2790 = ordered_hops.last().unwrap().0.candidate
2792 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2793 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2794 features_set = true;
2801 if let Some(node) = network_nodes.get(&target) {
2802 if let Some(node_info) = node.announcement_info.as_ref() {
2803 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2805 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2808 // We can fill in features for everything except hops which were
2809 // provided via the invoice we're paying. We could guess based on the
2810 // recipient's features but for now we simply avoid guessing at all.
2814 // Means we successfully traversed from the payer to the payee, now
2815 // save this path for the payment route. Also, update the liquidity
2816 // remaining on the used hops, so that we take them into account
2817 // while looking for more paths.
2818 if target == maybe_dummy_payee_node_id {
2822 new_entry = match dist.remove(&target) {
2823 Some(payment_hop) => payment_hop,
2824 // We can't arrive at None because, if we ever add an entry to targets,
2825 // we also fill in the entry in dist (see add_entry!).
2826 None => unreachable!(),
2828 // We "propagate" the fees one hop backward (topologically) here,
2829 // so that fees paid for a HTLC forwarding on the current channel are
2830 // associated with the previous channel (where they will be subtracted).
2831 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2832 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2834 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2835 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2837 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2838 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2840 let mut payment_path = PaymentPath {hops: ordered_hops};
2842 // We could have possibly constructed a slightly inconsistent path: since we reduce
2843 // value being transferred along the way, we could have violated htlc_minimum_msat
2844 // on some channels we already passed (assuming dest->source direction). Here, we
2845 // recompute the fees again, so that if that's the case, we match the currently
2846 // underpaid htlc_minimum_msat with fees.
2847 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2848 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2849 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2851 // Since a path allows to transfer as much value as
2852 // the smallest channel it has ("bottleneck"), we should recompute
2853 // the fees so sender HTLC don't overpay fees when traversing
2854 // larger channels than the bottleneck. This may happen because
2855 // when we were selecting those channels we were not aware how much value
2856 // this path will transfer, and the relative fee for them
2857 // might have been computed considering a larger value.
2858 // Remember that we used these channels so that we don't rely
2859 // on the same liquidity in future paths.
2860 let mut prevented_redundant_path_selection = false;
2861 for (hop, _) in payment_path.hops.iter() {
2862 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2863 let used_liquidity_msat = used_liquidities
2864 .entry(hop.candidate.id())
2865 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2866 .or_insert(spent_on_hop_msat);
2867 let hop_capacity = hop.candidate.effective_capacity();
2868 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2869 if *used_liquidity_msat == hop_max_msat {
2870 // If this path used all of this channel's available liquidity, we know
2871 // this path will not be selected again in the next loop iteration.
2872 prevented_redundant_path_selection = true;
2874 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2876 if !prevented_redundant_path_selection {
2877 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2878 // we'll probably end up picking the same path again on the next iteration.
2879 // Decrease the available liquidity of a hop in the middle of the path.
2880 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2881 let exhausted = u64::max_value();
2883 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2884 LoggedCandidateHop(victim_candidate));
2885 if let Some(scid) = victim_candidate.short_channel_id() {
2886 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2887 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2891 // Track the total amount all our collected paths allow to send so that we know
2892 // when to stop looking for more paths
2893 already_collected_value_msat += value_contribution_msat;
2895 payment_paths.push(payment_path);
2896 found_new_path = true;
2897 break 'path_construction;
2900 // If we found a path back to the payee, we shouldn't try to process it again. This is
2901 // the equivalent of the `elem.was_processed` check in
2902 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2903 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2905 // Otherwise, since the current target node is not us,
2906 // keep "unrolling" the payment graph from payee to payer by
2907 // finding a way to reach the current target from the payer side.
2908 match network_nodes.get(&node_id) {
2911 add_entries_to_cheapest_to_target_node!(node, node_id,
2912 value_contribution_msat,
2913 total_cltv_delta, path_length_to_node);
2919 if !found_new_path && channel_saturation_pow_half != 0 {
2920 channel_saturation_pow_half = 0;
2921 continue 'paths_collection;
2923 // If we don't support MPP, no use trying to gather more value ever.
2924 break 'paths_collection;
2928 // Stop either when the recommended value is reached or if no new path was found in this
2930 // In the latter case, making another path finding attempt won't help,
2931 // because we deterministically terminated the search due to low liquidity.
2932 if !found_new_path && channel_saturation_pow_half != 0 {
2933 channel_saturation_pow_half = 0;
2934 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2935 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
2936 path_value_msat = recommended_value_msat;
2937 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2938 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2939 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2940 break 'paths_collection;
2941 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2942 // Further, if this was our first walk of the graph, and we weren't limited by an
2943 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2944 // limited by an htlc_minimum_msat value, find another path with a higher value,
2945 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2946 // still keeping a lower total fee than this path.
2947 if !hit_minimum_limit {
2948 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2949 break 'paths_collection;
2951 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.");
2952 path_value_msat = recommended_value_msat;
2956 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2957 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
2958 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
2959 num_ignored_total_fee_limit;
2960 if num_ignored_total > 0 {
2962 "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.",
2963 num_ignored_value_contribution, num_ignored_path_length_limit,
2964 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
2965 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
2966 num_ignored_total_fee_limit, num_ignored_total);
2970 if payment_paths.len() == 0 {
2971 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2974 if already_collected_value_msat < final_value_msat {
2975 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2979 let mut selected_route = payment_paths;
2981 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2982 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2984 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2985 // the value they contribute towards the payment amount.
2986 // We sort in descending order as we will remove from the front in `retain`, next.
2987 selected_route.sort_unstable_by(|a, b|
2988 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2989 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2992 // We should make sure that at least 1 path left.
2993 let mut paths_left = selected_route.len();
2994 selected_route.retain(|path| {
2995 if paths_left == 1 {
2998 let path_value_msat = path.get_value_msat();
2999 if path_value_msat <= overpaid_value_msat {
3000 overpaid_value_msat -= path_value_msat;
3006 debug_assert!(selected_route.len() > 0);
3008 if overpaid_value_msat != 0 {
3010 // Now, subtract the remaining overpaid value from the most-expensive path.
3011 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
3012 // so that the sender pays less fees overall. And also htlc_minimum_msat.
3013 selected_route.sort_unstable_by(|a, b| {
3014 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3015 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3016 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
3018 let expensive_payment_path = selected_route.first_mut().unwrap();
3020 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
3021 // can't go negative.
3022 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
3023 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
3027 // Sort by the path itself and combine redundant paths.
3028 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
3029 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
3031 selected_route.sort_unstable_by_key(|path| {
3032 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
3033 debug_assert!(path.hops.len() <= key.len());
3034 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
3039 for idx in 0..(selected_route.len() - 1) {
3040 if idx + 1 >= selected_route.len() { break; }
3041 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
3042 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
3043 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
3044 selected_route[idx].update_value_and_recompute_fees(new_value);
3045 selected_route.remove(idx + 1);
3049 let mut paths = Vec::new();
3050 for payment_path in selected_route {
3051 let mut hops = Vec::with_capacity(payment_path.hops.len());
3052 for (hop, node_features) in payment_path.hops.iter()
3053 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
3055 let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
3056 let maybe_announced_channel = if let CandidateRouteHop::PublicHop(_) = hop.candidate {
3057 // If we sourced the hop from the graph we're sure the target node is announced.
3059 } else if let CandidateRouteHop::FirstHop(first_hop) = &hop.candidate {
3060 // If this is a first hop we also know if it's announced.
3061 first_hop.details.is_public
3063 // If we sourced it any other way, we double-check the network graph to see if
3064 // there are announced channels between the endpoints. If so, the hop might be
3065 // referring to any of the announced channels, as its `short_channel_id` might be
3066 // an alias, in which case we don't take any chances here.
3067 network_graph.node(&target).map_or(false, |hop_node|
3068 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
3069 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
3073 hops.push(RouteHop {
3074 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
3075 node_features: node_features.clone(),
3076 short_channel_id: hop.candidate.short_channel_id().unwrap(),
3077 channel_features: hop.candidate.features(),
3078 fee_msat: hop.fee_msat,
3079 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
3080 maybe_announced_channel,
3083 let mut final_cltv_delta = final_cltv_expiry_delta;
3084 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
3085 if let Some(blinded_path) = h.candidate.blinded_path() {
3086 final_cltv_delta = h.candidate.cltv_expiry_delta();
3088 hops: blinded_path.blinded_hops.clone(),
3089 blinding_point: blinded_path.blinding_point,
3090 excess_final_cltv_expiry_delta: 0,
3091 final_value_msat: h.fee_msat,
3095 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
3096 // applicable for the previous hop.
3097 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
3098 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
3101 paths.push(Path { hops, blinded_tail });
3103 // Make sure we would never create a route with more paths than we allow.
3104 debug_assert!(paths.len() <= payment_params.max_path_count.into());
3106 if let Some(node_features) = payment_params.payee.node_features() {
3107 for path in paths.iter_mut() {
3108 path.hops.last_mut().unwrap().node_features = node_features.clone();
3112 let route = Route { paths, route_params: Some(route_params.clone()) };
3114 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
3115 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
3116 if route.get_total_fees() > max_total_routing_fee_msat {
3117 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
3118 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
3122 log_info!(logger, "Got route: {}", log_route!(route));
3126 // When an adversarial intermediary node observes a payment, it may be able to infer its
3127 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
3128 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
3129 // payment path by adding a randomized 'shadow route' offset to the final hop.
3130 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
3131 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
3133 let network_channels = network_graph.channels();
3134 let network_nodes = network_graph.nodes();
3136 for path in route.paths.iter_mut() {
3137 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
3139 // Remember the last three nodes of the random walk and avoid looping back on them.
3140 // Init with the last three nodes from the actual path, if possible.
3141 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
3142 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
3143 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
3145 // Choose the last publicly known node as the starting point for the random walk.
3146 let mut cur_hop: Option<NodeId> = None;
3147 let mut path_nonce = [0u8; 12];
3148 if let Some(starting_hop) = path.hops.iter().rev()
3149 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
3150 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
3151 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
3154 // Init PRNG with the path-dependant nonce, which is static for private paths.
3155 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
3156 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
3158 // Pick a random path length in [1 .. 3]
3159 prng.process_in_place(&mut random_path_bytes);
3160 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
3162 for random_hop in 0..random_walk_length {
3163 // If we don't find a suitable offset in the public network graph, we default to
3164 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3165 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
3167 if let Some(cur_node_id) = cur_hop {
3168 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
3169 // Randomly choose the next unvisited hop.
3170 prng.process_in_place(&mut random_path_bytes);
3171 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
3172 .checked_rem(cur_node.channels.len())
3173 .and_then(|index| cur_node.channels.get(index))
3174 .and_then(|id| network_channels.get(id)) {
3175 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
3176 if !nodes_to_avoid.iter().any(|x| x == next_id) {
3177 nodes_to_avoid[random_hop] = *next_id;
3178 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
3179 cur_hop = Some(*next_id);
3186 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
3187 .checked_add(random_hop_offset)
3188 .unwrap_or(shadow_ctlv_expiry_delta_offset);
3191 // Limit the total offset to reduce the worst-case locked liquidity timevalue
3192 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
3193 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
3195 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
3196 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3197 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
3198 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
3199 max_path_offset = cmp::max(
3200 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
3201 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
3202 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
3204 // Add 'shadow' CLTV offset to the final hop
3205 if let Some(tail) = path.blinded_tail.as_mut() {
3206 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
3207 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
3209 if let Some(last_hop) = path.hops.last_mut() {
3210 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
3211 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
3216 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
3217 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
3219 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
3220 pub fn build_route_from_hops<L: Deref, GL: Deref>(
3221 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3222 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
3223 ) -> Result<Route, LightningError>
3224 where L::Target: Logger, GL::Target: Logger {
3225 let graph_lock = network_graph.read_only();
3226 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
3227 &graph_lock, logger, random_seed_bytes)?;
3228 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
3232 fn build_route_from_hops_internal<L: Deref>(
3233 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3234 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
3235 ) -> Result<Route, LightningError> where L::Target: Logger {
3238 our_node_id: NodeId,
3239 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
3242 impl ScoreLookUp for HopScorer {
3243 type ScoreParams = ();
3244 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
3245 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
3247 let mut cur_id = self.our_node_id;
3248 for i in 0..self.hop_ids.len() {
3249 if let Some(next_id) = self.hop_ids[i] {
3250 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
3262 impl<'a> Writeable for HopScorer {
3264 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
3269 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
3270 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
3273 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
3274 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
3275 for i in 0..hops.len() {
3276 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
3279 let scorer = HopScorer { our_node_id, hop_ids };
3281 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
3286 use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode};
3287 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
3288 use crate::routing::utxo::UtxoResult;
3289 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
3290 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
3291 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop, PublicHopCandidate};
3292 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
3293 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
3294 use crate::chain::transaction::OutPoint;
3295 use crate::sign::EntropySource;
3296 use crate::ln::types::ChannelId;
3297 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
3298 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
3299 use crate::ln::channelmanager;
3300 use crate::offers::invoice::BlindedPayInfo;
3301 use crate::util::config::UserConfig;
3302 use crate::util::test_utils as ln_test_utils;
3303 use crate::crypto::chacha20::ChaCha20;
3304 use crate::util::ser::{Readable, Writeable};
3306 use crate::util::ser::Writer;
3308 use bitcoin::hashes::Hash;
3309 use bitcoin::network::constants::Network;
3310 use bitcoin::blockdata::constants::ChainHash;
3311 use bitcoin::blockdata::script::Builder;
3312 use bitcoin::blockdata::opcodes;
3313 use bitcoin::blockdata::transaction::TxOut;
3314 use bitcoin::hashes::hex::FromHex;
3315 use bitcoin::secp256k1::{PublicKey,SecretKey};
3316 use bitcoin::secp256k1::Secp256k1;
3318 use crate::io::Cursor;
3319 use crate::prelude::*;
3320 use crate::sync::Arc;
3322 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3323 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
3324 channelmanager::ChannelDetails {
3325 channel_id: ChannelId::new_zero(),
3326 counterparty: channelmanager::ChannelCounterparty {
3329 unspendable_punishment_reserve: 0,
3330 forwarding_info: None,
3331 outbound_htlc_minimum_msat: None,
3332 outbound_htlc_maximum_msat: None,
3334 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3337 outbound_scid_alias: None,
3338 inbound_scid_alias: None,
3339 channel_value_satoshis: 0,
3342 outbound_capacity_msat,
3343 next_outbound_htlc_limit_msat: outbound_capacity_msat,
3344 next_outbound_htlc_minimum_msat: 0,
3345 inbound_capacity_msat: 42,
3346 unspendable_punishment_reserve: None,
3347 confirmations_required: None,
3348 confirmations: None,
3349 force_close_spend_delay: None,
3350 is_outbound: true, is_channel_ready: true,
3351 is_usable: true, is_public: true,
3352 inbound_htlc_minimum_msat: None,
3353 inbound_htlc_maximum_msat: None,
3355 feerate_sat_per_1000_weight: None,
3356 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
3357 pending_inbound_htlcs: Vec::new(),
3358 pending_outbound_htlcs: Vec::new(),
3363 fn simple_route_test() {
3364 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3365 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3366 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3367 let scorer = ln_test_utils::TestScorer::new();
3368 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3369 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3371 // Simple route to 2 via 1
3373 let route_params = RouteParameters::from_payment_params_and_value(
3374 payment_params.clone(), 0);
3375 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3376 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3377 &Default::default(), &random_seed_bytes) {
3378 assert_eq!(err, "Cannot send a payment of 0 msat");
3379 } else { panic!(); }
3381 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3382 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3383 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3384 assert_eq!(route.paths[0].hops.len(), 2);
3386 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3387 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3388 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3389 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3390 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3391 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3393 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3394 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3395 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3396 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3397 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3398 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3402 fn invalid_first_hop_test() {
3403 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3404 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3405 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3406 let scorer = ln_test_utils::TestScorer::new();
3407 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3408 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3410 // Simple route to 2 via 1
3412 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3414 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3415 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3416 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3417 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3418 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3419 } else { panic!(); }
3421 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3422 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3423 assert_eq!(route.paths[0].hops.len(), 2);
3427 fn htlc_minimum_test() {
3428 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3429 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3430 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3431 let scorer = ln_test_utils::TestScorer::new();
3432 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3433 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3435 // Simple route to 2 via 1
3437 // Disable other paths
3438 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3439 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3440 short_channel_id: 12,
3442 flags: 2, // to disable
3443 cltv_expiry_delta: 0,
3444 htlc_minimum_msat: 0,
3445 htlc_maximum_msat: MAX_VALUE_MSAT,
3447 fee_proportional_millionths: 0,
3448 excess_data: Vec::new()
3450 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3451 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3452 short_channel_id: 3,
3454 flags: 2, // to disable
3455 cltv_expiry_delta: 0,
3456 htlc_minimum_msat: 0,
3457 htlc_maximum_msat: MAX_VALUE_MSAT,
3459 fee_proportional_millionths: 0,
3460 excess_data: Vec::new()
3462 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3463 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3464 short_channel_id: 13,
3466 flags: 2, // to disable
3467 cltv_expiry_delta: 0,
3468 htlc_minimum_msat: 0,
3469 htlc_maximum_msat: MAX_VALUE_MSAT,
3471 fee_proportional_millionths: 0,
3472 excess_data: Vec::new()
3474 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3475 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3476 short_channel_id: 6,
3478 flags: 2, // to disable
3479 cltv_expiry_delta: 0,
3480 htlc_minimum_msat: 0,
3481 htlc_maximum_msat: MAX_VALUE_MSAT,
3483 fee_proportional_millionths: 0,
3484 excess_data: Vec::new()
3486 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3487 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3488 short_channel_id: 7,
3490 flags: 2, // to disable
3491 cltv_expiry_delta: 0,
3492 htlc_minimum_msat: 0,
3493 htlc_maximum_msat: MAX_VALUE_MSAT,
3495 fee_proportional_millionths: 0,
3496 excess_data: Vec::new()
3499 // Check against amount_to_transfer_over_msat.
3500 // Set minimal HTLC of 200_000_000 msat.
3501 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3502 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3503 short_channel_id: 2,
3506 cltv_expiry_delta: 0,
3507 htlc_minimum_msat: 200_000_000,
3508 htlc_maximum_msat: MAX_VALUE_MSAT,
3510 fee_proportional_millionths: 0,
3511 excess_data: Vec::new()
3514 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3516 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3517 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3518 short_channel_id: 4,
3521 cltv_expiry_delta: 0,
3522 htlc_minimum_msat: 0,
3523 htlc_maximum_msat: 199_999_999,
3525 fee_proportional_millionths: 0,
3526 excess_data: Vec::new()
3529 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3530 let route_params = RouteParameters::from_payment_params_and_value(
3531 payment_params, 199_999_999);
3532 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3533 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3534 &Default::default(), &random_seed_bytes) {
3535 assert_eq!(err, "Failed to find a path to the given destination");
3536 } else { panic!(); }
3538 // Lift the restriction on the first hop.
3539 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3540 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3541 short_channel_id: 2,
3544 cltv_expiry_delta: 0,
3545 htlc_minimum_msat: 0,
3546 htlc_maximum_msat: MAX_VALUE_MSAT,
3548 fee_proportional_millionths: 0,
3549 excess_data: Vec::new()
3552 // A payment above the minimum should pass
3553 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3554 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3555 assert_eq!(route.paths[0].hops.len(), 2);
3559 fn htlc_minimum_overpay_test() {
3560 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3561 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3562 let config = UserConfig::default();
3563 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3564 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3566 let scorer = ln_test_utils::TestScorer::new();
3567 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3568 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3570 // A route to node#2 via two paths.
3571 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3572 // Thus, they can't send 60 without overpaying.
3573 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3574 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3575 short_channel_id: 2,
3578 cltv_expiry_delta: 0,
3579 htlc_minimum_msat: 35_000,
3580 htlc_maximum_msat: 40_000,
3582 fee_proportional_millionths: 0,
3583 excess_data: Vec::new()
3585 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3586 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3587 short_channel_id: 12,
3590 cltv_expiry_delta: 0,
3591 htlc_minimum_msat: 35_000,
3592 htlc_maximum_msat: 40_000,
3594 fee_proportional_millionths: 0,
3595 excess_data: Vec::new()
3599 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3600 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3601 short_channel_id: 13,
3604 cltv_expiry_delta: 0,
3605 htlc_minimum_msat: 0,
3606 htlc_maximum_msat: MAX_VALUE_MSAT,
3608 fee_proportional_millionths: 0,
3609 excess_data: Vec::new()
3611 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3612 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3613 short_channel_id: 4,
3616 cltv_expiry_delta: 0,
3617 htlc_minimum_msat: 0,
3618 htlc_maximum_msat: MAX_VALUE_MSAT,
3620 fee_proportional_millionths: 0,
3621 excess_data: Vec::new()
3624 // Disable other paths
3625 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3626 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3627 short_channel_id: 1,
3629 flags: 2, // to disable
3630 cltv_expiry_delta: 0,
3631 htlc_minimum_msat: 0,
3632 htlc_maximum_msat: MAX_VALUE_MSAT,
3634 fee_proportional_millionths: 0,
3635 excess_data: Vec::new()
3638 let mut route_params = RouteParameters::from_payment_params_and_value(
3639 payment_params.clone(), 60_000);
3640 route_params.max_total_routing_fee_msat = Some(15_000);
3641 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3642 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3643 // Overpay fees to hit htlc_minimum_msat.
3644 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3645 // TODO: this could be better balanced to overpay 10k and not 15k.
3646 assert_eq!(overpaid_fees, 15_000);
3648 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3649 // while taking even more fee to match htlc_minimum_msat.
3650 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3651 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3652 short_channel_id: 12,
3655 cltv_expiry_delta: 0,
3656 htlc_minimum_msat: 65_000,
3657 htlc_maximum_msat: 80_000,
3659 fee_proportional_millionths: 0,
3660 excess_data: Vec::new()
3662 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3663 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3664 short_channel_id: 2,
3667 cltv_expiry_delta: 0,
3668 htlc_minimum_msat: 0,
3669 htlc_maximum_msat: MAX_VALUE_MSAT,
3671 fee_proportional_millionths: 0,
3672 excess_data: Vec::new()
3674 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3675 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3676 short_channel_id: 4,
3679 cltv_expiry_delta: 0,
3680 htlc_minimum_msat: 0,
3681 htlc_maximum_msat: MAX_VALUE_MSAT,
3683 fee_proportional_millionths: 100_000,
3684 excess_data: Vec::new()
3687 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3688 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3689 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3690 assert_eq!(route.paths.len(), 1);
3691 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3692 let fees = route.paths[0].hops[0].fee_msat;
3693 assert_eq!(fees, 5_000);
3695 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3696 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3697 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3698 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3699 // the other channel.
3700 assert_eq!(route.paths.len(), 1);
3701 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3702 let fees = route.paths[0].hops[0].fee_msat;
3703 assert_eq!(fees, 5_000);
3707 fn htlc_minimum_recipient_overpay_test() {
3708 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3709 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3710 let config = UserConfig::default();
3711 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3712 let scorer = ln_test_utils::TestScorer::new();
3713 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3714 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3716 // Route to node2 over a single path which requires overpaying the recipient themselves.
3718 // First disable all paths except the us -> node1 -> node2 path
3719 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3720 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3721 short_channel_id: 13,
3724 cltv_expiry_delta: 0,
3725 htlc_minimum_msat: 0,
3726 htlc_maximum_msat: 0,
3728 fee_proportional_millionths: 0,
3729 excess_data: Vec::new()
3732 // Set channel 4 to free but with a high htlc_minimum_msat
3733 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3734 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3735 short_channel_id: 4,
3738 cltv_expiry_delta: 0,
3739 htlc_minimum_msat: 15_000,
3740 htlc_maximum_msat: MAX_VALUE_MSAT,
3742 fee_proportional_millionths: 0,
3743 excess_data: Vec::new()
3746 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3747 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3748 // what we try to find a route for, so this test only just happens to work out to exactly
3750 let mut route_params = RouteParameters::from_payment_params_and_value(
3751 payment_params.clone(), 5_000);
3752 route_params.max_total_routing_fee_msat = Some(9_999);
3753 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3754 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3755 &Default::default(), &random_seed_bytes) {
3756 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3757 } else { panic!(); }
3759 let mut route_params = RouteParameters::from_payment_params_and_value(
3760 payment_params.clone(), 5_000);
3761 route_params.max_total_routing_fee_msat = Some(10_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 assert_eq!(route.get_total_fees(), 10_000);
3768 fn disable_channels_test() {
3769 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3770 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3771 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3772 let scorer = ln_test_utils::TestScorer::new();
3773 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3774 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3776 // // Disable channels 4 and 12 by flags=2
3777 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3778 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3779 short_channel_id: 4,
3781 flags: 2, // to disable
3782 cltv_expiry_delta: 0,
3783 htlc_minimum_msat: 0,
3784 htlc_maximum_msat: MAX_VALUE_MSAT,
3786 fee_proportional_millionths: 0,
3787 excess_data: Vec::new()
3789 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3790 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3791 short_channel_id: 12,
3793 flags: 2, // to disable
3794 cltv_expiry_delta: 0,
3795 htlc_minimum_msat: 0,
3796 htlc_maximum_msat: MAX_VALUE_MSAT,
3798 fee_proportional_millionths: 0,
3799 excess_data: Vec::new()
3802 // If all the channels require some features we don't understand, route should fail
3803 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3804 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3805 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3806 &Default::default(), &random_seed_bytes) {
3807 assert_eq!(err, "Failed to find a path to the given destination");
3808 } else { panic!(); }
3810 // If we specify a channel to node7, that overrides our local channel view and that gets used
3811 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3812 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3813 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3814 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3815 &Default::default(), &random_seed_bytes).unwrap();
3816 assert_eq!(route.paths[0].hops.len(), 2);
3818 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3819 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3820 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3821 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3822 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3823 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3825 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3826 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3827 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3828 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3829 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3830 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3834 fn disable_node_test() {
3835 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3836 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3837 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3838 let scorer = ln_test_utils::TestScorer::new();
3839 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3840 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3842 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3843 let mut unknown_features = NodeFeatures::empty();
3844 unknown_features.set_unknown_feature_required();
3845 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3846 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3847 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3849 // If all nodes require some features we don't understand, route should fail
3850 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3851 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3852 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3853 &Default::default(), &random_seed_bytes) {
3854 assert_eq!(err, "Failed to find a path to the given destination");
3855 } else { panic!(); }
3857 // If we specify a channel to node7, that overrides our local channel view and that gets used
3858 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3859 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3860 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3861 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3862 &Default::default(), &random_seed_bytes).unwrap();
3863 assert_eq!(route.paths[0].hops.len(), 2);
3865 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3866 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3867 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3868 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3869 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3870 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3872 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3873 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3874 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3875 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3876 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3877 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3879 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3880 // naively) assume that the user checked the feature bits on the invoice, which override
3881 // the node_announcement.
3885 fn our_chans_test() {
3886 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3887 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3888 let scorer = ln_test_utils::TestScorer::new();
3889 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3890 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3892 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3893 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3894 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3895 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3896 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3897 assert_eq!(route.paths[0].hops.len(), 3);
3899 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3900 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3901 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3902 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3903 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3904 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3906 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3907 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3908 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3909 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3910 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3911 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3913 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3914 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3915 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3916 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3917 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3918 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3920 // If we specify a channel to node7, that overrides our local channel view and that gets used
3921 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3922 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3923 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3924 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3925 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3926 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3927 &Default::default(), &random_seed_bytes).unwrap();
3928 assert_eq!(route.paths[0].hops.len(), 2);
3930 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3931 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3932 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3933 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3934 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3935 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3937 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3938 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3939 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3940 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3941 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3942 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3945 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3946 let zero_fees = RoutingFees {
3948 proportional_millionths: 0,
3950 vec![RouteHint(vec![RouteHintHop {
3951 src_node_id: nodes[3],
3952 short_channel_id: 8,
3954 cltv_expiry_delta: (8 << 4) | 1,
3955 htlc_minimum_msat: None,
3956 htlc_maximum_msat: None,
3958 ]), RouteHint(vec![RouteHintHop {
3959 src_node_id: nodes[4],
3960 short_channel_id: 9,
3963 proportional_millionths: 0,
3965 cltv_expiry_delta: (9 << 4) | 1,
3966 htlc_minimum_msat: None,
3967 htlc_maximum_msat: None,
3968 }]), RouteHint(vec![RouteHintHop {
3969 src_node_id: nodes[5],
3970 short_channel_id: 10,
3972 cltv_expiry_delta: (10 << 4) | 1,
3973 htlc_minimum_msat: None,
3974 htlc_maximum_msat: None,
3978 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3979 let zero_fees = RoutingFees {
3981 proportional_millionths: 0,
3983 vec![RouteHint(vec![RouteHintHop {
3984 src_node_id: nodes[2],
3985 short_channel_id: 5,
3988 proportional_millionths: 0,
3990 cltv_expiry_delta: (5 << 4) | 1,
3991 htlc_minimum_msat: None,
3992 htlc_maximum_msat: None,
3994 src_node_id: nodes[3],
3995 short_channel_id: 8,
3997 cltv_expiry_delta: (8 << 4) | 1,
3998 htlc_minimum_msat: None,
3999 htlc_maximum_msat: None,
4001 ]), RouteHint(vec![RouteHintHop {
4002 src_node_id: nodes[4],
4003 short_channel_id: 9,
4006 proportional_millionths: 0,
4008 cltv_expiry_delta: (9 << 4) | 1,
4009 htlc_minimum_msat: None,
4010 htlc_maximum_msat: None,
4011 }]), RouteHint(vec![RouteHintHop {
4012 src_node_id: nodes[5],
4013 short_channel_id: 10,
4015 cltv_expiry_delta: (10 << 4) | 1,
4016 htlc_minimum_msat: None,
4017 htlc_maximum_msat: None,
4022 fn partial_route_hint_test() {
4023 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4024 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4025 let scorer = ln_test_utils::TestScorer::new();
4026 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4027 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4029 // Simple test across 2, 3, 5, and 4 via a last_hop channel
4030 // Tests the behaviour when the RouteHint contains a suboptimal hop.
4031 // RouteHint may be partially used by the algo to build the best path.
4033 // First check that last hop can't have its source as the payee.
4034 let invalid_last_hop = RouteHint(vec![RouteHintHop {
4035 src_node_id: nodes[6],
4036 short_channel_id: 8,
4039 proportional_millionths: 0,
4041 cltv_expiry_delta: (8 << 4) | 1,
4042 htlc_minimum_msat: None,
4043 htlc_maximum_msat: None,
4046 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
4047 invalid_last_hops.push(invalid_last_hop);
4049 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4050 .with_route_hints(invalid_last_hops).unwrap();
4051 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4052 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
4053 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
4054 &Default::default(), &random_seed_bytes) {
4055 assert_eq!(err, "Route hint cannot have the payee as the source.");
4056 } else { panic!(); }
4059 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4060 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
4061 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4062 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4063 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4064 assert_eq!(route.paths[0].hops.len(), 5);
4066 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4067 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4068 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4069 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4070 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4071 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4073 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4074 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4075 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4076 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4077 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4078 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4080 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4081 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4082 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4083 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4084 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4085 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4087 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4088 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4089 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4090 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4091 // If we have a peer in the node map, we'll use their features here since we don't have
4092 // a way of figuring out their features from the invoice:
4093 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4094 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4096 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4097 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4098 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4099 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4100 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4101 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4104 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4105 let zero_fees = RoutingFees {
4107 proportional_millionths: 0,
4109 vec![RouteHint(vec![RouteHintHop {
4110 src_node_id: nodes[3],
4111 short_channel_id: 8,
4113 cltv_expiry_delta: (8 << 4) | 1,
4114 htlc_minimum_msat: None,
4115 htlc_maximum_msat: None,
4116 }]), RouteHint(vec![
4118 ]), RouteHint(vec![RouteHintHop {
4119 src_node_id: nodes[5],
4120 short_channel_id: 10,
4122 cltv_expiry_delta: (10 << 4) | 1,
4123 htlc_minimum_msat: None,
4124 htlc_maximum_msat: None,
4129 fn ignores_empty_last_hops_test() {
4130 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4131 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4132 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
4133 let scorer = ln_test_utils::TestScorer::new();
4134 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4135 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4137 // Test handling of an empty RouteHint passed in Invoice.
4138 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4139 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4140 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4141 assert_eq!(route.paths[0].hops.len(), 5);
4143 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4144 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4145 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4146 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4147 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4148 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4150 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4151 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4152 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4153 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4154 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4155 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4157 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4158 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4159 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4160 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4161 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4162 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4164 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4165 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4166 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4167 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4168 // If we have a peer in the node map, we'll use their features here since we don't have
4169 // a way of figuring out their features from the invoice:
4170 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4171 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4173 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4174 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4175 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4176 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4177 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4178 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4181 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
4183 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
4184 let zero_fees = RoutingFees {
4186 proportional_millionths: 0,
4188 vec![RouteHint(vec![RouteHintHop {
4189 src_node_id: hint_hops[0],
4190 short_channel_id: 0xff00,
4193 proportional_millionths: 0,
4195 cltv_expiry_delta: (5 << 4) | 1,
4196 htlc_minimum_msat: None,
4197 htlc_maximum_msat: None,
4199 src_node_id: hint_hops[1],
4200 short_channel_id: 0xff01,
4202 cltv_expiry_delta: (8 << 4) | 1,
4203 htlc_minimum_msat: None,
4204 htlc_maximum_msat: None,
4209 fn multi_hint_last_hops_test() {
4210 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4211 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4212 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
4213 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4214 let scorer = ln_test_utils::TestScorer::new();
4215 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4216 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4217 // Test through channels 2, 3, 0xff00, 0xff01.
4218 // Test shows that multiple hop hints are considered.
4220 // Disabling channels 6 & 7 by flags=2
4221 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4222 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4223 short_channel_id: 6,
4225 flags: 2, // to disable
4226 cltv_expiry_delta: 0,
4227 htlc_minimum_msat: 0,
4228 htlc_maximum_msat: MAX_VALUE_MSAT,
4230 fee_proportional_millionths: 0,
4231 excess_data: Vec::new()
4233 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4234 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4235 short_channel_id: 7,
4237 flags: 2, // to disable
4238 cltv_expiry_delta: 0,
4239 htlc_minimum_msat: 0,
4240 htlc_maximum_msat: MAX_VALUE_MSAT,
4242 fee_proportional_millionths: 0,
4243 excess_data: Vec::new()
4246 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4247 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4248 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4249 assert_eq!(route.paths[0].hops.len(), 4);
4251 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4252 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4253 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4254 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4255 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4256 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4258 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4259 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4260 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4261 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4262 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4263 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4265 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4266 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4267 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4268 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4269 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4270 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4272 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4273 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4274 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4275 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4276 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4277 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4281 fn private_multi_hint_last_hops_test() {
4282 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4283 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4285 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4286 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4288 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4289 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4290 let scorer = ln_test_utils::TestScorer::new();
4291 // Test through channels 2, 3, 0xff00, 0xff01.
4292 // Test shows that multiple hop hints are considered.
4294 // Disabling channels 6 & 7 by flags=2
4295 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4296 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4297 short_channel_id: 6,
4299 flags: 2, // to disable
4300 cltv_expiry_delta: 0,
4301 htlc_minimum_msat: 0,
4302 htlc_maximum_msat: MAX_VALUE_MSAT,
4304 fee_proportional_millionths: 0,
4305 excess_data: Vec::new()
4307 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4308 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4309 short_channel_id: 7,
4311 flags: 2, // to disable
4312 cltv_expiry_delta: 0,
4313 htlc_minimum_msat: 0,
4314 htlc_maximum_msat: MAX_VALUE_MSAT,
4316 fee_proportional_millionths: 0,
4317 excess_data: Vec::new()
4320 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4321 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4322 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4323 assert_eq!(route.paths[0].hops.len(), 4);
4325 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4326 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4327 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4328 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4329 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4330 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4332 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4333 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4334 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4335 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4336 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4337 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4339 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4340 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4341 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4342 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4343 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4344 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4346 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4347 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4348 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4349 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4350 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4351 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4354 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4355 let zero_fees = RoutingFees {
4357 proportional_millionths: 0,
4359 vec![RouteHint(vec![RouteHintHop {
4360 src_node_id: nodes[4],
4361 short_channel_id: 11,
4363 cltv_expiry_delta: (11 << 4) | 1,
4364 htlc_minimum_msat: None,
4365 htlc_maximum_msat: None,
4367 src_node_id: nodes[3],
4368 short_channel_id: 8,
4370 cltv_expiry_delta: (8 << 4) | 1,
4371 htlc_minimum_msat: None,
4372 htlc_maximum_msat: None,
4373 }]), RouteHint(vec![RouteHintHop {
4374 src_node_id: nodes[4],
4375 short_channel_id: 9,
4378 proportional_millionths: 0,
4380 cltv_expiry_delta: (9 << 4) | 1,
4381 htlc_minimum_msat: None,
4382 htlc_maximum_msat: None,
4383 }]), RouteHint(vec![RouteHintHop {
4384 src_node_id: nodes[5],
4385 short_channel_id: 10,
4387 cltv_expiry_delta: (10 << 4) | 1,
4388 htlc_minimum_msat: None,
4389 htlc_maximum_msat: None,
4394 fn last_hops_with_public_channel_test() {
4395 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4396 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4397 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4398 let scorer = ln_test_utils::TestScorer::new();
4399 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4400 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4401 // This test shows that public routes can be present in the invoice
4402 // which would be handled in the same manner.
4404 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4405 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4406 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4407 assert_eq!(route.paths[0].hops.len(), 5);
4409 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4410 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4411 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4412 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4413 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4414 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4416 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4417 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4418 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4419 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4420 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4421 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4423 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4424 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4425 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4426 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4427 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4428 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4430 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4431 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4432 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4433 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4434 // If we have a peer in the node map, we'll use their features here since we don't have
4435 // a way of figuring out their features from the invoice:
4436 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4437 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4439 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4440 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4441 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4442 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4443 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4444 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4448 fn our_chans_last_hop_connect_test() {
4449 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4450 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4451 let scorer = ln_test_utils::TestScorer::new();
4452 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4453 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4455 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4456 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4457 let mut last_hops = last_hops(&nodes);
4458 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4459 .with_route_hints(last_hops.clone()).unwrap();
4460 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4461 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4462 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4463 &Default::default(), &random_seed_bytes).unwrap();
4464 assert_eq!(route.paths[0].hops.len(), 2);
4466 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4467 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4468 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4469 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4470 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4471 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4473 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4474 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4475 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4476 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4477 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4478 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4480 last_hops[0].0[0].fees.base_msat = 1000;
4482 // Revert to via 6 as the fee on 8 goes up
4483 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4484 .with_route_hints(last_hops).unwrap();
4485 let route_params = RouteParameters::from_payment_params_and_value(
4486 payment_params.clone(), 100);
4487 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4488 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4489 assert_eq!(route.paths[0].hops.len(), 4);
4491 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4492 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4493 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4494 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4495 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4496 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4498 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4499 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4500 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4501 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4502 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4503 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4505 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4506 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4507 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4508 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4509 // If we have a peer in the node map, we'll use their features here since we don't have
4510 // a way of figuring out their features from the invoice:
4511 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4512 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4514 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4515 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4516 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4517 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4518 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4519 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4521 // ...but still use 8 for larger payments as 6 has a variable feerate
4522 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4523 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4524 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4525 assert_eq!(route.paths[0].hops.len(), 5);
4527 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4528 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4529 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4530 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4531 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4532 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4534 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4535 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4536 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4537 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4538 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4539 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4541 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4542 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4543 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4544 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4545 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4546 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4548 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4549 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4550 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4551 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4552 // If we have a peer in the node map, we'll use their features here since we don't have
4553 // a way of figuring out their features from the invoice:
4554 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4555 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4557 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4558 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4559 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4560 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4561 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4562 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4565 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> {
4566 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4567 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4568 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4570 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4571 let last_hops = RouteHint(vec![RouteHintHop {
4572 src_node_id: middle_node_id,
4573 short_channel_id: 8,
4576 proportional_millionths: last_hop_fee_prop,
4578 cltv_expiry_delta: (8 << 4) | 1,
4579 htlc_minimum_msat: None,
4580 htlc_maximum_msat: last_hop_htlc_max,
4582 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4583 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4584 let scorer = ln_test_utils::TestScorer::new();
4585 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4586 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4587 let logger = ln_test_utils::TestLogger::new();
4588 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4589 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4590 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4591 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4592 &random_seed_bytes);
4597 fn unannounced_path_test() {
4598 // We should be able to send a payment to a destination without any help of a routing graph
4599 // if we have a channel with a common counterparty that appears in the first and last hop
4601 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4603 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4604 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4605 assert_eq!(route.paths[0].hops.len(), 2);
4607 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4608 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4609 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4610 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4611 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4612 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4614 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4615 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4616 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4617 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4618 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4619 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4623 fn overflow_unannounced_path_test_liquidity_underflow() {
4624 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4625 // the last-hop had a fee which overflowed a u64, we'd panic.
4626 // This was due to us adding the first-hop from us unconditionally, causing us to think
4627 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4628 // In this test, we previously hit a subtraction underflow due to having less available
4629 // liquidity at the last hop than 0.
4630 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());
4634 fn overflow_unannounced_path_test_feerate_overflow() {
4635 // This tests for the same case as above, except instead of hitting a subtraction
4636 // underflow, we hit a case where the fee charged at a hop overflowed.
4637 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());
4641 fn available_amount_while_routing_test() {
4642 // Tests whether we choose the correct available channel amount while routing.
4644 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4645 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4646 let scorer = ln_test_utils::TestScorer::new();
4647 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4648 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4649 let config = UserConfig::default();
4650 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4651 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4654 // We will use a simple single-path route from
4655 // our node to node2 via node0: channels {1, 3}.
4657 // First disable all other paths.
4658 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4659 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4660 short_channel_id: 2,
4663 cltv_expiry_delta: 0,
4664 htlc_minimum_msat: 0,
4665 htlc_maximum_msat: 100_000,
4667 fee_proportional_millionths: 0,
4668 excess_data: Vec::new()
4670 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4671 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4672 short_channel_id: 12,
4675 cltv_expiry_delta: 0,
4676 htlc_minimum_msat: 0,
4677 htlc_maximum_msat: 100_000,
4679 fee_proportional_millionths: 0,
4680 excess_data: Vec::new()
4683 // Make the first channel (#1) very permissive,
4684 // and we will be testing all limits on the second channel.
4685 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4686 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4687 short_channel_id: 1,
4690 cltv_expiry_delta: 0,
4691 htlc_minimum_msat: 0,
4692 htlc_maximum_msat: 1_000_000_000,
4694 fee_proportional_millionths: 0,
4695 excess_data: Vec::new()
4698 // First, let's see if routing works if we have absolutely no idea about the available amount.
4699 // In this case, it should be set to 250_000 sats.
4700 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4701 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4702 short_channel_id: 3,
4705 cltv_expiry_delta: 0,
4706 htlc_minimum_msat: 0,
4707 htlc_maximum_msat: 250_000_000,
4709 fee_proportional_millionths: 0,
4710 excess_data: Vec::new()
4714 // Attempt to route more than available results in a failure.
4715 let route_params = RouteParameters::from_payment_params_and_value(
4716 payment_params.clone(), 250_000_001);
4717 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4718 &our_id, &route_params, &network_graph.read_only(), None,
4719 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4720 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4721 } else { panic!(); }
4725 // Now, attempt to route an exact amount we have should be fine.
4726 let route_params = RouteParameters::from_payment_params_and_value(
4727 payment_params.clone(), 250_000_000);
4728 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4729 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4730 assert_eq!(route.paths.len(), 1);
4731 let path = route.paths.last().unwrap();
4732 assert_eq!(path.hops.len(), 2);
4733 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4734 assert_eq!(path.final_value_msat(), 250_000_000);
4737 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4738 // Disable channel #1 and use another first hop.
4739 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4740 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4741 short_channel_id: 1,
4744 cltv_expiry_delta: 0,
4745 htlc_minimum_msat: 0,
4746 htlc_maximum_msat: 1_000_000_000,
4748 fee_proportional_millionths: 0,
4749 excess_data: Vec::new()
4752 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4753 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4756 // Attempt to route more than available results in a failure.
4757 let route_params = RouteParameters::from_payment_params_and_value(
4758 payment_params.clone(), 200_000_001);
4759 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4760 &our_id, &route_params, &network_graph.read_only(),
4761 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4762 &Default::default(), &random_seed_bytes) {
4763 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4764 } else { panic!(); }
4768 // Now, attempt to route an exact amount we have should be fine.
4769 let route_params = RouteParameters::from_payment_params_and_value(
4770 payment_params.clone(), 200_000_000);
4771 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4772 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4773 &Default::default(), &random_seed_bytes).unwrap();
4774 assert_eq!(route.paths.len(), 1);
4775 let path = route.paths.last().unwrap();
4776 assert_eq!(path.hops.len(), 2);
4777 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4778 assert_eq!(path.final_value_msat(), 200_000_000);
4781 // Enable channel #1 back.
4782 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4783 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4784 short_channel_id: 1,
4787 cltv_expiry_delta: 0,
4788 htlc_minimum_msat: 0,
4789 htlc_maximum_msat: 1_000_000_000,
4791 fee_proportional_millionths: 0,
4792 excess_data: Vec::new()
4796 // Now let's see if routing works if we know only htlc_maximum_msat.
4797 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4798 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4799 short_channel_id: 3,
4802 cltv_expiry_delta: 0,
4803 htlc_minimum_msat: 0,
4804 htlc_maximum_msat: 15_000,
4806 fee_proportional_millionths: 0,
4807 excess_data: Vec::new()
4811 // Attempt to route more than available results in a failure.
4812 let route_params = RouteParameters::from_payment_params_and_value(
4813 payment_params.clone(), 15_001);
4814 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4815 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4816 &scorer, &Default::default(), &random_seed_bytes) {
4817 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4818 } else { panic!(); }
4822 // Now, attempt to route an exact amount we have should be fine.
4823 let route_params = RouteParameters::from_payment_params_and_value(
4824 payment_params.clone(), 15_000);
4825 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4826 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4827 assert_eq!(route.paths.len(), 1);
4828 let path = route.paths.last().unwrap();
4829 assert_eq!(path.hops.len(), 2);
4830 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4831 assert_eq!(path.final_value_msat(), 15_000);
4834 // Now let's see if routing works if we know only capacity from the UTXO.
4836 // We can't change UTXO capacity on the fly, so we'll disable
4837 // the existing channel and add another one with the capacity we need.
4838 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4839 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4840 short_channel_id: 3,
4843 cltv_expiry_delta: 0,
4844 htlc_minimum_msat: 0,
4845 htlc_maximum_msat: MAX_VALUE_MSAT,
4847 fee_proportional_millionths: 0,
4848 excess_data: Vec::new()
4851 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4852 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4853 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4854 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4855 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4857 *chain_monitor.utxo_ret.lock().unwrap() =
4858 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4859 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4861 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4862 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4863 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4864 short_channel_id: 333,
4867 cltv_expiry_delta: (3 << 4) | 1,
4868 htlc_minimum_msat: 0,
4869 htlc_maximum_msat: 15_000,
4871 fee_proportional_millionths: 0,
4872 excess_data: Vec::new()
4874 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4875 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4876 short_channel_id: 333,
4879 cltv_expiry_delta: (3 << 4) | 2,
4880 htlc_minimum_msat: 0,
4881 htlc_maximum_msat: 15_000,
4883 fee_proportional_millionths: 0,
4884 excess_data: Vec::new()
4888 // Attempt to route more than available results in a failure.
4889 let route_params = RouteParameters::from_payment_params_and_value(
4890 payment_params.clone(), 15_001);
4891 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4892 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4893 &scorer, &Default::default(), &random_seed_bytes) {
4894 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4895 } else { panic!(); }
4899 // Now, attempt to route an exact amount we have should be fine.
4900 let route_params = RouteParameters::from_payment_params_and_value(
4901 payment_params.clone(), 15_000);
4902 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4903 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4904 assert_eq!(route.paths.len(), 1);
4905 let path = route.paths.last().unwrap();
4906 assert_eq!(path.hops.len(), 2);
4907 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4908 assert_eq!(path.final_value_msat(), 15_000);
4911 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4912 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4913 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4914 short_channel_id: 333,
4917 cltv_expiry_delta: 0,
4918 htlc_minimum_msat: 0,
4919 htlc_maximum_msat: 10_000,
4921 fee_proportional_millionths: 0,
4922 excess_data: Vec::new()
4926 // Attempt to route more than available results in a failure.
4927 let route_params = RouteParameters::from_payment_params_and_value(
4928 payment_params.clone(), 10_001);
4929 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4930 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4931 &scorer, &Default::default(), &random_seed_bytes) {
4932 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4933 } else { panic!(); }
4937 // Now, attempt to route an exact amount we have should be fine.
4938 let route_params = RouteParameters::from_payment_params_and_value(
4939 payment_params.clone(), 10_000);
4940 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4941 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4942 assert_eq!(route.paths.len(), 1);
4943 let path = route.paths.last().unwrap();
4944 assert_eq!(path.hops.len(), 2);
4945 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4946 assert_eq!(path.final_value_msat(), 10_000);
4951 fn available_liquidity_last_hop_test() {
4952 // Check that available liquidity properly limits the path even when only
4953 // one of the latter hops is limited.
4954 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4955 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4956 let scorer = ln_test_utils::TestScorer::new();
4957 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4958 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4959 let config = UserConfig::default();
4960 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4961 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4964 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4965 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4966 // Total capacity: 50 sats.
4968 // Disable other potential paths.
4969 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4970 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4971 short_channel_id: 2,
4974 cltv_expiry_delta: 0,
4975 htlc_minimum_msat: 0,
4976 htlc_maximum_msat: 100_000,
4978 fee_proportional_millionths: 0,
4979 excess_data: Vec::new()
4981 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4982 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4983 short_channel_id: 7,
4986 cltv_expiry_delta: 0,
4987 htlc_minimum_msat: 0,
4988 htlc_maximum_msat: 100_000,
4990 fee_proportional_millionths: 0,
4991 excess_data: Vec::new()
4996 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4997 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4998 short_channel_id: 12,
5001 cltv_expiry_delta: 0,
5002 htlc_minimum_msat: 0,
5003 htlc_maximum_msat: 100_000,
5005 fee_proportional_millionths: 0,
5006 excess_data: Vec::new()
5008 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5009 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5010 short_channel_id: 13,
5013 cltv_expiry_delta: 0,
5014 htlc_minimum_msat: 0,
5015 htlc_maximum_msat: 100_000,
5017 fee_proportional_millionths: 0,
5018 excess_data: Vec::new()
5021 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5022 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5023 short_channel_id: 6,
5026 cltv_expiry_delta: 0,
5027 htlc_minimum_msat: 0,
5028 htlc_maximum_msat: 50_000,
5030 fee_proportional_millionths: 0,
5031 excess_data: Vec::new()
5033 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5034 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5035 short_channel_id: 11,
5038 cltv_expiry_delta: 0,
5039 htlc_minimum_msat: 0,
5040 htlc_maximum_msat: 100_000,
5042 fee_proportional_millionths: 0,
5043 excess_data: Vec::new()
5046 // Attempt to route more than available results in a failure.
5047 let route_params = RouteParameters::from_payment_params_and_value(
5048 payment_params.clone(), 60_000);
5049 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5050 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5051 &scorer, &Default::default(), &random_seed_bytes) {
5052 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5053 } else { panic!(); }
5057 // Now, attempt to route 49 sats (just a bit below the capacity).
5058 let route_params = RouteParameters::from_payment_params_and_value(
5059 payment_params.clone(), 49_000);
5060 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5061 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5062 assert_eq!(route.paths.len(), 1);
5063 let mut total_amount_paid_msat = 0;
5064 for path in &route.paths {
5065 assert_eq!(path.hops.len(), 4);
5066 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5067 total_amount_paid_msat += path.final_value_msat();
5069 assert_eq!(total_amount_paid_msat, 49_000);
5073 // Attempt to route an exact amount is also fine
5074 let route_params = RouteParameters::from_payment_params_and_value(
5075 payment_params, 50_000);
5076 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5077 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5078 assert_eq!(route.paths.len(), 1);
5079 let mut total_amount_paid_msat = 0;
5080 for path in &route.paths {
5081 assert_eq!(path.hops.len(), 4);
5082 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5083 total_amount_paid_msat += path.final_value_msat();
5085 assert_eq!(total_amount_paid_msat, 50_000);
5090 fn ignore_fee_first_hop_test() {
5091 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5092 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5093 let scorer = ln_test_utils::TestScorer::new();
5094 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5095 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5096 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5098 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5099 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5100 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5101 short_channel_id: 1,
5104 cltv_expiry_delta: 0,
5105 htlc_minimum_msat: 0,
5106 htlc_maximum_msat: 100_000,
5107 fee_base_msat: 1_000_000,
5108 fee_proportional_millionths: 0,
5109 excess_data: Vec::new()
5111 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5112 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5113 short_channel_id: 3,
5116 cltv_expiry_delta: 0,
5117 htlc_minimum_msat: 0,
5118 htlc_maximum_msat: 50_000,
5120 fee_proportional_millionths: 0,
5121 excess_data: Vec::new()
5125 let route_params = RouteParameters::from_payment_params_and_value(
5126 payment_params, 50_000);
5127 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5128 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5129 assert_eq!(route.paths.len(), 1);
5130 let mut total_amount_paid_msat = 0;
5131 for path in &route.paths {
5132 assert_eq!(path.hops.len(), 2);
5133 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5134 total_amount_paid_msat += path.final_value_msat();
5136 assert_eq!(total_amount_paid_msat, 50_000);
5141 fn simple_mpp_route_test() {
5142 let (secp_ctx, _, _, _, _) = build_graph();
5143 let (_, _, _, nodes) = get_nodes(&secp_ctx);
5144 let config = UserConfig::default();
5145 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5146 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5148 do_simple_mpp_route_test(clear_payment_params);
5150 // MPP to a 1-hop blinded path for nodes[2]
5151 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
5152 let blinded_path = BlindedPath {
5153 introduction_node: IntroductionNode::NodeId(nodes[2]),
5154 blinding_point: ln_test_utils::pubkey(42),
5155 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
5157 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
5159 fee_proportional_millionths: 0,
5160 htlc_minimum_msat: 0,
5161 htlc_maximum_msat: 0,
5162 cltv_expiry_delta: 0,
5163 features: BlindedHopFeatures::empty(),
5165 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
5166 .with_bolt12_features(bolt12_features.clone()).unwrap();
5167 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
5169 // MPP to 3 2-hop blinded paths
5170 let mut blinded_path_node_0 = blinded_path.clone();
5171 blinded_path_node_0.introduction_node = IntroductionNode::NodeId(nodes[0]);
5172 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
5173 let mut node_0_payinfo = blinded_payinfo.clone();
5174 node_0_payinfo.htlc_maximum_msat = 50_000;
5176 let mut blinded_path_node_7 = blinded_path_node_0.clone();
5177 blinded_path_node_7.introduction_node = IntroductionNode::NodeId(nodes[7]);
5178 let mut node_7_payinfo = blinded_payinfo.clone();
5179 node_7_payinfo.htlc_maximum_msat = 60_000;
5181 let mut blinded_path_node_1 = blinded_path_node_0.clone();
5182 blinded_path_node_1.introduction_node = IntroductionNode::NodeId(nodes[1]);
5183 let mut node_1_payinfo = blinded_payinfo.clone();
5184 node_1_payinfo.htlc_maximum_msat = 180_000;
5186 let two_hop_blinded_payment_params = PaymentParameters::blinded(
5188 (node_0_payinfo, blinded_path_node_0),
5189 (node_7_payinfo, blinded_path_node_7),
5190 (node_1_payinfo, blinded_path_node_1)
5192 .with_bolt12_features(bolt12_features).unwrap();
5193 do_simple_mpp_route_test(two_hop_blinded_payment_params);
5197 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
5198 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5199 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5200 let scorer = ln_test_utils::TestScorer::new();
5201 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5202 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5204 // We need a route consisting of 3 paths:
5205 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5206 // To achieve this, the amount being transferred should be around
5207 // the total capacity of these 3 paths.
5209 // First, we set limits on these (previously unlimited) channels.
5210 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
5212 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5213 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5214 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5215 short_channel_id: 1,
5218 cltv_expiry_delta: 0,
5219 htlc_minimum_msat: 0,
5220 htlc_maximum_msat: 100_000,
5222 fee_proportional_millionths: 0,
5223 excess_data: Vec::new()
5225 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5226 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5227 short_channel_id: 3,
5230 cltv_expiry_delta: 0,
5231 htlc_minimum_msat: 0,
5232 htlc_maximum_msat: 50_000,
5234 fee_proportional_millionths: 0,
5235 excess_data: Vec::new()
5238 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
5239 // (total limit 60).
5240 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5241 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5242 short_channel_id: 12,
5245 cltv_expiry_delta: 0,
5246 htlc_minimum_msat: 0,
5247 htlc_maximum_msat: 60_000,
5249 fee_proportional_millionths: 0,
5250 excess_data: Vec::new()
5252 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5253 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5254 short_channel_id: 13,
5257 cltv_expiry_delta: 0,
5258 htlc_minimum_msat: 0,
5259 htlc_maximum_msat: 60_000,
5261 fee_proportional_millionths: 0,
5262 excess_data: Vec::new()
5265 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5266 // (total capacity 180 sats).
5267 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5268 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5269 short_channel_id: 2,
5272 cltv_expiry_delta: 0,
5273 htlc_minimum_msat: 0,
5274 htlc_maximum_msat: 200_000,
5276 fee_proportional_millionths: 0,
5277 excess_data: Vec::new()
5279 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5280 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5281 short_channel_id: 4,
5284 cltv_expiry_delta: 0,
5285 htlc_minimum_msat: 0,
5286 htlc_maximum_msat: 180_000,
5288 fee_proportional_millionths: 0,
5289 excess_data: Vec::new()
5293 // Attempt to route more than available results in a failure.
5294 let route_params = RouteParameters::from_payment_params_and_value(
5295 payment_params.clone(), 300_000);
5296 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5297 &our_id, &route_params, &network_graph.read_only(), None,
5298 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5299 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5300 } else { panic!(); }
5304 // Attempt to route while setting max_path_count to 0 results in a failure.
5305 let zero_payment_params = payment_params.clone().with_max_path_count(0);
5306 let route_params = RouteParameters::from_payment_params_and_value(
5307 zero_payment_params, 100);
5308 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5309 &our_id, &route_params, &network_graph.read_only(), None,
5310 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5311 assert_eq!(err, "Can't find a route with no paths allowed.");
5312 } else { panic!(); }
5316 // Attempt to route while setting max_path_count to 3 results in a failure.
5317 // This is the case because the minimal_value_contribution_msat would require each path
5318 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5319 let fail_payment_params = payment_params.clone().with_max_path_count(3);
5320 let route_params = RouteParameters::from_payment_params_and_value(
5321 fail_payment_params, 250_000);
5322 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5323 &our_id, &route_params, &network_graph.read_only(), None,
5324 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5325 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5326 } else { panic!(); }
5330 // Now, attempt to route 250 sats (just a bit below the capacity).
5331 // Our algorithm should provide us with these 3 paths.
5332 let route_params = RouteParameters::from_payment_params_and_value(
5333 payment_params.clone(), 250_000);
5334 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5335 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5336 assert_eq!(route.paths.len(), 3);
5337 let mut total_amount_paid_msat = 0;
5338 for path in &route.paths {
5339 if let Some(bt) = &path.blinded_tail {
5340 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5342 assert_eq!(path.hops.len(), 2);
5343 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5345 total_amount_paid_msat += path.final_value_msat();
5347 assert_eq!(total_amount_paid_msat, 250_000);
5351 // Attempt to route an exact amount is also fine
5352 let route_params = RouteParameters::from_payment_params_and_value(
5353 payment_params.clone(), 290_000);
5354 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5355 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5356 assert_eq!(route.paths.len(), 3);
5357 let mut total_amount_paid_msat = 0;
5358 for path in &route.paths {
5359 if payment_params.payee.blinded_route_hints().len() != 0 {
5360 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5361 if let Some(bt) = &path.blinded_tail {
5362 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5363 if bt.hops.len() > 1 {
5364 let network_graph = network_graph.read_only();
5366 NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
5367 payment_params.payee.blinded_route_hints().iter()
5368 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5369 .and_then(|(_, p)| p.public_introduction_node_id(&network_graph))
5374 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5377 assert_eq!(path.hops.len(), 2);
5378 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5380 total_amount_paid_msat += path.final_value_msat();
5382 assert_eq!(total_amount_paid_msat, 290_000);
5387 fn long_mpp_route_test() {
5388 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5389 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5390 let scorer = ln_test_utils::TestScorer::new();
5391 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5392 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5393 let config = UserConfig::default();
5394 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5395 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5398 // We need a route consisting of 3 paths:
5399 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5400 // Note that these paths overlap (channels 5, 12, 13).
5401 // We will route 300 sats.
5402 // Each path will have 100 sats capacity, those channels which
5403 // are used twice will have 200 sats capacity.
5405 // Disable other potential paths.
5406 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5407 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5408 short_channel_id: 2,
5411 cltv_expiry_delta: 0,
5412 htlc_minimum_msat: 0,
5413 htlc_maximum_msat: 100_000,
5415 fee_proportional_millionths: 0,
5416 excess_data: Vec::new()
5418 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5419 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5420 short_channel_id: 7,
5423 cltv_expiry_delta: 0,
5424 htlc_minimum_msat: 0,
5425 htlc_maximum_msat: 100_000,
5427 fee_proportional_millionths: 0,
5428 excess_data: Vec::new()
5431 // Path via {node0, node2} is channels {1, 3, 5}.
5432 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5433 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5434 short_channel_id: 1,
5437 cltv_expiry_delta: 0,
5438 htlc_minimum_msat: 0,
5439 htlc_maximum_msat: 100_000,
5441 fee_proportional_millionths: 0,
5442 excess_data: Vec::new()
5444 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5445 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5446 short_channel_id: 3,
5449 cltv_expiry_delta: 0,
5450 htlc_minimum_msat: 0,
5451 htlc_maximum_msat: 100_000,
5453 fee_proportional_millionths: 0,
5454 excess_data: Vec::new()
5457 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5458 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5459 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5460 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5461 short_channel_id: 5,
5464 cltv_expiry_delta: 0,
5465 htlc_minimum_msat: 0,
5466 htlc_maximum_msat: 200_000,
5468 fee_proportional_millionths: 0,
5469 excess_data: Vec::new()
5472 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5473 // Add 100 sats to the capacities of {12, 13}, because these channels
5474 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5475 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5476 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5477 short_channel_id: 12,
5480 cltv_expiry_delta: 0,
5481 htlc_minimum_msat: 0,
5482 htlc_maximum_msat: 200_000,
5484 fee_proportional_millionths: 0,
5485 excess_data: Vec::new()
5487 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5488 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5489 short_channel_id: 13,
5492 cltv_expiry_delta: 0,
5493 htlc_minimum_msat: 0,
5494 htlc_maximum_msat: 200_000,
5496 fee_proportional_millionths: 0,
5497 excess_data: Vec::new()
5500 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5501 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5502 short_channel_id: 6,
5505 cltv_expiry_delta: 0,
5506 htlc_minimum_msat: 0,
5507 htlc_maximum_msat: 100_000,
5509 fee_proportional_millionths: 0,
5510 excess_data: Vec::new()
5512 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5513 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5514 short_channel_id: 11,
5517 cltv_expiry_delta: 0,
5518 htlc_minimum_msat: 0,
5519 htlc_maximum_msat: 100_000,
5521 fee_proportional_millionths: 0,
5522 excess_data: Vec::new()
5525 // Path via {node7, node2} is channels {12, 13, 5}.
5526 // We already limited them to 200 sats (they are used twice for 100 sats).
5527 // Nothing to do here.
5530 // Attempt to route more than available results in a failure.
5531 let route_params = RouteParameters::from_payment_params_and_value(
5532 payment_params.clone(), 350_000);
5533 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5534 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5535 &scorer, &Default::default(), &random_seed_bytes) {
5536 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5537 } else { panic!(); }
5541 // Now, attempt to route 300 sats (exact amount we can route).
5542 // Our algorithm should provide us with these 3 paths, 100 sats each.
5543 let route_params = RouteParameters::from_payment_params_and_value(
5544 payment_params, 300_000);
5545 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5546 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5547 assert_eq!(route.paths.len(), 3);
5549 let mut total_amount_paid_msat = 0;
5550 for path in &route.paths {
5551 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5552 total_amount_paid_msat += path.final_value_msat();
5554 assert_eq!(total_amount_paid_msat, 300_000);
5560 fn mpp_cheaper_route_test() {
5561 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5562 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5563 let scorer = ln_test_utils::TestScorer::new();
5564 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5565 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5566 let config = UserConfig::default();
5567 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5568 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5571 // This test checks that if we have two cheaper paths and one more expensive path,
5572 // so that liquidity-wise any 2 of 3 combination is sufficient,
5573 // two cheaper paths will be taken.
5574 // These paths have equal available liquidity.
5576 // We need a combination of 3 paths:
5577 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5578 // Note that these paths overlap (channels 5, 12, 13).
5579 // Each path will have 100 sats capacity, those channels which
5580 // are used twice will have 200 sats capacity.
5582 // Disable other potential paths.
5583 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5584 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5585 short_channel_id: 2,
5588 cltv_expiry_delta: 0,
5589 htlc_minimum_msat: 0,
5590 htlc_maximum_msat: 100_000,
5592 fee_proportional_millionths: 0,
5593 excess_data: Vec::new()
5595 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5596 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5597 short_channel_id: 7,
5600 cltv_expiry_delta: 0,
5601 htlc_minimum_msat: 0,
5602 htlc_maximum_msat: 100_000,
5604 fee_proportional_millionths: 0,
5605 excess_data: Vec::new()
5608 // Path via {node0, node2} is channels {1, 3, 5}.
5609 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5610 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5611 short_channel_id: 1,
5614 cltv_expiry_delta: 0,
5615 htlc_minimum_msat: 0,
5616 htlc_maximum_msat: 100_000,
5618 fee_proportional_millionths: 0,
5619 excess_data: Vec::new()
5621 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5622 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5623 short_channel_id: 3,
5626 cltv_expiry_delta: 0,
5627 htlc_minimum_msat: 0,
5628 htlc_maximum_msat: 100_000,
5630 fee_proportional_millionths: 0,
5631 excess_data: Vec::new()
5634 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5635 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5636 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5637 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5638 short_channel_id: 5,
5641 cltv_expiry_delta: 0,
5642 htlc_minimum_msat: 0,
5643 htlc_maximum_msat: 200_000,
5645 fee_proportional_millionths: 0,
5646 excess_data: Vec::new()
5649 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5650 // Add 100 sats to the capacities of {12, 13}, because these channels
5651 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5652 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5653 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5654 short_channel_id: 12,
5657 cltv_expiry_delta: 0,
5658 htlc_minimum_msat: 0,
5659 htlc_maximum_msat: 200_000,
5661 fee_proportional_millionths: 0,
5662 excess_data: Vec::new()
5664 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5665 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5666 short_channel_id: 13,
5669 cltv_expiry_delta: 0,
5670 htlc_minimum_msat: 0,
5671 htlc_maximum_msat: 200_000,
5673 fee_proportional_millionths: 0,
5674 excess_data: Vec::new()
5677 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5678 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5679 short_channel_id: 6,
5682 cltv_expiry_delta: 0,
5683 htlc_minimum_msat: 0,
5684 htlc_maximum_msat: 100_000,
5685 fee_base_msat: 1_000,
5686 fee_proportional_millionths: 0,
5687 excess_data: Vec::new()
5689 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5690 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5691 short_channel_id: 11,
5694 cltv_expiry_delta: 0,
5695 htlc_minimum_msat: 0,
5696 htlc_maximum_msat: 100_000,
5698 fee_proportional_millionths: 0,
5699 excess_data: Vec::new()
5702 // Path via {node7, node2} is channels {12, 13, 5}.
5703 // We already limited them to 200 sats (they are used twice for 100 sats).
5704 // Nothing to do here.
5707 // Now, attempt to route 180 sats.
5708 // Our algorithm should provide us with these 2 paths.
5709 let route_params = RouteParameters::from_payment_params_and_value(
5710 payment_params, 180_000);
5711 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5712 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5713 assert_eq!(route.paths.len(), 2);
5715 let mut total_value_transferred_msat = 0;
5716 let mut total_paid_msat = 0;
5717 for path in &route.paths {
5718 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5719 total_value_transferred_msat += path.final_value_msat();
5720 for hop in &path.hops {
5721 total_paid_msat += hop.fee_msat;
5724 // If we paid fee, this would be higher.
5725 assert_eq!(total_value_transferred_msat, 180_000);
5726 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5727 assert_eq!(total_fees_paid, 0);
5732 fn fees_on_mpp_route_test() {
5733 // This test makes sure that MPP algorithm properly takes into account
5734 // fees charged on the channels, by making the fees impactful:
5735 // if the fee is not properly accounted for, the behavior is different.
5736 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5737 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5738 let scorer = ln_test_utils::TestScorer::new();
5739 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5740 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5741 let config = UserConfig::default();
5742 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5743 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5746 // We need a route consisting of 2 paths:
5747 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5748 // We will route 200 sats, Each path will have 100 sats capacity.
5750 // This test is not particularly stable: e.g.,
5751 // there's a way to route via {node0, node2, node4}.
5752 // It works while pathfinding is deterministic, but can be broken otherwise.
5753 // It's fine to ignore this concern for now.
5755 // Disable other potential paths.
5756 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5757 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5758 short_channel_id: 2,
5761 cltv_expiry_delta: 0,
5762 htlc_minimum_msat: 0,
5763 htlc_maximum_msat: 100_000,
5765 fee_proportional_millionths: 0,
5766 excess_data: Vec::new()
5769 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5770 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5771 short_channel_id: 7,
5774 cltv_expiry_delta: 0,
5775 htlc_minimum_msat: 0,
5776 htlc_maximum_msat: 100_000,
5778 fee_proportional_millionths: 0,
5779 excess_data: Vec::new()
5782 // Path via {node0, node2} is channels {1, 3, 5}.
5783 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5784 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5785 short_channel_id: 1,
5788 cltv_expiry_delta: 0,
5789 htlc_minimum_msat: 0,
5790 htlc_maximum_msat: 100_000,
5792 fee_proportional_millionths: 0,
5793 excess_data: Vec::new()
5795 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5796 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5797 short_channel_id: 3,
5800 cltv_expiry_delta: 0,
5801 htlc_minimum_msat: 0,
5802 htlc_maximum_msat: 100_000,
5804 fee_proportional_millionths: 0,
5805 excess_data: Vec::new()
5808 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5809 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5810 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5811 short_channel_id: 5,
5814 cltv_expiry_delta: 0,
5815 htlc_minimum_msat: 0,
5816 htlc_maximum_msat: 100_000,
5818 fee_proportional_millionths: 0,
5819 excess_data: Vec::new()
5822 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5823 // All channels should be 100 sats capacity. But for the fee experiment,
5824 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5825 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5826 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5827 // so no matter how large are other channels,
5828 // the whole path will be limited by 100 sats with just these 2 conditions:
5829 // - channel 12 capacity is 250 sats
5830 // - fee for channel 6 is 150 sats
5831 // Let's test this by enforcing these 2 conditions and removing other limits.
5832 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5833 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5834 short_channel_id: 12,
5837 cltv_expiry_delta: 0,
5838 htlc_minimum_msat: 0,
5839 htlc_maximum_msat: 250_000,
5841 fee_proportional_millionths: 0,
5842 excess_data: Vec::new()
5844 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5845 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5846 short_channel_id: 13,
5849 cltv_expiry_delta: 0,
5850 htlc_minimum_msat: 0,
5851 htlc_maximum_msat: MAX_VALUE_MSAT,
5853 fee_proportional_millionths: 0,
5854 excess_data: Vec::new()
5857 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5858 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5859 short_channel_id: 6,
5862 cltv_expiry_delta: 0,
5863 htlc_minimum_msat: 0,
5864 htlc_maximum_msat: MAX_VALUE_MSAT,
5865 fee_base_msat: 150_000,
5866 fee_proportional_millionths: 0,
5867 excess_data: Vec::new()
5869 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5870 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5871 short_channel_id: 11,
5874 cltv_expiry_delta: 0,
5875 htlc_minimum_msat: 0,
5876 htlc_maximum_msat: MAX_VALUE_MSAT,
5878 fee_proportional_millionths: 0,
5879 excess_data: Vec::new()
5883 // Attempt to route more than available results in a failure.
5884 let route_params = RouteParameters::from_payment_params_and_value(
5885 payment_params.clone(), 210_000);
5886 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5887 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5888 &scorer, &Default::default(), &random_seed_bytes) {
5889 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5890 } else { panic!(); }
5894 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5895 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5896 max_total_routing_fee_msat: Some(149_999) };
5897 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5898 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5899 &scorer, &Default::default(), &random_seed_bytes) {
5900 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5901 } else { panic!(); }
5905 // Now, attempt to route 200 sats (exact amount we can route).
5906 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5907 max_total_routing_fee_msat: Some(150_000) };
5908 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5909 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5910 assert_eq!(route.paths.len(), 2);
5912 let mut total_amount_paid_msat = 0;
5913 for path in &route.paths {
5914 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5915 total_amount_paid_msat += path.final_value_msat();
5917 assert_eq!(total_amount_paid_msat, 200_000);
5918 assert_eq!(route.get_total_fees(), 150_000);
5923 fn mpp_with_last_hops() {
5924 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5925 // via a single last-hop route hint, we'd fail to route if we first collected routes
5926 // totaling close but not quite enough to fund the full payment.
5928 // This was because we considered last-hop hints to have exactly the sought payment amount
5929 // instead of the amount we were trying to collect, needlessly limiting our path searching
5930 // at the very first hop.
5932 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5933 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5934 // to only have the remaining to-collect amount in available liquidity.
5936 // This bug appeared in production in some specific channel configurations.
5937 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5938 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5939 let scorer = ln_test_utils::TestScorer::new();
5940 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5941 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5942 let config = UserConfig::default();
5943 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
5944 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
5945 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5946 src_node_id: nodes[2],
5947 short_channel_id: 42,
5948 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5949 cltv_expiry_delta: 42,
5950 htlc_minimum_msat: None,
5951 htlc_maximum_msat: None,
5952 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5954 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5955 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5956 // would first use the no-fee route and then fail to find a path along the second route as
5957 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5958 // under 5% of our payment amount.
5959 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5960 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5961 short_channel_id: 1,
5964 cltv_expiry_delta: (5 << 4) | 5,
5965 htlc_minimum_msat: 0,
5966 htlc_maximum_msat: 99_000,
5967 fee_base_msat: u32::max_value(),
5968 fee_proportional_millionths: u32::max_value(),
5969 excess_data: Vec::new()
5971 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5972 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5973 short_channel_id: 2,
5976 cltv_expiry_delta: (5 << 4) | 3,
5977 htlc_minimum_msat: 0,
5978 htlc_maximum_msat: 99_000,
5979 fee_base_msat: u32::max_value(),
5980 fee_proportional_millionths: u32::max_value(),
5981 excess_data: Vec::new()
5983 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5984 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5985 short_channel_id: 4,
5988 cltv_expiry_delta: (4 << 4) | 1,
5989 htlc_minimum_msat: 0,
5990 htlc_maximum_msat: MAX_VALUE_MSAT,
5992 fee_proportional_millionths: 0,
5993 excess_data: Vec::new()
5995 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5996 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5997 short_channel_id: 13,
5999 flags: 0|2, // Channel disabled
6000 cltv_expiry_delta: (13 << 4) | 1,
6001 htlc_minimum_msat: 0,
6002 htlc_maximum_msat: MAX_VALUE_MSAT,
6004 fee_proportional_millionths: 2000000,
6005 excess_data: Vec::new()
6008 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
6010 let route_params = RouteParameters::from_payment_params_and_value(
6011 payment_params, 100_000);
6012 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6013 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6014 assert_eq!(route.paths.len(), 2);
6015 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
6016 // Paths are manually ordered ordered by SCID, so:
6017 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
6018 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
6019 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
6020 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
6021 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
6022 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
6023 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
6024 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
6025 assert_eq!(route.get_total_fees(), 1);
6026 assert_eq!(route.get_total_amount(), 100_000);
6030 fn drop_lowest_channel_mpp_route_test() {
6031 // This test checks that low-capacity channel is dropped when after
6032 // path finding we realize that we found more capacity than we need.
6033 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6034 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6035 let scorer = ln_test_utils::TestScorer::new();
6036 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6037 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6038 let config = UserConfig::default();
6039 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6040 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6042 .with_max_channel_saturation_power_of_half(0);
6044 // We need a route consisting of 3 paths:
6045 // From our node to node2 via node0, node7, node1 (three paths one hop each).
6047 // The first and the second paths should be sufficient, but the third should be
6048 // cheaper, so that we select it but drop later.
6050 // First, we set limits on these (previously unlimited) channels.
6051 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
6053 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
6054 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6055 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6056 short_channel_id: 1,
6059 cltv_expiry_delta: 0,
6060 htlc_minimum_msat: 0,
6061 htlc_maximum_msat: 100_000,
6063 fee_proportional_millionths: 0,
6064 excess_data: Vec::new()
6066 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6067 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6068 short_channel_id: 3,
6071 cltv_expiry_delta: 0,
6072 htlc_minimum_msat: 0,
6073 htlc_maximum_msat: 50_000,
6075 fee_proportional_millionths: 0,
6076 excess_data: Vec::new()
6079 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
6080 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6081 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6082 short_channel_id: 12,
6085 cltv_expiry_delta: 0,
6086 htlc_minimum_msat: 0,
6087 htlc_maximum_msat: 60_000,
6089 fee_proportional_millionths: 0,
6090 excess_data: Vec::new()
6092 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6093 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6094 short_channel_id: 13,
6097 cltv_expiry_delta: 0,
6098 htlc_minimum_msat: 0,
6099 htlc_maximum_msat: 60_000,
6101 fee_proportional_millionths: 0,
6102 excess_data: Vec::new()
6105 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
6106 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6107 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6108 short_channel_id: 2,
6111 cltv_expiry_delta: 0,
6112 htlc_minimum_msat: 0,
6113 htlc_maximum_msat: 20_000,
6115 fee_proportional_millionths: 0,
6116 excess_data: Vec::new()
6118 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6119 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6120 short_channel_id: 4,
6123 cltv_expiry_delta: 0,
6124 htlc_minimum_msat: 0,
6125 htlc_maximum_msat: 20_000,
6127 fee_proportional_millionths: 0,
6128 excess_data: Vec::new()
6132 // Attempt to route more than available results in a failure.
6133 let route_params = RouteParameters::from_payment_params_and_value(
6134 payment_params.clone(), 150_000);
6135 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6136 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6137 &scorer, &Default::default(), &random_seed_bytes) {
6138 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6139 } else { panic!(); }
6143 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
6144 // Our algorithm should provide us with these 3 paths.
6145 let route_params = RouteParameters::from_payment_params_and_value(
6146 payment_params.clone(), 125_000);
6147 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6148 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6149 assert_eq!(route.paths.len(), 3);
6150 let mut total_amount_paid_msat = 0;
6151 for path in &route.paths {
6152 assert_eq!(path.hops.len(), 2);
6153 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6154 total_amount_paid_msat += path.final_value_msat();
6156 assert_eq!(total_amount_paid_msat, 125_000);
6160 // Attempt to route without the last small cheap channel
6161 let route_params = RouteParameters::from_payment_params_and_value(
6162 payment_params, 90_000);
6163 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6164 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6165 assert_eq!(route.paths.len(), 2);
6166 let mut total_amount_paid_msat = 0;
6167 for path in &route.paths {
6168 assert_eq!(path.hops.len(), 2);
6169 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6170 total_amount_paid_msat += path.final_value_msat();
6172 assert_eq!(total_amount_paid_msat, 90_000);
6177 fn min_criteria_consistency() {
6178 // Test that we don't use an inconsistent metric between updating and walking nodes during
6179 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
6180 // was updated with a different criterion from the heap sorting, resulting in loops in
6181 // calculated paths. We test for that specific case here.
6183 // We construct a network that looks like this:
6185 // node2 -1(3)2- node3
6189 // node1 -1(5)2- node4 -1(1)2- node6
6195 // We create a loop on the side of our real path - our destination is node 6, with a
6196 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
6197 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
6198 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
6199 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
6200 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
6201 // "previous hop" being set to node 3, creating a loop in the path.
6202 let secp_ctx = Secp256k1::new();
6203 let logger = Arc::new(ln_test_utils::TestLogger::new());
6204 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6205 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
6206 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6207 let scorer = ln_test_utils::TestScorer::new();
6208 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6209 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6210 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
6212 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
6213 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6214 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6215 short_channel_id: 6,
6218 cltv_expiry_delta: (6 << 4) | 0,
6219 htlc_minimum_msat: 0,
6220 htlc_maximum_msat: MAX_VALUE_MSAT,
6222 fee_proportional_millionths: 0,
6223 excess_data: Vec::new()
6225 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
6227 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6228 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6229 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6230 short_channel_id: 5,
6233 cltv_expiry_delta: (5 << 4) | 0,
6234 htlc_minimum_msat: 0,
6235 htlc_maximum_msat: MAX_VALUE_MSAT,
6237 fee_proportional_millionths: 0,
6238 excess_data: Vec::new()
6240 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
6242 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
6243 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6244 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6245 short_channel_id: 4,
6248 cltv_expiry_delta: (4 << 4) | 0,
6249 htlc_minimum_msat: 0,
6250 htlc_maximum_msat: MAX_VALUE_MSAT,
6252 fee_proportional_millionths: 0,
6253 excess_data: Vec::new()
6255 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6257 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6258 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
6259 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6260 short_channel_id: 3,
6263 cltv_expiry_delta: (3 << 4) | 0,
6264 htlc_minimum_msat: 0,
6265 htlc_maximum_msat: MAX_VALUE_MSAT,
6267 fee_proportional_millionths: 0,
6268 excess_data: Vec::new()
6270 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6272 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6273 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
6274 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6275 short_channel_id: 2,
6278 cltv_expiry_delta: (2 << 4) | 0,
6279 htlc_minimum_msat: 0,
6280 htlc_maximum_msat: MAX_VALUE_MSAT,
6282 fee_proportional_millionths: 0,
6283 excess_data: Vec::new()
6286 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6287 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6288 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6289 short_channel_id: 1,
6292 cltv_expiry_delta: (1 << 4) | 0,
6293 htlc_minimum_msat: 100,
6294 htlc_maximum_msat: MAX_VALUE_MSAT,
6296 fee_proportional_millionths: 0,
6297 excess_data: Vec::new()
6299 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6302 // Now ensure the route flows simply over nodes 1 and 4 to 6.
6303 let route_params = RouteParameters::from_payment_params_and_value(
6304 payment_params, 10_000);
6305 let route = get_route(&our_id, &route_params, &network.read_only(), None,
6306 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6307 assert_eq!(route.paths.len(), 1);
6308 assert_eq!(route.paths[0].hops.len(), 3);
6310 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6311 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6312 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6313 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6314 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6315 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6317 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6318 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6319 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6320 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6321 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6322 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6324 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6325 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6326 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6327 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6328 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6329 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6335 fn exact_fee_liquidity_limit() {
6336 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6337 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6338 // we calculated fees on a higher value, resulting in us ignoring such paths.
6339 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6340 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6341 let scorer = ln_test_utils::TestScorer::new();
6342 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6343 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6344 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6346 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6348 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6349 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6350 short_channel_id: 2,
6353 cltv_expiry_delta: 0,
6354 htlc_minimum_msat: 0,
6355 htlc_maximum_msat: 85_000,
6357 fee_proportional_millionths: 0,
6358 excess_data: Vec::new()
6361 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6362 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6363 short_channel_id: 12,
6366 cltv_expiry_delta: (4 << 4) | 1,
6367 htlc_minimum_msat: 0,
6368 htlc_maximum_msat: 270_000,
6370 fee_proportional_millionths: 1000000,
6371 excess_data: Vec::new()
6375 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6376 // 200% fee charged channel 13 in the 1-to-2 direction.
6377 let mut route_params = RouteParameters::from_payment_params_and_value(
6378 payment_params, 90_000);
6379 route_params.max_total_routing_fee_msat = Some(90_000*2);
6380 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6381 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6382 assert_eq!(route.paths.len(), 1);
6383 assert_eq!(route.paths[0].hops.len(), 2);
6385 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6386 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6387 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6388 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6389 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6390 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6392 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6393 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6394 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6395 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6396 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6397 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6402 fn htlc_max_reduction_below_min() {
6403 // Test that if, while walking the graph, we reduce the value being sent to meet an
6404 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6405 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6406 // resulting in us thinking there is no possible path, even if other paths exist.
6407 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6408 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6409 let scorer = ln_test_utils::TestScorer::new();
6410 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6411 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6412 let config = UserConfig::default();
6413 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6414 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6417 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6418 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6419 // then try to send 90_000.
6420 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6421 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6422 short_channel_id: 2,
6425 cltv_expiry_delta: 0,
6426 htlc_minimum_msat: 0,
6427 htlc_maximum_msat: 80_000,
6429 fee_proportional_millionths: 0,
6430 excess_data: Vec::new()
6432 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6433 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6434 short_channel_id: 4,
6437 cltv_expiry_delta: (4 << 4) | 1,
6438 htlc_minimum_msat: 90_000,
6439 htlc_maximum_msat: MAX_VALUE_MSAT,
6441 fee_proportional_millionths: 0,
6442 excess_data: Vec::new()
6446 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6447 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6448 // expensive) channels 12-13 path.
6449 let mut route_params = RouteParameters::from_payment_params_and_value(
6450 payment_params, 90_000);
6451 route_params.max_total_routing_fee_msat = Some(90_000*2);
6452 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6453 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6454 assert_eq!(route.paths.len(), 1);
6455 assert_eq!(route.paths[0].hops.len(), 2);
6457 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6458 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6459 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6460 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6461 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6462 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6464 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6465 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6466 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6467 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6468 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6469 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6474 fn multiple_direct_first_hops() {
6475 // Previously we'd only ever considered one first hop path per counterparty.
6476 // However, as we don't restrict users to one channel per peer, we really need to support
6477 // looking at all first hop paths.
6478 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6479 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6480 // route over multiple channels with the same first hop.
6481 let secp_ctx = Secp256k1::new();
6482 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6483 let logger = Arc::new(ln_test_utils::TestLogger::new());
6484 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6485 let scorer = ln_test_utils::TestScorer::new();
6486 let config = UserConfig::default();
6487 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6488 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6490 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6491 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6494 let route_params = RouteParameters::from_payment_params_and_value(
6495 payment_params.clone(), 100_000);
6496 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6497 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6498 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6499 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6500 assert_eq!(route.paths.len(), 1);
6501 assert_eq!(route.paths[0].hops.len(), 1);
6503 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6504 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6505 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6508 let route_params = RouteParameters::from_payment_params_and_value(
6509 payment_params.clone(), 100_000);
6510 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6511 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6512 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6513 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6514 assert_eq!(route.paths.len(), 2);
6515 assert_eq!(route.paths[0].hops.len(), 1);
6516 assert_eq!(route.paths[1].hops.len(), 1);
6518 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6519 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6521 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6522 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6524 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6525 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6529 // If we have a bunch of outbound channels to the same node, where most are not
6530 // sufficient to pay the full payment, but one is, we should default to just using the
6531 // one single channel that has sufficient balance, avoiding MPP.
6533 // If we have several options above the 3xpayment value threshold, we should pick the
6534 // smallest of them, avoiding further fragmenting our available outbound balance to
6536 let route_params = RouteParameters::from_payment_params_and_value(
6537 payment_params, 100_000);
6538 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6539 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6540 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6541 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6542 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6543 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6544 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6545 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6546 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6547 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6548 assert_eq!(route.paths.len(), 1);
6549 assert_eq!(route.paths[0].hops.len(), 1);
6551 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6552 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6553 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6558 fn prefers_shorter_route_with_higher_fees() {
6559 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6560 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6561 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6563 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6564 let scorer = ln_test_utils::TestScorer::new();
6565 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6566 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6567 let route_params = RouteParameters::from_payment_params_and_value(
6568 payment_params.clone(), 100);
6569 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6570 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6571 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6573 assert_eq!(route.get_total_fees(), 100);
6574 assert_eq!(route.get_total_amount(), 100);
6575 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6577 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6578 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6579 let scorer = FixedPenaltyScorer::with_penalty(100);
6580 let route_params = RouteParameters::from_payment_params_and_value(
6581 payment_params, 100);
6582 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6583 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6584 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6586 assert_eq!(route.get_total_fees(), 300);
6587 assert_eq!(route.get_total_amount(), 100);
6588 assert_eq!(path, vec![2, 4, 7, 10]);
6591 struct BadChannelScorer {
6592 short_channel_id: u64,
6596 impl Writeable for BadChannelScorer {
6597 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6599 impl ScoreLookUp for BadChannelScorer {
6600 type ScoreParams = ();
6601 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6602 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6606 struct BadNodeScorer {
6611 impl Writeable for BadNodeScorer {
6612 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6615 impl ScoreLookUp for BadNodeScorer {
6616 type ScoreParams = ();
6617 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6618 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6623 fn avoids_routing_through_bad_channels_and_nodes() {
6624 let (secp_ctx, network, _, _, logger) = build_graph();
6625 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6626 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6627 let network_graph = network.read_only();
6629 // A path to nodes[6] exists when no penalties are applied to any channel.
6630 let scorer = ln_test_utils::TestScorer::new();
6631 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6632 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6633 let route_params = RouteParameters::from_payment_params_and_value(
6634 payment_params, 100);
6635 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6636 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6637 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6639 assert_eq!(route.get_total_fees(), 100);
6640 assert_eq!(route.get_total_amount(), 100);
6641 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6643 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6644 let scorer = BadChannelScorer { short_channel_id: 6 };
6645 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6646 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6647 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6649 assert_eq!(route.get_total_fees(), 300);
6650 assert_eq!(route.get_total_amount(), 100);
6651 assert_eq!(path, vec![2, 4, 7, 10]);
6653 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6654 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6655 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6656 &scorer, &Default::default(), &random_seed_bytes) {
6657 Err(LightningError { err, .. } ) => {
6658 assert_eq!(err, "Failed to find a path to the given destination");
6660 Ok(_) => panic!("Expected error"),
6665 fn total_fees_single_path() {
6667 paths: vec![Path { hops: vec![
6669 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6670 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6671 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6674 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6675 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6676 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6679 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6680 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6681 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6683 ], blinded_tail: None }],
6687 assert_eq!(route.get_total_fees(), 250);
6688 assert_eq!(route.get_total_amount(), 225);
6692 fn total_fees_multi_path() {
6694 paths: vec![Path { hops: vec![
6696 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6697 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6698 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6701 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6702 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6703 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6705 ], blinded_tail: None }, Path { hops: vec![
6707 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6708 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6709 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6712 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6713 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6714 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6716 ], blinded_tail: None }],
6720 assert_eq!(route.get_total_fees(), 200);
6721 assert_eq!(route.get_total_amount(), 300);
6725 fn total_empty_route_no_panic() {
6726 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6727 // would both panic if the route was completely empty. We test to ensure they return 0
6728 // here, even though its somewhat nonsensical as a route.
6729 let route = Route { paths: Vec::new(), route_params: None };
6731 assert_eq!(route.get_total_fees(), 0);
6732 assert_eq!(route.get_total_amount(), 0);
6736 fn limits_total_cltv_delta() {
6737 let (secp_ctx, network, _, _, logger) = build_graph();
6738 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6739 let network_graph = network.read_only();
6741 let scorer = ln_test_utils::TestScorer::new();
6743 // Make sure that generally there is at least one route available
6744 let feasible_max_total_cltv_delta = 1008;
6745 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6746 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6747 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6748 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6749 let route_params = RouteParameters::from_payment_params_and_value(
6750 feasible_payment_params, 100);
6751 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6752 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6753 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6754 assert_ne!(path.len(), 0);
6756 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6757 let fail_max_total_cltv_delta = 23;
6758 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6759 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6760 let route_params = RouteParameters::from_payment_params_and_value(
6761 fail_payment_params, 100);
6762 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6763 &Default::default(), &random_seed_bytes)
6765 Err(LightningError { err, .. } ) => {
6766 assert_eq!(err, "Failed to find a path to the given destination");
6768 Ok(_) => panic!("Expected error"),
6773 fn avoids_recently_failed_paths() {
6774 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6775 // randomly inserting channels into it until we can't find a route anymore.
6776 let (secp_ctx, network, _, _, logger) = build_graph();
6777 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6778 let network_graph = network.read_only();
6780 let scorer = ln_test_utils::TestScorer::new();
6781 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6782 .with_max_path_count(1);
6783 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6784 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6786 // We should be able to find a route initially, and then after we fail a few random
6787 // channels eventually we won't be able to any longer.
6788 let route_params = RouteParameters::from_payment_params_and_value(
6789 payment_params.clone(), 100);
6790 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6791 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6793 let route_params = RouteParameters::from_payment_params_and_value(
6794 payment_params.clone(), 100);
6795 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6796 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6798 for chan in route.paths[0].hops.iter() {
6799 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6801 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6802 % route.paths[0].hops.len();
6803 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6809 fn limits_path_length() {
6810 let (secp_ctx, network, _, _, logger) = build_line_graph();
6811 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6812 let network_graph = network.read_only();
6814 let scorer = ln_test_utils::TestScorer::new();
6815 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6816 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6818 // First check we can actually create a long route on this graph.
6819 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6820 let route_params = RouteParameters::from_payment_params_and_value(
6821 feasible_payment_params, 100);
6822 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6823 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6824 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6825 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6827 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6828 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6829 let route_params = RouteParameters::from_payment_params_and_value(
6830 fail_payment_params, 100);
6831 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6832 &Default::default(), &random_seed_bytes)
6834 Err(LightningError { err, .. } ) => {
6835 assert_eq!(err, "Failed to find a path to the given destination");
6837 Ok(_) => panic!("Expected error"),
6842 fn adds_and_limits_cltv_offset() {
6843 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6844 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6846 let scorer = ln_test_utils::TestScorer::new();
6848 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6849 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6850 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6851 let route_params = RouteParameters::from_payment_params_and_value(
6852 payment_params.clone(), 100);
6853 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6854 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6855 assert_eq!(route.paths.len(), 1);
6857 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6859 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6860 let mut route_default = route.clone();
6861 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6862 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6863 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6864 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6865 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6867 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6868 let mut route_limited = route.clone();
6869 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6870 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6871 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6872 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6873 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6877 fn adds_plausible_cltv_offset() {
6878 let (secp_ctx, network, _, _, logger) = build_graph();
6879 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6880 let network_graph = network.read_only();
6881 let network_nodes = network_graph.nodes();
6882 let network_channels = network_graph.channels();
6883 let scorer = ln_test_utils::TestScorer::new();
6884 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6885 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6886 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6888 let route_params = RouteParameters::from_payment_params_and_value(
6889 payment_params.clone(), 100);
6890 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6891 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6892 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6894 let mut path_plausibility = vec![];
6896 for p in route.paths {
6897 // 1. Select random observation point
6898 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6899 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6901 prng.process_in_place(&mut random_bytes);
6902 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6903 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6905 // 2. Calculate what CLTV expiry delta we would observe there
6906 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6908 // 3. Starting from the observation point, find candidate paths
6909 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6910 candidates.push_back((observation_point, vec![]));
6912 let mut found_plausible_candidate = false;
6914 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6915 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6916 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6917 found_plausible_candidate = true;
6918 break 'candidate_loop;
6922 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6923 for channel_id in &cur_node.channels {
6924 if let Some(channel_info) = network_channels.get(&channel_id) {
6925 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6926 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6927 if cur_path_cltv_deltas.iter().sum::<u32>()
6928 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6929 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6930 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6931 candidates.push_back((*next_id, new_path_cltv_deltas));
6939 path_plausibility.push(found_plausible_candidate);
6941 assert!(path_plausibility.iter().all(|x| *x));
6945 fn builds_correct_path_from_hops() {
6946 let (secp_ctx, network, _, _, logger) = build_graph();
6947 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6948 let network_graph = network.read_only();
6950 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6951 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6953 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6954 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6955 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6956 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6957 Arc::clone(&logger), &random_seed_bytes).unwrap();
6958 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6959 assert_eq!(hops.len(), route.paths[0].hops.len());
6960 for (idx, hop_pubkey) in hops.iter().enumerate() {
6961 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6966 fn avoids_saturating_channels() {
6967 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6968 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6969 let decay_params = ProbabilisticScoringDecayParameters::default();
6970 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6972 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6973 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6974 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6975 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6976 short_channel_id: 4,
6979 cltv_expiry_delta: (4 << 4) | 1,
6980 htlc_minimum_msat: 0,
6981 htlc_maximum_msat: 250_000_000,
6983 fee_proportional_millionths: 0,
6984 excess_data: Vec::new()
6986 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6987 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6988 short_channel_id: 13,
6991 cltv_expiry_delta: (13 << 4) | 1,
6992 htlc_minimum_msat: 0,
6993 htlc_maximum_msat: 250_000_000,
6995 fee_proportional_millionths: 0,
6996 excess_data: Vec::new()
6999 let config = UserConfig::default();
7000 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
7001 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7003 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7004 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7005 // 100,000 sats is less than the available liquidity on each channel, set above.
7006 let route_params = RouteParameters::from_payment_params_and_value(
7007 payment_params, 100_000_000);
7008 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
7009 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
7010 assert_eq!(route.paths.len(), 2);
7011 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
7012 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
7015 #[cfg(feature = "std")]
7016 pub(super) fn random_init_seed() -> u64 {
7017 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
7018 use core::hash::{BuildHasher, Hasher};
7019 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
7020 println!("Using seed of {}", seed);
7025 #[cfg(feature = "std")]
7026 fn generate_routes() {
7027 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
7029 let logger = ln_test_utils::TestLogger::new();
7030 let graph = match super::bench_utils::read_network_graph(&logger) {
7038 let params = ProbabilisticScoringFeeParameters::default();
7039 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
7040 let features = super::Bolt11InvoiceFeatures::empty();
7042 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7046 #[cfg(feature = "std")]
7047 fn generate_routes_mpp() {
7048 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
7050 let logger = ln_test_utils::TestLogger::new();
7051 let graph = match super::bench_utils::read_network_graph(&logger) {
7059 let params = ProbabilisticScoringFeeParameters::default();
7060 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
7061 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7063 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7067 #[cfg(feature = "std")]
7068 fn generate_large_mpp_routes() {
7069 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
7071 let logger = ln_test_utils::TestLogger::new();
7072 let graph = match super::bench_utils::read_network_graph(&logger) {
7080 let params = ProbabilisticScoringFeeParameters::default();
7081 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
7082 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7084 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
7088 fn honors_manual_penalties() {
7089 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
7090 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7092 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7093 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7095 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
7096 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
7098 // First check set manual penalties are returned by the scorer.
7099 let usage = ChannelUsage {
7101 inflight_htlc_msat: 0,
7102 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
7104 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
7105 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
7106 let network_graph = network_graph.read_only();
7107 let channels = network_graph.channels();
7108 let channel = channels.get(&5).unwrap();
7109 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
7110 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop(PublicHopCandidate {
7112 short_channel_id: 5,
7114 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
7116 // Then check we can get a normal route
7117 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
7118 let route_params = RouteParameters::from_payment_params_and_value(
7119 payment_params, 100);
7120 let route = get_route(&our_id, &route_params, &network_graph, None,
7121 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
7122 assert!(route.is_ok());
7124 // Then check that we can't get a route if we ban an intermediate node.
7125 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
7126 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7127 assert!(route.is_err());
7129 // Finally make sure we can route again, when we remove the ban.
7130 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
7131 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7132 assert!(route.is_ok());
7136 fn abide_by_route_hint_max_htlc() {
7137 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
7138 // params in the final route.
7139 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7140 let netgraph = network_graph.read_only();
7141 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7142 let scorer = ln_test_utils::TestScorer::new();
7143 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7144 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7145 let config = UserConfig::default();
7147 let max_htlc_msat = 50_000;
7148 let route_hint_1 = RouteHint(vec![RouteHintHop {
7149 src_node_id: nodes[2],
7150 short_channel_id: 42,
7153 proportional_millionths: 0,
7155 cltv_expiry_delta: 10,
7156 htlc_minimum_msat: None,
7157 htlc_maximum_msat: Some(max_htlc_msat),
7159 let dest_node_id = ln_test_utils::pubkey(42);
7160 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7161 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
7162 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7165 // Make sure we'll error if our route hints don't have enough liquidity according to their
7166 // htlc_maximum_msat.
7167 let mut route_params = RouteParameters::from_payment_params_and_value(
7168 payment_params, max_htlc_msat + 1);
7169 route_params.max_total_routing_fee_msat = None;
7170 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
7171 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
7174 assert_eq!(err, "Failed to find a sufficient route to the given destination");
7175 } else { panic!(); }
7177 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
7178 let mut route_hint_2 = route_hint_1.clone();
7179 route_hint_2.0[0].short_channel_id = 43;
7180 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7181 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7182 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7184 let mut route_params = RouteParameters::from_payment_params_and_value(
7185 payment_params, max_htlc_msat + 1);
7186 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
7187 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
7188 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7189 assert_eq!(route.paths.len(), 2);
7190 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7191 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7195 fn direct_channel_to_hints_with_max_htlc() {
7196 // Check that if we have a first hop channel peer that's connected to multiple provided route
7197 // hints, that we properly split the payment between the route hints if needed.
7198 let logger = Arc::new(ln_test_utils::TestLogger::new());
7199 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7200 let scorer = ln_test_utils::TestScorer::new();
7201 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7202 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7203 let config = UserConfig::default();
7205 let our_node_id = ln_test_utils::pubkey(42);
7206 let intermed_node_id = ln_test_utils::pubkey(43);
7207 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7209 let amt_msat = 900_000;
7210 let max_htlc_msat = 500_000;
7211 let route_hint_1 = RouteHint(vec![RouteHintHop {
7212 src_node_id: intermed_node_id,
7213 short_channel_id: 44,
7216 proportional_millionths: 0,
7218 cltv_expiry_delta: 10,
7219 htlc_minimum_msat: None,
7220 htlc_maximum_msat: Some(max_htlc_msat),
7222 src_node_id: intermed_node_id,
7223 short_channel_id: 45,
7226 proportional_millionths: 0,
7228 cltv_expiry_delta: 10,
7229 htlc_minimum_msat: None,
7230 // Check that later route hint max htlcs don't override earlier ones
7231 htlc_maximum_msat: Some(max_htlc_msat - 50),
7233 let mut route_hint_2 = route_hint_1.clone();
7234 route_hint_2.0[0].short_channel_id = 46;
7235 route_hint_2.0[1].short_channel_id = 47;
7236 let dest_node_id = ln_test_utils::pubkey(44);
7237 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7238 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7239 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7242 let route_params = RouteParameters::from_payment_params_and_value(
7243 payment_params, amt_msat);
7244 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7245 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7246 &Default::default(), &random_seed_bytes).unwrap();
7247 assert_eq!(route.paths.len(), 2);
7248 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7249 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7250 assert_eq!(route.get_total_amount(), amt_msat);
7252 // Re-run but with two first hop channels connected to the same route hint peers that must be
7254 let first_hops = vec![
7255 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7256 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7258 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7259 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7260 &Default::default(), &random_seed_bytes).unwrap();
7261 assert_eq!(route.paths.len(), 2);
7262 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7263 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7264 assert_eq!(route.get_total_amount(), amt_msat);
7266 // Make sure this works for blinded route hints.
7267 let blinded_path = BlindedPath {
7268 introduction_node: IntroductionNode::NodeId(intermed_node_id),
7269 blinding_point: ln_test_utils::pubkey(42),
7271 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
7272 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
7275 let blinded_payinfo = BlindedPayInfo {
7277 fee_proportional_millionths: 0,
7278 htlc_minimum_msat: 1,
7279 htlc_maximum_msat: max_htlc_msat,
7280 cltv_expiry_delta: 10,
7281 features: BlindedHopFeatures::empty(),
7283 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7284 let payment_params = PaymentParameters::blinded(vec![
7285 (blinded_payinfo.clone(), blinded_path.clone()),
7286 (blinded_payinfo.clone(), blinded_path.clone())])
7287 .with_bolt12_features(bolt12_features).unwrap();
7288 let route_params = RouteParameters::from_payment_params_and_value(
7289 payment_params, amt_msat);
7290 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7291 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7292 &Default::default(), &random_seed_bytes).unwrap();
7293 assert_eq!(route.paths.len(), 2);
7294 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7295 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7296 assert_eq!(route.get_total_amount(), amt_msat);
7300 fn blinded_route_ser() {
7301 let blinded_path_1 = BlindedPath {
7302 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(42)),
7303 blinding_point: ln_test_utils::pubkey(43),
7305 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7306 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7309 let blinded_path_2 = BlindedPath {
7310 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(46)),
7311 blinding_point: ln_test_utils::pubkey(47),
7313 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7314 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7317 // (De)serialize a Route with 1 blinded path out of two total paths.
7318 let mut route = Route { paths: vec![Path {
7319 hops: vec![RouteHop {
7320 pubkey: ln_test_utils::pubkey(50),
7321 node_features: NodeFeatures::empty(),
7322 short_channel_id: 42,
7323 channel_features: ChannelFeatures::empty(),
7325 cltv_expiry_delta: 0,
7326 maybe_announced_channel: true,
7328 blinded_tail: Some(BlindedTail {
7329 hops: blinded_path_1.blinded_hops,
7330 blinding_point: blinded_path_1.blinding_point,
7331 excess_final_cltv_expiry_delta: 40,
7332 final_value_msat: 100,
7334 hops: vec![RouteHop {
7335 pubkey: ln_test_utils::pubkey(51),
7336 node_features: NodeFeatures::empty(),
7337 short_channel_id: 43,
7338 channel_features: ChannelFeatures::empty(),
7340 cltv_expiry_delta: 0,
7341 maybe_announced_channel: true,
7342 }], blinded_tail: None }],
7345 let encoded_route = route.encode();
7346 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7347 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7348 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7350 // (De)serialize a Route with two paths, each containing a blinded tail.
7351 route.paths[1].blinded_tail = Some(BlindedTail {
7352 hops: blinded_path_2.blinded_hops,
7353 blinding_point: blinded_path_2.blinding_point,
7354 excess_final_cltv_expiry_delta: 41,
7355 final_value_msat: 101,
7357 let encoded_route = route.encode();
7358 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7359 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7360 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7364 fn blinded_path_inflight_processing() {
7365 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7366 // account for the blinded tail's final amount_msat.
7367 let mut inflight_htlcs = InFlightHtlcs::new();
7368 let blinded_path = BlindedPath {
7369 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(43)),
7370 blinding_point: ln_test_utils::pubkey(48),
7371 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7374 hops: vec![RouteHop {
7375 pubkey: ln_test_utils::pubkey(42),
7376 node_features: NodeFeatures::empty(),
7377 short_channel_id: 42,
7378 channel_features: ChannelFeatures::empty(),
7380 cltv_expiry_delta: 0,
7381 maybe_announced_channel: false,
7384 pubkey: ln_test_utils::pubkey(43),
7385 node_features: NodeFeatures::empty(),
7386 short_channel_id: 43,
7387 channel_features: ChannelFeatures::empty(),
7389 cltv_expiry_delta: 0,
7390 maybe_announced_channel: false,
7392 blinded_tail: Some(BlindedTail {
7393 hops: blinded_path.blinded_hops,
7394 blinding_point: blinded_path.blinding_point,
7395 excess_final_cltv_expiry_delta: 0,
7396 final_value_msat: 200,
7399 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7400 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7401 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7405 fn blinded_path_cltv_shadow_offset() {
7406 // Make sure we add a shadow offset when sending to blinded paths.
7407 let blinded_path = BlindedPath {
7408 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(43)),
7409 blinding_point: ln_test_utils::pubkey(44),
7411 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7412 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7415 let mut route = Route { paths: vec![Path {
7416 hops: vec![RouteHop {
7417 pubkey: ln_test_utils::pubkey(42),
7418 node_features: NodeFeatures::empty(),
7419 short_channel_id: 42,
7420 channel_features: ChannelFeatures::empty(),
7422 cltv_expiry_delta: 0,
7423 maybe_announced_channel: false,
7426 pubkey: ln_test_utils::pubkey(43),
7427 node_features: NodeFeatures::empty(),
7428 short_channel_id: 43,
7429 channel_features: ChannelFeatures::empty(),
7431 cltv_expiry_delta: 0,
7432 maybe_announced_channel: false,
7435 blinded_tail: Some(BlindedTail {
7436 hops: blinded_path.blinded_hops,
7437 blinding_point: blinded_path.blinding_point,
7438 excess_final_cltv_expiry_delta: 0,
7439 final_value_msat: 200,
7441 }], route_params: None};
7443 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7444 let (_, network_graph, _, _, _) = build_line_graph();
7445 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7446 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7447 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7451 fn simple_blinded_route_hints() {
7452 do_simple_blinded_route_hints(1);
7453 do_simple_blinded_route_hints(2);
7454 do_simple_blinded_route_hints(3);
7457 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7458 // Check that we can generate a route to a blinded path with the expected hops.
7459 let (secp_ctx, network, _, _, logger) = build_graph();
7460 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7461 let network_graph = network.read_only();
7463 let scorer = ln_test_utils::TestScorer::new();
7464 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7465 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7467 let mut blinded_path = BlindedPath {
7468 introduction_node: IntroductionNode::NodeId(nodes[2]),
7469 blinding_point: ln_test_utils::pubkey(42),
7470 blinded_hops: Vec::with_capacity(num_blinded_hops),
7472 for i in 0..num_blinded_hops {
7473 blinded_path.blinded_hops.push(
7474 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7477 let blinded_payinfo = BlindedPayInfo {
7479 fee_proportional_millionths: 500,
7480 htlc_minimum_msat: 1000,
7481 htlc_maximum_msat: 100_000_000,
7482 cltv_expiry_delta: 15,
7483 features: BlindedHopFeatures::empty(),
7486 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7487 let route_params = RouteParameters::from_payment_params_and_value(
7488 payment_params, 1001);
7489 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7490 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7491 assert_eq!(route.paths.len(), 1);
7492 assert_eq!(route.paths[0].hops.len(), 2);
7494 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7495 assert_eq!(tail.hops, blinded_path.blinded_hops);
7496 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7497 assert_eq!(tail.final_value_msat, 1001);
7499 let final_hop = route.paths[0].hops.last().unwrap();
7501 NodeId::from_pubkey(&final_hop.pubkey),
7502 *blinded_path.public_introduction_node_id(&network_graph).unwrap()
7504 if tail.hops.len() > 1 {
7505 assert_eq!(final_hop.fee_msat,
7506 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7507 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7509 assert_eq!(final_hop.fee_msat, 0);
7510 assert_eq!(final_hop.cltv_expiry_delta, 0);
7515 fn blinded_path_routing_errors() {
7516 // Check that we can generate a route to a blinded path with the expected hops.
7517 let (secp_ctx, network, _, _, logger) = build_graph();
7518 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7519 let network_graph = network.read_only();
7521 let scorer = ln_test_utils::TestScorer::new();
7522 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7523 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7525 let mut invalid_blinded_path = BlindedPath {
7526 introduction_node: IntroductionNode::NodeId(nodes[2]),
7527 blinding_point: ln_test_utils::pubkey(42),
7529 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7532 let blinded_payinfo = BlindedPayInfo {
7534 fee_proportional_millionths: 500,
7535 htlc_minimum_msat: 1000,
7536 htlc_maximum_msat: 100_000_000,
7537 cltv_expiry_delta: 15,
7538 features: BlindedHopFeatures::empty(),
7541 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7542 invalid_blinded_path_2.introduction_node = IntroductionNode::NodeId(ln_test_utils::pubkey(45));
7543 let payment_params = PaymentParameters::blinded(vec![
7544 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7545 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7546 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7547 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7548 &scorer, &Default::default(), &random_seed_bytes)
7550 Err(LightningError { err, .. }) => {
7551 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7553 _ => panic!("Expected error")
7556 invalid_blinded_path.introduction_node = IntroductionNode::NodeId(our_id);
7557 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7558 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7559 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7560 &Default::default(), &random_seed_bytes)
7562 Err(LightningError { err, .. }) => {
7563 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7565 _ => panic!("Expected error")
7568 invalid_blinded_path.introduction_node = IntroductionNode::NodeId(ln_test_utils::pubkey(46));
7569 invalid_blinded_path.blinded_hops.clear();
7570 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7571 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7572 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7573 &Default::default(), &random_seed_bytes)
7575 Err(LightningError { err, .. }) => {
7576 assert_eq!(err, "0-hop blinded path provided");
7578 _ => panic!("Expected error")
7583 fn matching_intro_node_paths_provided() {
7584 // Check that if multiple blinded paths with the same intro node are provided in payment
7585 // parameters, we'll return the correct paths in the resulting MPP route.
7586 let (secp_ctx, network, _, _, logger) = build_graph();
7587 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7588 let network_graph = network.read_only();
7590 let scorer = ln_test_utils::TestScorer::new();
7591 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7592 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7593 let config = UserConfig::default();
7595 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7596 let blinded_path_1 = BlindedPath {
7597 introduction_node: IntroductionNode::NodeId(nodes[2]),
7598 blinding_point: ln_test_utils::pubkey(42),
7600 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7601 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7604 let blinded_payinfo_1 = BlindedPayInfo {
7606 fee_proportional_millionths: 0,
7607 htlc_minimum_msat: 0,
7608 htlc_maximum_msat: 30_000,
7609 cltv_expiry_delta: 0,
7610 features: BlindedHopFeatures::empty(),
7613 let mut blinded_path_2 = blinded_path_1.clone();
7614 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7615 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7616 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7618 let blinded_hints = vec![
7619 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7620 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7622 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7623 .with_bolt12_features(bolt12_features).unwrap();
7625 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7626 route_params.max_total_routing_fee_msat = Some(100_000);
7627 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7628 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7629 assert_eq!(route.paths.len(), 2);
7630 let mut total_amount_paid_msat = 0;
7631 for path in route.paths.into_iter() {
7632 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7633 if let Some(bt) = &path.blinded_tail {
7634 assert_eq!(bt.blinding_point,
7635 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7636 .map(|(_, bp)| bp.blinding_point).unwrap());
7637 } else { panic!(); }
7638 total_amount_paid_msat += path.final_value_msat();
7640 assert_eq!(total_amount_paid_msat, 100_000);
7644 fn direct_to_intro_node() {
7645 // This previously caused a debug panic in the router when asserting
7646 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7647 // direct channels we failed to account for the fee charged for use of the blinded path.
7650 // node0 -1(1)2 - node1
7651 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7652 // doesn't account for the blinded path fee.
7654 let secp_ctx = Secp256k1::new();
7655 let logger = Arc::new(ln_test_utils::TestLogger::new());
7656 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7657 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7658 let scorer = ln_test_utils::TestScorer::new();
7659 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7660 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7662 let amt_msat = 10_000_000;
7663 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7664 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7665 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7666 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7667 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7668 short_channel_id: 1,
7671 cltv_expiry_delta: 42,
7672 htlc_minimum_msat: 1_000,
7673 htlc_maximum_msat: 10_000_000,
7675 fee_proportional_millionths: 0,
7676 excess_data: Vec::new()
7678 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7679 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7680 short_channel_id: 1,
7683 cltv_expiry_delta: 42,
7684 htlc_minimum_msat: 1_000,
7685 htlc_maximum_msat: 10_000_000,
7687 fee_proportional_millionths: 0,
7688 excess_data: Vec::new()
7690 let first_hops = vec![
7691 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7693 let blinded_path = BlindedPath {
7694 introduction_node: IntroductionNode::NodeId(nodes[1]),
7695 blinding_point: ln_test_utils::pubkey(42),
7697 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7698 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7701 let blinded_payinfo = BlindedPayInfo {
7702 fee_base_msat: 1000,
7703 fee_proportional_millionths: 0,
7704 htlc_minimum_msat: 1000,
7705 htlc_maximum_msat: MAX_VALUE_MSAT,
7706 cltv_expiry_delta: 0,
7707 features: BlindedHopFeatures::empty(),
7709 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7711 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7713 let netgraph = network_graph.read_only();
7714 let route_params = RouteParameters::from_payment_params_and_value(
7715 payment_params.clone(), amt_msat);
7716 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7717 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7718 &Default::default(), &random_seed_bytes) {
7719 assert_eq!(err, "Failed to find a path to the given destination");
7720 } else { panic!("Expected error") }
7722 // Sending an exact amount accounting for the blinded path fee works.
7723 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7724 let route_params = RouteParameters::from_payment_params_and_value(
7725 payment_params, amt_minus_blinded_path_fee);
7726 let route = get_route(&nodes[0], &route_params, &netgraph,
7727 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7728 &Default::default(), &random_seed_bytes).unwrap();
7729 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7730 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7734 fn direct_to_matching_intro_nodes() {
7735 // This previously caused us to enter `unreachable` code in the following situation:
7736 // 1. We add a route candidate for intro_node contributing a high amount
7737 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7738 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7739 // amount, and update our route candidate for intro_node for the lower amount
7740 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7741 // lower contribution amount, but fail (this was previously caused by failure to account for
7742 // blinded path fees when adding first_hop<>intro_node candidates)
7743 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7744 // candidate still thinks its path is contributing the original higher amount. This caused us
7745 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7747 let secp_ctx = Secp256k1::new();
7748 let logger = Arc::new(ln_test_utils::TestLogger::new());
7749 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7750 let scorer = ln_test_utils::TestScorer::new();
7751 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7752 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7753 let config = UserConfig::default();
7755 // Values are taken from the fuzz input that uncovered this panic.
7756 let amt_msat = 21_7020_5185_1403_2640;
7757 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7758 let first_hops = vec![
7759 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7760 18446744073709551615)];
7762 let blinded_path = BlindedPath {
7763 introduction_node: IntroductionNode::NodeId(nodes[1]),
7764 blinding_point: ln_test_utils::pubkey(42),
7766 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7767 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7770 let blinded_payinfo = BlindedPayInfo {
7771 fee_base_msat: 5046_2720,
7772 fee_proportional_millionths: 0,
7773 htlc_minimum_msat: 4503_5996_2737_0496,
7774 htlc_maximum_msat: 45_0359_9627_3704_9600,
7775 cltv_expiry_delta: 0,
7776 features: BlindedHopFeatures::empty(),
7778 let mut blinded_hints = vec![
7779 (blinded_payinfo.clone(), blinded_path.clone()),
7780 (blinded_payinfo.clone(), blinded_path.clone()),
7782 blinded_hints[1].0.fee_base_msat = 419_4304;
7783 blinded_hints[1].0.fee_proportional_millionths = 257;
7784 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7785 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7786 blinded_hints[1].0.cltv_expiry_delta = 0;
7788 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7789 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7790 .with_bolt12_features(bolt12_features).unwrap();
7792 let netgraph = network_graph.read_only();
7793 let route_params = RouteParameters::from_payment_params_and_value(
7794 payment_params, amt_msat);
7795 let route = get_route(&nodes[0], &route_params, &netgraph,
7796 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7797 &Default::default(), &random_seed_bytes).unwrap();
7798 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7799 assert_eq!(route.get_total_amount(), amt_msat);
7803 fn we_are_intro_node_candidate_hops() {
7804 // This previously led to a panic in the router because we'd generate a Path with only a
7805 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7806 // where the origin node is the intro node. We now fully disallow considering candidate hops
7807 // where the origin node is the intro node.
7808 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7809 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7810 let scorer = ln_test_utils::TestScorer::new();
7811 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7812 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7813 let config = UserConfig::default();
7815 // Values are taken from the fuzz input that uncovered this panic.
7816 let amt_msat = 21_7020_5185_1423_0019;
7818 let blinded_path = BlindedPath {
7819 introduction_node: IntroductionNode::NodeId(our_id),
7820 blinding_point: ln_test_utils::pubkey(42),
7822 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7823 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7826 let blinded_payinfo = BlindedPayInfo {
7827 fee_base_msat: 5052_9027,
7828 fee_proportional_millionths: 0,
7829 htlc_minimum_msat: 21_7020_5185_1423_0019,
7830 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7831 cltv_expiry_delta: 0,
7832 features: BlindedHopFeatures::empty(),
7834 let mut blinded_hints = vec![
7835 (blinded_payinfo.clone(), blinded_path.clone()),
7836 (blinded_payinfo.clone(), blinded_path.clone()),
7838 blinded_hints[1].1.introduction_node = IntroductionNode::NodeId(nodes[6]);
7840 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7841 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7842 .with_bolt12_features(bolt12_features.clone()).unwrap();
7844 let netgraph = network_graph.read_only();
7845 let route_params = RouteParameters::from_payment_params_and_value(
7846 payment_params, amt_msat);
7847 if let Err(LightningError { err, .. }) = get_route(
7848 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7850 assert_eq!(err, "Failed to find a path to the given destination");
7855 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7856 // This previously led to a debug panic in the router because we'd find an invalid Path with
7857 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7858 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7859 // the payment, when it was intended to only include the final value of the payment.
7860 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7861 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7862 let scorer = ln_test_utils::TestScorer::new();
7863 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7864 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7865 let config = UserConfig::default();
7867 // Values are taken from the fuzz input that uncovered this panic.
7868 let amt_msat = 21_7020_5185_1423_0019;
7870 let blinded_path = BlindedPath {
7871 introduction_node: IntroductionNode::NodeId(our_id),
7872 blinding_point: ln_test_utils::pubkey(42),
7874 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7875 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7878 let blinded_payinfo = BlindedPayInfo {
7879 fee_base_msat: 10_4425_1395,
7880 fee_proportional_millionths: 0,
7881 htlc_minimum_msat: 21_7301_9934_9094_0931,
7882 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7883 cltv_expiry_delta: 0,
7884 features: BlindedHopFeatures::empty(),
7886 let mut blinded_hints = vec![
7887 (blinded_payinfo.clone(), blinded_path.clone()),
7888 (blinded_payinfo.clone(), blinded_path.clone()),
7889 (blinded_payinfo.clone(), blinded_path.clone()),
7891 blinded_hints[1].0.fee_base_msat = 5052_9027;
7892 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7893 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7895 blinded_hints[2].1.introduction_node = IntroductionNode::NodeId(nodes[6]);
7897 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7898 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7899 .with_bolt12_features(bolt12_features.clone()).unwrap();
7901 let netgraph = network_graph.read_only();
7902 let route_params = RouteParameters::from_payment_params_and_value(
7903 payment_params, amt_msat);
7904 if let Err(LightningError { err, .. }) = get_route(
7905 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7907 assert_eq!(err, "Failed to find a path to the given destination");
7912 fn min_htlc_overpay_violates_max_htlc() {
7913 do_min_htlc_overpay_violates_max_htlc(true);
7914 do_min_htlc_overpay_violates_max_htlc(false);
7916 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7917 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7918 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7919 // to `targets` and build an invalid path with it, and subsequently hit a debug panic asserting
7920 // that the used liquidity for a hop was less than its available liquidity limit.
7921 let secp_ctx = Secp256k1::new();
7922 let logger = Arc::new(ln_test_utils::TestLogger::new());
7923 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7924 let scorer = ln_test_utils::TestScorer::new();
7925 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7926 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7927 let config = UserConfig::default();
7929 // Values are taken from the fuzz input that uncovered this panic.
7930 let amt_msat = 7_4009_8048;
7931 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7932 let first_hop_outbound_capacity = 2_7345_2000;
7933 let first_hops = vec![get_channel_details(
7934 Some(200), nodes[0], channelmanager::provided_init_features(&config),
7935 first_hop_outbound_capacity
7938 let base_fee = 1_6778_3453;
7939 let htlc_min = 2_5165_8240;
7940 let payment_params = if blinded_payee {
7941 let blinded_path = BlindedPath {
7942 introduction_node: IntroductionNode::NodeId(nodes[0]),
7943 blinding_point: ln_test_utils::pubkey(42),
7945 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7946 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7949 let blinded_payinfo = BlindedPayInfo {
7950 fee_base_msat: base_fee,
7951 fee_proportional_millionths: 0,
7952 htlc_minimum_msat: htlc_min,
7953 htlc_maximum_msat: htlc_min * 1000,
7954 cltv_expiry_delta: 0,
7955 features: BlindedHopFeatures::empty(),
7957 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7958 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
7959 .with_bolt12_features(bolt12_features.clone()).unwrap()
7961 let route_hint = RouteHint(vec![RouteHintHop {
7962 src_node_id: nodes[0],
7963 short_channel_id: 42,
7965 base_msat: base_fee,
7966 proportional_millionths: 0,
7968 cltv_expiry_delta: 10,
7969 htlc_minimum_msat: Some(htlc_min),
7970 htlc_maximum_msat: None,
7973 PaymentParameters::from_node_id(nodes[1], 42)
7974 .with_route_hints(vec![route_hint]).unwrap()
7975 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).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, Some(&first_hops.iter().collect::<Vec<_>>()),
7983 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7985 assert_eq!(err, "Failed to find a path to the given destination");
7990 fn previously_used_liquidity_violates_max_htlc() {
7991 do_previously_used_liquidity_violates_max_htlc(true);
7992 do_previously_used_liquidity_violates_max_htlc(false);
7995 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
7996 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
7997 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
7998 // candidate. In this case, the candidate does not have enough due to a previous path taking up
7999 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
8000 // asserting that the used liquidity for a hop was less than its available liquidity limit.
8001 let secp_ctx = Secp256k1::new();
8002 let logger = Arc::new(ln_test_utils::TestLogger::new());
8003 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8004 let scorer = ln_test_utils::TestScorer::new();
8005 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8006 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8007 let config = UserConfig::default();
8009 // Values are taken from the fuzz input that uncovered this panic.
8010 let amt_msat = 52_4288;
8011 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8012 let first_hops = vec![get_channel_details(
8013 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
8014 ), get_channel_details(
8015 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
8018 let base_fees = [0, 425_9840, 0, 0];
8019 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
8020 let payment_params = if blinded_payee {
8021 let blinded_path = BlindedPath {
8022 introduction_node: IntroductionNode::NodeId(nodes[0]),
8023 blinding_point: ln_test_utils::pubkey(42),
8025 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8026 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8029 let mut blinded_hints = Vec::new();
8030 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
8031 blinded_hints.push((BlindedPayInfo {
8032 fee_base_msat: *base_fee,
8033 fee_proportional_millionths: 0,
8034 htlc_minimum_msat: *htlc_min,
8035 htlc_maximum_msat: htlc_min * 100,
8036 cltv_expiry_delta: 10,
8037 features: BlindedHopFeatures::empty(),
8038 }, blinded_path.clone()));
8040 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8041 PaymentParameters::blinded(blinded_hints.clone())
8042 .with_bolt12_features(bolt12_features.clone()).unwrap()
8044 let mut route_hints = Vec::new();
8045 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
8046 route_hints.push(RouteHint(vec![RouteHintHop {
8047 src_node_id: nodes[0],
8048 short_channel_id: 42 + idx as u64,
8050 base_msat: *base_fee,
8051 proportional_millionths: 0,
8053 cltv_expiry_delta: 10,
8054 htlc_minimum_msat: Some(*htlc_min),
8055 htlc_maximum_msat: Some(htlc_min * 100),
8058 PaymentParameters::from_node_id(nodes[1], 42)
8059 .with_route_hints(route_hints).unwrap()
8060 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8063 let netgraph = network_graph.read_only();
8064 let route_params = RouteParameters::from_payment_params_and_value(
8065 payment_params, amt_msat);
8067 let route = get_route(
8068 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8069 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8071 assert_eq!(route.paths.len(), 1);
8072 assert_eq!(route.get_total_amount(), amt_msat);
8076 fn candidate_path_min() {
8077 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
8078 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
8079 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
8080 // would add a connecting first_hop node that did not have enough contribution amount, leading
8081 // to a debug panic upon invalid path construction.
8082 let secp_ctx = Secp256k1::new();
8083 let logger = Arc::new(ln_test_utils::TestLogger::new());
8084 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8085 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
8086 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8087 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8088 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8089 let config = UserConfig::default();
8091 // Values are taken from the fuzz input that uncovered this panic.
8092 let amt_msat = 7_4009_8048;
8093 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
8094 let first_hops = vec![get_channel_details(
8095 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
8098 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
8099 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8100 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8101 short_channel_id: 6,
8104 cltv_expiry_delta: (6 << 4) | 0,
8105 htlc_minimum_msat: 0,
8106 htlc_maximum_msat: MAX_VALUE_MSAT,
8108 fee_proportional_millionths: 0,
8109 excess_data: Vec::new()
8111 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
8113 let htlc_min = 2_5165_8240;
8114 let blinded_hints = vec![
8116 fee_base_msat: 1_6778_3453,
8117 fee_proportional_millionths: 0,
8118 htlc_minimum_msat: htlc_min,
8119 htlc_maximum_msat: htlc_min * 100,
8120 cltv_expiry_delta: 10,
8121 features: BlindedHopFeatures::empty(),
8123 introduction_node: IntroductionNode::NodeId(nodes[0]),
8124 blinding_point: ln_test_utils::pubkey(42),
8126 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8127 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8131 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8132 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8133 .with_bolt12_features(bolt12_features.clone()).unwrap();
8134 let route_params = RouteParameters::from_payment_params_and_value(
8135 payment_params, amt_msat);
8136 let netgraph = network_graph.read_only();
8138 if let Err(LightningError { err, .. }) = get_route(
8139 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8140 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8143 assert_eq!(err, "Failed to find a path to the given destination");
8148 fn path_contribution_includes_min_htlc_overpay() {
8149 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
8150 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
8151 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
8152 // selection, both tested here.
8153 let secp_ctx = Secp256k1::new();
8154 let logger = Arc::new(ln_test_utils::TestLogger::new());
8155 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8156 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8157 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8158 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8159 let config = UserConfig::default();
8161 // Values are taken from the fuzz input that uncovered this panic.
8162 let amt_msat = 562_0000;
8163 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8164 let first_hops = vec![
8165 get_channel_details(
8166 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
8170 let htlc_mins = [49_0000, 1125_0000];
8171 let payment_params = {
8172 let blinded_path = BlindedPath {
8173 introduction_node: IntroductionNode::NodeId(nodes[0]),
8174 blinding_point: ln_test_utils::pubkey(42),
8176 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8177 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8180 let mut blinded_hints = Vec::new();
8181 for htlc_min in htlc_mins.iter() {
8182 blinded_hints.push((BlindedPayInfo {
8184 fee_proportional_millionths: 0,
8185 htlc_minimum_msat: *htlc_min,
8186 htlc_maximum_msat: *htlc_min * 100,
8187 cltv_expiry_delta: 10,
8188 features: BlindedHopFeatures::empty(),
8189 }, blinded_path.clone()));
8191 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8192 PaymentParameters::blinded(blinded_hints.clone())
8193 .with_bolt12_features(bolt12_features.clone()).unwrap()
8196 let netgraph = network_graph.read_only();
8197 let route_params = RouteParameters::from_payment_params_and_value(
8198 payment_params, amt_msat);
8199 let route = get_route(
8200 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8201 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8204 assert_eq!(route.paths.len(), 1);
8205 assert_eq!(route.get_total_amount(), amt_msat);
8209 fn first_hop_preferred_over_hint() {
8210 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
8211 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
8212 let secp_ctx = Secp256k1::new();
8213 let logger = Arc::new(ln_test_utils::TestLogger::new());
8214 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8215 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
8216 let scorer = ln_test_utils::TestScorer::new();
8217 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8218 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8219 let config = UserConfig::default();
8221 let amt_msat = 1_000_000;
8222 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
8224 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
8225 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
8226 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8227 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8228 short_channel_id: 1,
8231 cltv_expiry_delta: 42,
8232 htlc_minimum_msat: 1_000,
8233 htlc_maximum_msat: 10_000_000,
8235 fee_proportional_millionths: 0,
8236 excess_data: Vec::new()
8238 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8239 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8240 short_channel_id: 1,
8243 cltv_expiry_delta: 42,
8244 htlc_minimum_msat: 1_000,
8245 htlc_maximum_msat: 10_000_000,
8247 fee_proportional_millionths: 0,
8248 excess_data: Vec::new()
8251 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
8252 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
8253 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8254 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8255 short_channel_id: 2,
8258 cltv_expiry_delta: 42,
8259 htlc_minimum_msat: 1_000,
8260 htlc_maximum_msat: 10_000_000,
8262 fee_proportional_millionths: 0,
8263 excess_data: Vec::new()
8265 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8266 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8267 short_channel_id: 2,
8270 cltv_expiry_delta: 42,
8271 htlc_minimum_msat: 1_000,
8272 htlc_maximum_msat: 10_000_000,
8274 fee_proportional_millionths: 0,
8275 excess_data: Vec::new()
8278 let dest_node_id = nodes[2];
8280 let route_hint = RouteHint(vec![RouteHintHop {
8281 src_node_id: our_node_id,
8282 short_channel_id: 44,
8285 proportional_millionths: 0,
8287 cltv_expiry_delta: 10,
8288 htlc_minimum_msat: None,
8289 htlc_maximum_msat: Some(5_000_000),
8292 src_node_id: nodes[0],
8293 short_channel_id: 45,
8296 proportional_millionths: 0,
8298 cltv_expiry_delta: 10,
8299 htlc_minimum_msat: None,
8300 htlc_maximum_msat: None,
8303 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8304 .with_route_hints(vec![route_hint]).unwrap()
8305 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8306 let route_params = RouteParameters::from_payment_params_and_value(
8307 payment_params, amt_msat);
8309 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8311 let first_hop = get_channel_details(Some(1), nodes[0],
8312 channelmanager::provided_init_features(&config), 999_999);
8313 let first_hops = vec![first_hop];
8315 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8316 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8317 &Default::default(), &random_seed_bytes).unwrap();
8318 assert_eq!(route.paths.len(), 1);
8319 assert_eq!(route.get_total_amount(), amt_msat);
8320 assert_eq!(route.paths[0].hops.len(), 2);
8321 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8322 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8323 assert_eq!(route.get_total_fees(), 123);
8325 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8326 // for a first hop channel.
8327 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8328 first_hop.outbound_scid_alias = Some(44);
8329 let first_hops = vec![first_hop];
8331 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8332 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8333 &Default::default(), &random_seed_bytes);
8334 assert!(route_res.is_err());
8336 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8337 // use the cheaper second hop of the route hint.
8338 let mut first_hop = get_channel_details(Some(1), nodes[0],
8339 channelmanager::provided_init_features(&config), 10_000_000);
8340 first_hop.outbound_scid_alias = Some(44);
8341 let first_hops = vec![first_hop];
8343 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8344 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8345 &Default::default(), &random_seed_bytes).unwrap();
8346 assert_eq!(route.paths.len(), 1);
8347 assert_eq!(route.get_total_amount(), amt_msat);
8348 assert_eq!(route.paths[0].hops.len(), 2);
8349 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8350 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8351 assert_eq!(route.get_total_fees(), 123);
8355 fn allow_us_being_first_hint() {
8356 // Check that we consider a route hint even if we are the src of the first hop.
8357 let secp_ctx = Secp256k1::new();
8358 let logger = Arc::new(ln_test_utils::TestLogger::new());
8359 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8360 let scorer = ln_test_utils::TestScorer::new();
8361 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8362 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8363 let config = UserConfig::default();
8365 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8367 let amt_msat = 1_000_000;
8368 let dest_node_id = nodes[1];
8370 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8371 let first_hops = vec![first_hop];
8373 let route_hint = RouteHint(vec![RouteHintHop {
8374 src_node_id: our_node_id,
8375 short_channel_id: 44,
8378 proportional_millionths: 0,
8380 cltv_expiry_delta: 10,
8381 htlc_minimum_msat: None,
8382 htlc_maximum_msat: None,
8385 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8386 .with_route_hints(vec![route_hint]).unwrap()
8387 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8389 let route_params = RouteParameters::from_payment_params_and_value(
8390 payment_params, amt_msat);
8393 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8394 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8395 &Default::default(), &random_seed_bytes).unwrap();
8397 assert_eq!(route.paths.len(), 1);
8398 assert_eq!(route.get_total_amount(), amt_msat);
8399 assert_eq!(route.get_total_fees(), 0);
8400 assert_eq!(route.paths[0].hops.len(), 1);
8402 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8406 #[cfg(all(any(test, ldk_bench), feature = "std"))]
8407 pub(crate) mod bench_utils {
8410 use std::time::Duration;
8412 use bitcoin::hashes::Hash;
8413 use bitcoin::secp256k1::SecretKey;
8415 use crate::chain::transaction::OutPoint;
8416 use crate::routing::scoring::ScoreUpdate;
8417 use crate::sign::KeysManager;
8418 use crate::ln::types::ChannelId;
8419 use crate::ln::channelmanager::{self, ChannelCounterparty};
8420 use crate::util::config::UserConfig;
8421 use crate::util::test_utils::TestLogger;
8423 /// Tries to open a network graph file, or panics with a URL to fetch it.
8424 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
8425 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
8426 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
8427 .or_else(|_| { // Fall back to guessing based on the binary location
8428 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8429 let mut path = std::env::current_exe().unwrap();
8430 path.pop(); // lightning-...
8432 path.pop(); // debug
8433 path.pop(); // target
8434 path.push("lightning");
8435 path.push("net_graph-2023-01-18.bin");
8438 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8439 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8440 let mut path = std::env::current_exe().unwrap();
8441 path.pop(); // bench...
8443 path.pop(); // debug
8444 path.pop(); // target
8445 path.pop(); // bench
8446 path.push("lightning");
8447 path.push("net_graph-2023-01-18.bin");
8450 .map_err(|_| "Please fetch https://bitcoin.ninja/ldk-net_graph-v0.0.113-2023-01-18.bin and place it at lightning/net_graph-2023-01-18.bin");
8451 #[cfg(require_route_graph_test)]
8452 return Ok(res.unwrap());
8453 #[cfg(not(require_route_graph_test))]
8457 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
8458 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
8461 pub(crate) fn payer_pubkey() -> PublicKey {
8462 let secp_ctx = Secp256k1::new();
8463 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8467 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8469 channel_id: ChannelId::new_zero(),
8470 counterparty: ChannelCounterparty {
8471 features: channelmanager::provided_init_features(&UserConfig::default()),
8473 unspendable_punishment_reserve: 0,
8474 forwarding_info: None,
8475 outbound_htlc_minimum_msat: None,
8476 outbound_htlc_maximum_msat: None,
8478 funding_txo: Some(OutPoint {
8479 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8482 short_channel_id: Some(1),
8483 inbound_scid_alias: None,
8484 outbound_scid_alias: None,
8485 channel_value_satoshis: 10_000_000_000,
8487 balance_msat: 10_000_000_000,
8488 outbound_capacity_msat: 10_000_000_000,
8489 next_outbound_htlc_minimum_msat: 0,
8490 next_outbound_htlc_limit_msat: 10_000_000_000,
8491 inbound_capacity_msat: 0,
8492 unspendable_punishment_reserve: None,
8493 confirmations_required: None,
8494 confirmations: None,
8495 force_close_spend_delay: None,
8497 is_channel_ready: true,
8500 inbound_htlc_minimum_msat: None,
8501 inbound_htlc_maximum_msat: None,
8503 feerate_sat_per_1000_weight: None,
8504 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
8505 pending_inbound_htlcs: Vec::new(),
8506 pending_outbound_htlcs: Vec::new(),
8510 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8511 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8512 starting_amount: u64, route_count: usize,
8513 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8514 let payer = payer_pubkey();
8515 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8516 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8518 let nodes = graph.read_only().nodes().clone();
8519 let mut route_endpoints = Vec::new();
8520 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
8521 // with some routes we picked being un-routable.
8522 for _ in 0..route_count * 3 / 2 {
8524 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8525 let src = PublicKey::from_slice(nodes.unordered_keys()
8526 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8527 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8528 let dst = PublicKey::from_slice(nodes.unordered_keys()
8529 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8530 let params = PaymentParameters::from_node_id(dst, 42)
8531 .with_bolt11_features(features.clone()).unwrap();
8532 let first_hop = first_hop(src);
8533 let amt_msat = starting_amount + seed % 1_000_000;
8534 let route_params = RouteParameters::from_payment_params_and_value(
8535 params.clone(), amt_msat);
8537 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8538 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8540 // ...and seed the scorer with success and failure data...
8541 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8542 let mut score_amt = seed % 1_000_000_000;
8544 // Generate fail/success paths for a wider range of potential amounts with
8545 // MPP enabled to give us a chance to apply penalties for more potential
8547 let mpp_features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
8548 let params = PaymentParameters::from_node_id(dst, 42)
8549 .with_bolt11_features(mpp_features).unwrap();
8550 let route_params = RouteParameters::from_payment_params_and_value(
8551 params.clone(), score_amt);
8552 let route_res = get_route(&payer, &route_params, &graph.read_only(),
8553 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
8554 &random_seed_bytes);
8555 if let Ok(route) = route_res {
8556 for path in route.paths {
8557 if seed & 0x80 == 0 {
8558 scorer.payment_path_successful(&path, Duration::ZERO);
8560 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
8561 scorer.payment_path_failed(&path, short_channel_id, Duration::ZERO);
8563 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8567 // If we couldn't find a path with a higher amount, reduce and try again.
8571 route_endpoints.push((first_hop, params, amt_msat));
8577 // Because we've changed channel scores, it's possible we'll take different routes to the
8578 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
8579 // requires a too-high CLTV delta.
8580 route_endpoints.retain(|(first_hop, params, amt_msat)| {
8581 let route_params = RouteParameters::from_payment_params_and_value(
8582 params.clone(), *amt_msat);
8583 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8584 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
8586 route_endpoints.truncate(route_count);
8587 assert_eq!(route_endpoints.len(), route_count);
8595 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8596 use crate::sign::{EntropySource, KeysManager};
8597 use crate::ln::channelmanager;
8598 use crate::ln::features::Bolt11InvoiceFeatures;
8599 use crate::routing::gossip::NetworkGraph;
8600 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
8601 use crate::util::config::UserConfig;
8602 use crate::util::logger::{Logger, Record};
8603 use crate::util::test_utils::TestLogger;
8605 use criterion::Criterion;
8607 struct DummyLogger {}
8608 impl Logger for DummyLogger {
8609 fn log(&self, _record: Record) {}
8612 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8613 let logger = TestLogger::new();
8614 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8615 let scorer = FixedPenaltyScorer::with_penalty(0);
8616 generate_routes(bench, &network_graph, scorer, &Default::default(),
8617 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8620 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8621 let logger = TestLogger::new();
8622 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8623 let scorer = FixedPenaltyScorer::with_penalty(0);
8624 generate_routes(bench, &network_graph, scorer, &Default::default(),
8625 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8626 "generate_mpp_routes_with_zero_penalty_scorer");
8629 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8630 let logger = TestLogger::new();
8631 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8632 let params = ProbabilisticScoringFeeParameters::default();
8633 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8634 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8635 "generate_routes_with_probabilistic_scorer");
8638 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8639 let logger = TestLogger::new();
8640 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8641 let params = ProbabilisticScoringFeeParameters::default();
8642 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8643 generate_routes(bench, &network_graph, scorer, ¶ms,
8644 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8645 "generate_mpp_routes_with_probabilistic_scorer");
8648 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8649 let logger = TestLogger::new();
8650 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8651 let params = ProbabilisticScoringFeeParameters::default();
8652 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8653 generate_routes(bench, &network_graph, scorer, ¶ms,
8654 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8655 "generate_large_mpp_routes_with_probabilistic_scorer");
8658 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8659 let logger = TestLogger::new();
8660 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8661 let mut params = ProbabilisticScoringFeeParameters::default();
8662 params.linear_success_probability = false;
8663 let scorer = ProbabilisticScorer::new(
8664 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8665 generate_routes(bench, &network_graph, scorer, ¶ms,
8666 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8667 "generate_routes_with_nonlinear_probabilistic_scorer");
8670 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8671 let logger = TestLogger::new();
8672 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8673 let mut params = ProbabilisticScoringFeeParameters::default();
8674 params.linear_success_probability = false;
8675 let scorer = ProbabilisticScorer::new(
8676 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8677 generate_routes(bench, &network_graph, scorer, ¶ms,
8678 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8679 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8682 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8683 let logger = TestLogger::new();
8684 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8685 let mut params = ProbabilisticScoringFeeParameters::default();
8686 params.linear_success_probability = false;
8687 let scorer = ProbabilisticScorer::new(
8688 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8689 generate_routes(bench, &network_graph, scorer, ¶ms,
8690 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8691 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8694 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8695 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8696 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8697 bench_name: &'static str,
8699 let payer = bench_utils::payer_pubkey();
8700 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8701 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8703 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8704 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8706 // ...then benchmark finding paths between the nodes we learned.
8708 bench.bench_function(bench_name, |b| b.iter(|| {
8709 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8710 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8711 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8712 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());