1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The router finds paths within a [`NetworkGraph`] for a payment.
12 use bitcoin::secp256k1::{PublicKey, Secp256k1, self};
14 use crate::blinded_path::{BlindedHop, BlindedPath, Direction, IntroductionNode};
15 use crate::blinded_path::message;
16 use crate::blinded_path::payment::{ForwardTlvs, PaymentConstraints, PaymentRelay, ReceiveTlvs, self};
17 use crate::ln::{PaymentHash, PaymentPreimage};
18 use crate::ln::channel_state::ChannelDetails;
19 use crate::ln::channelmanager::{PaymentId, MIN_FINAL_CLTV_EXPIRY_DELTA, RecipientOnionFields};
20 use crate::ln::features::{BlindedHopFeatures, Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
21 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
22 use crate::ln::onion_utils;
23 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice};
24 use crate::onion_message::messenger::{DefaultMessageRouter, Destination, MessageRouter, OnionMessagePath};
25 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
26 use crate::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp};
27 use crate::sign::EntropySource;
28 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
29 use crate::util::logger::{Level, Logger};
30 use crate::crypto::chacha20::ChaCha20;
33 use crate::prelude::*;
34 use alloc::collections::BinaryHeap;
38 /// A [`Router`] implemented using [`find_route`].
39 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> where
41 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
42 ES::Target: EntropySource,
49 message_router: DefaultMessageRouter<G, L, ES>,
52 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
54 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
55 ES::Target: EntropySource,
57 /// Creates a new router.
58 pub fn new(network_graph: G, logger: L, entropy_source: ES, scorer: S, score_params: SP) -> Self {
59 let message_router = DefaultMessageRouter::new(network_graph.clone(), entropy_source.clone());
60 Self { network_graph, logger, entropy_source, scorer, score_params, message_router }
64 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
66 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
67 ES::Target: EntropySource,
72 params: &RouteParameters,
73 first_hops: Option<&[&ChannelDetails]>,
74 inflight_htlcs: InFlightHtlcs
75 ) -> Result<Route, LightningError> {
76 let random_seed_bytes = self.entropy_source.get_secure_random_bytes();
78 payer, params, &self.network_graph, first_hops, &*self.logger,
79 &ScorerAccountingForInFlightHtlcs::new(self.scorer.read_lock(), &inflight_htlcs),
85 fn create_blinded_payment_paths<
86 T: secp256k1::Signing + secp256k1::Verification
88 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
89 amount_msats: u64, secp_ctx: &Secp256k1<T>
90 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
91 // Limit the number of blinded paths that are computed.
92 const MAX_PAYMENT_PATHS: usize = 3;
94 // Ensure peers have at least three channels so that it is more difficult to infer the
95 // recipient's node_id.
96 const MIN_PEER_CHANNELS: usize = 3;
98 let network_graph = self.network_graph.deref().read_only();
99 let paths = first_hops.into_iter()
100 .filter(|details| details.counterparty.features.supports_route_blinding())
101 .filter(|details| amount_msats <= details.inbound_capacity_msat)
102 .filter(|details| amount_msats >= details.inbound_htlc_minimum_msat.unwrap_or(0))
103 .filter(|details| amount_msats <= details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX))
104 .filter(|details| network_graph
105 .node(&NodeId::from_pubkey(&details.counterparty.node_id))
106 .map(|node_info| node_info.channels.len() >= MIN_PEER_CHANNELS)
109 .filter_map(|details| {
110 let short_channel_id = match details.get_inbound_payment_scid() {
111 Some(short_channel_id) => short_channel_id,
114 let payment_relay: PaymentRelay = match details.counterparty.forwarding_info {
115 Some(forwarding_info) => match forwarding_info.try_into() {
116 Ok(payment_relay) => payment_relay,
117 Err(()) => return None,
122 let cltv_expiry_delta = payment_relay.cltv_expiry_delta as u32;
123 let payment_constraints = PaymentConstraints {
124 max_cltv_expiry: tlvs.payment_constraints.max_cltv_expiry + cltv_expiry_delta,
125 htlc_minimum_msat: details.inbound_htlc_minimum_msat.unwrap_or(0),
127 Some(payment::ForwardNode {
132 features: BlindedHopFeatures::empty(),
134 node_id: details.counterparty.node_id,
135 htlc_maximum_msat: details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX),
138 .map(|forward_node| {
139 BlindedPath::new_for_payment(
140 &[forward_node], recipient, tlvs.clone(), u64::MAX, MIN_FINAL_CLTV_EXPIRY_DELTA,
141 &*self.entropy_source, secp_ctx
144 .take(MAX_PAYMENT_PATHS)
145 .collect::<Result<Vec<_>, _>>();
148 Ok(paths) if !paths.is_empty() => Ok(paths),
150 if network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient)) {
151 BlindedPath::one_hop_for_payment(
152 recipient, tlvs, MIN_FINAL_CLTV_EXPIRY_DELTA, &*self.entropy_source, secp_ctx
153 ).map(|path| vec![path])
162 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
164 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
165 ES::Target: EntropySource,
168 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
169 ) -> Result<OnionMessagePath, ()> {
170 self.message_router.find_path(sender, peers, destination)
173 fn create_blinded_paths<
174 T: secp256k1::Signing + secp256k1::Verification
176 &self, recipient: PublicKey, peers: Vec<message::ForwardNode>, secp_ctx: &Secp256k1<T>,
177 ) -> Result<Vec<BlindedPath>, ()> {
178 self.message_router.create_blinded_paths(recipient, peers, secp_ctx)
182 /// A trait defining behavior for routing a payment.
183 pub trait Router: MessageRouter {
184 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
186 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
187 /// and [`RouteParameters::final_value_msat`], respectively.
189 &self, payer: &PublicKey, route_params: &RouteParameters,
190 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
191 ) -> Result<Route, LightningError>;
193 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
195 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
196 /// and [`RouteParameters::final_value_msat`], respectively.
198 /// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
200 fn find_route_with_id(
201 &self, payer: &PublicKey, route_params: &RouteParameters,
202 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
203 _payment_hash: PaymentHash, _payment_id: PaymentId
204 ) -> Result<Route, LightningError> {
205 self.find_route(payer, route_params, first_hops, inflight_htlcs)
208 /// Creates [`BlindedPath`]s for payment to the `recipient` node. The channels in `first_hops`
209 /// are assumed to be with the `recipient`'s peers. The payment secret and any constraints are
211 fn create_blinded_payment_paths<
212 T: secp256k1::Signing + secp256k1::Verification
214 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
215 amount_msats: u64, secp_ctx: &Secp256k1<T>
216 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()>;
219 /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
221 /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
224 /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
225 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> where S::Target: ScoreLookUp {
227 // Maps a channel's short channel id and its direction to the liquidity used up.
228 inflight_htlcs: &'a InFlightHtlcs,
230 impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
231 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
232 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
233 ScorerAccountingForInFlightHtlcs {
240 impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
241 type ScoreParams = <S::Target as ScoreLookUp>::ScoreParams;
242 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
243 let target = match candidate.target() {
244 Some(target) => target,
245 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
247 let short_channel_id = match candidate.short_channel_id() {
248 Some(short_channel_id) => short_channel_id,
249 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
251 let source = candidate.source();
252 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
253 &source, &target, short_channel_id
255 let usage = ChannelUsage {
256 inflight_htlc_msat: usage.inflight_htlc_msat.saturating_add(used_liquidity),
260 self.scorer.channel_penalty_msat(candidate, usage, score_params)
262 self.scorer.channel_penalty_msat(candidate, usage, score_params)
267 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
268 /// in-use channel liquidity.
270 pub struct InFlightHtlcs(
271 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
272 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
273 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
275 HashMap<(u64, bool), u64>
279 /// Constructs an empty `InFlightHtlcs`.
280 pub fn new() -> Self { InFlightHtlcs(new_hash_map()) }
282 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
283 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
284 if path.hops.is_empty() { return };
286 let mut cumulative_msat = 0;
287 if let Some(tail) = &path.blinded_tail {
288 cumulative_msat += tail.final_value_msat;
291 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
292 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
293 // the router excludes the payer node. In the following lines, the payer's information is
294 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
295 // in our sliding window of two.
296 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
297 .map(|hop| hop.pubkey)
298 .chain(core::iter::once(payer_node_id));
300 // Taking the reversed vector from above, we zip it with just the reversed hops list to
301 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
302 // the total amount sent.
303 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
304 cumulative_msat += next_hop.fee_msat;
306 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
307 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
308 .or_insert(cumulative_msat);
312 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
314 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
316 .entry((channel_scid, source < target))
317 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
318 .or_insert(used_msat);
321 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
323 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
324 self.0.get(&(channel_scid, source < target)).map(|v| *v)
328 impl Writeable for InFlightHtlcs {
329 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
332 impl Readable for InFlightHtlcs {
333 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
334 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
335 Ok(Self(infight_map))
339 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
340 /// that leads to it.
341 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
342 pub struct RouteHop {
343 /// The node_id of the node at this hop.
344 pub pubkey: PublicKey,
345 /// The node_announcement features of the node at this hop. For the last hop, these may be
346 /// amended to match the features present in the invoice this node generated.
347 pub node_features: NodeFeatures,
348 /// The channel that should be used from the previous hop to reach this node.
349 pub short_channel_id: u64,
350 /// The channel_announcement features of the channel that should be used from the previous hop
351 /// to reach this node.
352 pub channel_features: ChannelFeatures,
353 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
354 /// If this is the last hop in [`Path::hops`]:
355 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
356 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
358 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
360 /// The CLTV delta added for this hop.
361 /// If this is the last hop in [`Path::hops`]:
362 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
363 /// * otherwise, this is the CLTV delta expected at the destination
365 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
366 pub cltv_expiry_delta: u32,
367 /// Indicates whether this hop is possibly announced in the public network graph.
369 /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
370 /// either know for sure it's announced in the public graph, or if any public channels exist
371 /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
372 /// the channel to be unannounced.
374 /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
375 pub maybe_announced_channel: bool,
378 impl_writeable_tlv_based!(RouteHop, {
379 (0, pubkey, required),
380 (1, maybe_announced_channel, (default_value, true)),
381 (2, node_features, required),
382 (4, short_channel_id, required),
383 (6, channel_features, required),
384 (8, fee_msat, required),
385 (10, cltv_expiry_delta, required),
388 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
389 /// their [`Bolt12Invoice`].
391 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
392 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
393 pub struct BlindedTail {
394 /// The hops of the [`BlindedPath`] provided by the recipient.
396 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
397 pub hops: Vec<BlindedHop>,
398 /// The blinding point of the [`BlindedPath`] provided by the recipient.
400 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
401 pub blinding_point: PublicKey,
402 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
403 /// inferring the destination. May be 0.
404 pub excess_final_cltv_expiry_delta: u32,
405 /// The total amount paid on this [`Path`], excluding the fees.
406 pub final_value_msat: u64,
409 impl_writeable_tlv_based!(BlindedTail, {
410 (0, hops, required_vec),
411 (2, blinding_point, required),
412 (4, excess_final_cltv_expiry_delta, required),
413 (6, final_value_msat, required),
416 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
417 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
418 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
420 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
421 pub hops: Vec<RouteHop>,
422 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
423 pub blinded_tail: Option<BlindedTail>,
427 /// Gets the fees for a given path, excluding any excess paid to the recipient.
428 pub fn fee_msat(&self) -> u64 {
429 match &self.blinded_tail {
430 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
432 // Do not count last hop of each path since that's the full value of the payment
433 self.hops.split_last().map_or(0,
434 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
439 /// Gets the total amount paid on this [`Path`], excluding the fees.
440 pub fn final_value_msat(&self) -> u64 {
441 match &self.blinded_tail {
442 Some(blinded_tail) => blinded_tail.final_value_msat,
443 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
447 /// Gets the final hop's CLTV expiry delta.
448 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
449 match &self.blinded_tail {
451 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
456 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
457 /// it can take multiple paths. Each path is composed of one or more hops through the network.
458 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
460 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
461 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
463 pub paths: Vec<Path>,
464 /// The `route_params` parameter passed to [`find_route`].
466 /// This is used by `ChannelManager` to track information which may be required for retries.
468 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
469 pub route_params: Option<RouteParameters>,
473 /// Returns the total amount of fees paid on this [`Route`].
475 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
476 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
477 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
479 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
480 pub fn get_total_fees(&self) -> u64 {
481 let overpaid_value_msat = self.route_params.as_ref()
482 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
483 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
486 /// Returns the total amount paid on this [`Route`], excluding the fees.
488 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
489 /// we had to reach the [`htlc_minimum_msat`] limits.
491 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
492 pub fn get_total_amount(&self) -> u64 {
493 self.paths.iter().map(|path| path.final_value_msat()).sum()
497 impl fmt::Display for Route {
498 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
499 log_route!(self).fmt(f)
503 const SERIALIZATION_VERSION: u8 = 1;
504 const MIN_SERIALIZATION_VERSION: u8 = 1;
506 impl Writeable for Route {
507 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
508 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
509 (self.paths.len() as u64).write(writer)?;
510 let mut blinded_tails = Vec::new();
511 for (idx, path) in self.paths.iter().enumerate() {
512 (path.hops.len() as u8).write(writer)?;
513 for hop in path.hops.iter() {
516 if let Some(blinded_tail) = &path.blinded_tail {
517 if blinded_tails.is_empty() {
518 blinded_tails = Vec::with_capacity(path.hops.len());
520 blinded_tails.push(None);
523 blinded_tails.push(Some(blinded_tail));
524 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
526 write_tlv_fields!(writer, {
527 // For compatibility with LDK versions prior to 0.0.117, we take the individual
528 // RouteParameters' fields and reconstruct them on read.
529 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
530 (2, blinded_tails, optional_vec),
531 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
532 (5, self.route_params.as_ref().and_then(|p| p.max_total_routing_fee_msat), option),
538 impl Readable for Route {
539 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
540 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
541 let path_count: u64 = Readable::read(reader)?;
542 if path_count == 0 { return Err(DecodeError::InvalidValue); }
543 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
544 let mut min_final_cltv_expiry_delta = u32::max_value();
545 for _ in 0..path_count {
546 let hop_count: u8 = Readable::read(reader)?;
547 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
548 for _ in 0..hop_count {
549 hops.push(Readable::read(reader)?);
551 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
552 min_final_cltv_expiry_delta =
553 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
554 paths.push(Path { hops, blinded_tail: None });
556 _init_and_read_len_prefixed_tlv_fields!(reader, {
557 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
558 (2, blinded_tails, optional_vec),
559 (3, final_value_msat, option),
560 (5, max_total_routing_fee_msat, option)
562 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
563 if blinded_tails.len() != 0 {
564 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
565 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
566 path.blinded_tail = blinded_tail_opt;
570 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
571 let route_params = match (payment_params, final_value_msat) {
572 (Some(payment_params), Some(final_value_msat)) => {
573 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
578 Ok(Route { paths, route_params })
582 /// Parameters needed to find a [`Route`].
584 /// Passed to [`find_route`] and [`build_route_from_hops`].
585 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
586 pub struct RouteParameters {
587 /// The parameters of the failed payment path.
588 pub payment_params: PaymentParameters,
590 /// The amount in msats sent on the failed payment path.
591 pub final_value_msat: u64,
593 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
595 /// This limit also applies to the total fees that may arise while retrying failed payment
598 /// Note that values below a few sats may result in some paths being spuriously ignored.
599 pub max_total_routing_fee_msat: Option<u64>,
602 impl RouteParameters {
603 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
605 /// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
606 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
607 Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
610 /// Sets the maximum number of hops that can be included in a payment path, based on the provided
611 /// [`RecipientOnionFields`] and blinded paths.
612 pub fn set_max_path_length(
613 &mut self, recipient_onion: &RecipientOnionFields, is_keysend: bool, best_block_height: u32
614 ) -> Result<(), ()> {
615 let keysend_preimage_opt = is_keysend.then(|| PaymentPreimage([42; 32]));
616 onion_utils::set_max_path_length(
617 self, recipient_onion, keysend_preimage_opt, best_block_height
622 impl Writeable for RouteParameters {
623 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
624 write_tlv_fields!(writer, {
625 (0, self.payment_params, required),
626 (1, self.max_total_routing_fee_msat, option),
627 (2, self.final_value_msat, required),
628 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
629 // `RouteParameters` directly. For compatibility, we write it here.
630 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
636 impl Readable for RouteParameters {
637 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
638 _init_and_read_len_prefixed_tlv_fields!(reader, {
639 (0, payment_params, (required: ReadableArgs, 0)),
640 (1, max_total_routing_fee_msat, option),
641 (2, final_value_msat, required),
642 (4, final_cltv_delta, option),
644 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
645 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
646 if final_cltv_expiry_delta == &0 {
647 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
652 final_value_msat: final_value_msat.0.unwrap(),
653 max_total_routing_fee_msat,
658 /// Maximum total CTLV difference we allow for a full payment path.
659 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
661 /// Maximum number of paths we allow an (MPP) payment to have.
662 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
663 // limits, but for now more than 10 paths likely carries too much one-path failure.
664 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
666 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
668 // The median hop CLTV expiry delta currently seen in the network.
669 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
671 /// Estimated maximum number of hops that can be included in a payment path. May be inaccurate if
672 /// payment metadata, custom TLVs, or blinded paths are included in the payment.
673 // During routing, we only consider paths shorter than our maximum length estimate.
674 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
675 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
676 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
678 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
679 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
680 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
681 // (payment_secret and total_msat) = 93 bytes for the final hop.
682 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
683 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
684 pub const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
686 /// Information used to route a payment.
687 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
688 pub struct PaymentParameters {
689 /// Information about the payee, such as their features and route hints for their channels.
692 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
693 pub expiry_time: Option<u64>,
695 /// The maximum total CLTV delta we accept for the route.
696 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
697 pub max_total_cltv_expiry_delta: u32,
699 /// The maximum number of paths that may be used by (MPP) payments.
700 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
701 pub max_path_count: u8,
703 /// The maximum number of [`Path::hops`] in any returned path.
704 /// Defaults to [`MAX_PATH_LENGTH_ESTIMATE`].
705 pub max_path_length: u8,
707 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
708 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
709 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
710 /// increasing failure probability for those paths.
712 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
713 /// restriction have been found. While paths which meet this criteria will be searched for, it
714 /// is ultimately up to the scorer to select them over other paths.
716 /// A value of 0 will allow payments up to and including a channel's total announced usable
717 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
720 pub max_channel_saturation_power_of_half: u8,
722 /// A list of SCIDs which this payment was previously attempted over and which caused the
723 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
725 pub previously_failed_channels: Vec<u64>,
727 /// A list of indices corresponding to blinded paths in [`Payee::Blinded::route_hints`] which this
728 /// payment was previously attempted over and which caused the payment to fail. Future attempts
729 /// for the same payment shouldn't be relayed through any of these blinded paths.
730 pub previously_failed_blinded_path_idxs: Vec<u64>,
733 impl Writeable for PaymentParameters {
734 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
735 let mut clear_hints = &vec![];
736 let mut blinded_hints = &vec![];
738 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
739 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
741 write_tlv_fields!(writer, {
742 (0, self.payee.node_id(), option),
743 (1, self.max_total_cltv_expiry_delta, required),
744 (2, self.payee.features(), option),
745 (3, self.max_path_count, required),
746 (4, *clear_hints, required_vec),
747 (5, self.max_channel_saturation_power_of_half, required),
748 (6, self.expiry_time, option),
749 (7, self.previously_failed_channels, required_vec),
750 (8, *blinded_hints, optional_vec),
751 (9, self.payee.final_cltv_expiry_delta(), option),
752 (11, self.previously_failed_blinded_path_idxs, required_vec),
753 (13, self.max_path_length, required),
759 impl ReadableArgs<u32> for PaymentParameters {
760 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
761 _init_and_read_len_prefixed_tlv_fields!(reader, {
762 (0, payee_pubkey, option),
763 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
764 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
765 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
766 (4, clear_route_hints, required_vec),
767 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
768 (6, expiry_time, option),
769 (7, previously_failed_channels, optional_vec),
770 (8, blinded_route_hints, optional_vec),
771 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
772 (11, previously_failed_blinded_path_idxs, optional_vec),
773 (13, max_path_length, (default_value, MAX_PATH_LENGTH_ESTIMATE)),
775 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
776 let payee = if blinded_route_hints.len() != 0 {
777 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
779 route_hints: blinded_route_hints,
780 features: features.and_then(|f: Features| f.bolt12()),
784 route_hints: clear_route_hints,
785 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
786 features: features.and_then(|f| f.bolt11()),
787 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
791 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
792 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
794 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
796 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
797 previously_failed_blinded_path_idxs: previously_failed_blinded_path_idxs.unwrap_or(Vec::new()),
798 max_path_length: _init_tlv_based_struct_field!(max_path_length, (default_value, unused)),
804 impl PaymentParameters {
805 /// Creates a payee with the node id of the given `pubkey`.
807 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
809 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
811 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
813 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
814 max_path_count: DEFAULT_MAX_PATH_COUNT,
815 max_path_length: MAX_PATH_LENGTH_ESTIMATE,
816 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
817 previously_failed_channels: Vec::new(),
818 previously_failed_blinded_path_idxs: Vec::new(),
822 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
824 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
827 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
828 /// whether your router will be allowed to find a multi-part route for this payment. If you
829 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
830 /// [`RecipientOnionFields::secret_only`].
832 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
833 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
834 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
835 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
836 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
839 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
840 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
841 /// [`PaymentParameters::expiry_time`].
842 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
843 Self::blinded(invoice.payment_paths().to_vec())
844 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
845 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
848 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
849 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
851 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
853 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
854 max_path_count: DEFAULT_MAX_PATH_COUNT,
855 max_path_length: MAX_PATH_LENGTH_ESTIMATE,
856 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
857 previously_failed_channels: Vec::new(),
858 previously_failed_blinded_path_idxs: Vec::new(),
862 /// Includes the payee's features. Errors if the parameters were not initialized with
863 /// [`PaymentParameters::from_bolt12_invoice`].
865 /// This is not exported to bindings users since bindings don't support move semantics
866 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
868 Payee::Clear { .. } => Err(()),
869 Payee::Blinded { route_hints, .. } =>
870 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
874 /// Includes the payee's features. Errors if the parameters were initialized with
875 /// [`PaymentParameters::from_bolt12_invoice`].
877 /// This is not exported to bindings users since bindings don't support move semantics
878 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
880 Payee::Blinded { .. } => Err(()),
881 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
883 payee: Payee::Clear {
884 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
890 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
891 /// [`PaymentParameters::from_bolt12_invoice`].
893 /// This is not exported to bindings users since bindings don't support move semantics
894 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
896 Payee::Blinded { .. } => Err(()),
897 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
899 payee: Payee::Clear {
900 route_hints, node_id, features, final_cltv_expiry_delta,
906 /// Includes a payment expiration in seconds relative to the UNIX epoch.
908 /// This is not exported to bindings users since bindings don't support move semantics
909 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
910 Self { expiry_time: Some(expiry_time), ..self }
913 /// Includes a limit for the total CLTV expiry delta which is considered during routing
915 /// This is not exported to bindings users since bindings don't support move semantics
916 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
917 Self { max_total_cltv_expiry_delta, ..self }
920 /// Includes a limit for the maximum number of payment paths that may be used.
922 /// This is not exported to bindings users since bindings don't support move semantics
923 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
924 Self { max_path_count, ..self }
927 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
928 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
930 /// This is not exported to bindings users since bindings don't support move semantics
931 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
932 Self { max_channel_saturation_power_of_half, ..self }
935 pub(crate) fn insert_previously_failed_blinded_path(&mut self, failed_blinded_tail: &BlindedTail) {
936 let mut found_blinded_tail = false;
937 for (idx, (_, path)) in self.payee.blinded_route_hints().iter().enumerate() {
938 if failed_blinded_tail.hops == path.blinded_hops &&
939 failed_blinded_tail.blinding_point == path.blinding_point
941 self.previously_failed_blinded_path_idxs.push(idx as u64);
942 found_blinded_tail = true;
945 debug_assert!(found_blinded_tail);
949 /// The recipient of a payment, differing based on whether they've hidden their identity with route
951 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
953 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
954 /// will be included in the final [`Route`].
956 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
958 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
959 /// Features supported by the payee.
961 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
963 features: Option<Bolt12InvoiceFeatures>,
965 /// The recipient included these route hints in their BOLT11 invoice.
967 /// The node id of the payee.
969 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
970 route_hints: Vec<RouteHint>,
971 /// Features supported by the payee.
973 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
974 /// does not contain any features.
976 /// [`for_keysend`]: PaymentParameters::for_keysend
977 features: Option<Bolt11InvoiceFeatures>,
978 /// The minimum CLTV delta at the end of the route. This value must not be zero.
979 final_cltv_expiry_delta: u32,
984 fn node_id(&self) -> Option<PublicKey> {
986 Self::Clear { node_id, .. } => Some(*node_id),
990 fn node_features(&self) -> Option<NodeFeatures> {
992 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
993 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
996 fn supports_basic_mpp(&self) -> bool {
998 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
999 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
1002 fn features(&self) -> Option<FeaturesRef> {
1004 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
1005 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
1008 fn final_cltv_expiry_delta(&self) -> Option<u32> {
1010 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
1014 pub(crate) fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
1016 Self::Blinded { route_hints, .. } => &route_hints[..],
1017 Self::Clear { .. } => &[]
1021 fn unblinded_route_hints(&self) -> &[RouteHint] {
1023 Self::Blinded { .. } => &[],
1024 Self::Clear { route_hints, .. } => &route_hints[..]
1029 enum FeaturesRef<'a> {
1030 Bolt11(&'a Bolt11InvoiceFeatures),
1031 Bolt12(&'a Bolt12InvoiceFeatures),
1034 Bolt11(Bolt11InvoiceFeatures),
1035 Bolt12(Bolt12InvoiceFeatures),
1039 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
1041 Self::Bolt12(f) => Some(f),
1045 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
1047 Self::Bolt11(f) => Some(f),
1053 impl<'a> Writeable for FeaturesRef<'a> {
1054 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1056 Self::Bolt11(f) => Ok(f.write(w)?),
1057 Self::Bolt12(f) => Ok(f.write(w)?),
1062 impl ReadableArgs<bool> for Features {
1063 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
1064 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
1065 Ok(Self::Bolt12(Readable::read(reader)?))
1069 /// A list of hops along a payment path terminating with a channel to the recipient.
1070 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1071 pub struct RouteHint(pub Vec<RouteHintHop>);
1073 impl Writeable for RouteHint {
1074 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1075 (self.0.len() as u64).write(writer)?;
1076 for hop in self.0.iter() {
1083 impl Readable for RouteHint {
1084 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1085 let hop_count: u64 = Readable::read(reader)?;
1086 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
1087 for _ in 0..hop_count {
1088 hops.push(Readable::read(reader)?);
1094 /// A channel descriptor for a hop along a payment path.
1096 /// While this generally comes from BOLT 11's `r` field, this struct includes more fields than are
1097 /// available in BOLT 11. Thus, encoding and decoding this via `lightning-invoice` is lossy, as
1098 /// fields not supported in BOLT 11 will be stripped.
1099 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1100 pub struct RouteHintHop {
1101 /// The node_id of the non-target end of the route
1102 pub src_node_id: PublicKey,
1103 /// The short_channel_id of this channel
1104 pub short_channel_id: u64,
1105 /// The fees which must be paid to use this channel
1106 pub fees: RoutingFees,
1107 /// The difference in CLTV values between this node and the next node.
1108 pub cltv_expiry_delta: u16,
1109 /// The minimum value, in msat, which must be relayed to the next hop.
1110 pub htlc_minimum_msat: Option<u64>,
1111 /// The maximum value in msat available for routing with a single HTLC.
1112 pub htlc_maximum_msat: Option<u64>,
1115 impl_writeable_tlv_based!(RouteHintHop, {
1116 (0, src_node_id, required),
1117 (1, htlc_minimum_msat, option),
1118 (2, short_channel_id, required),
1119 (3, htlc_maximum_msat, option),
1120 (4, fees, required),
1121 (6, cltv_expiry_delta, required),
1124 #[derive(Eq, PartialEq)]
1125 #[repr(align(64))] // Force the size to 64 bytes
1126 struct RouteGraphNode {
1129 // The maximum value a yet-to-be-constructed payment path might flow through this node.
1130 // This value is upper-bounded by us by:
1131 // - how much is needed for a path being constructed
1132 // - how much value can channels following this node (up to the destination) can contribute,
1133 // considering their capacity and fees
1134 value_contribution_msat: u64,
1135 total_cltv_delta: u32,
1136 /// The number of hops walked up to this node.
1137 path_length_to_node: u8,
1140 impl cmp::Ord for RouteGraphNode {
1141 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
1142 other.score.cmp(&self.score).then_with(|| other.node_id.cmp(&self.node_id))
1146 impl cmp::PartialOrd for RouteGraphNode {
1147 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
1148 Some(self.cmp(other))
1152 // While RouteGraphNode can be laid out with fewer bytes, performance appears to be improved
1153 // substantially when it is laid out at exactly 64 bytes.
1155 // Thus, we use `#[repr(C)]` on the struct to force a suboptimal layout and check that it stays 64
1157 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1158 const _GRAPH_NODE_SMALL: usize = 64 - core::mem::size_of::<RouteGraphNode>();
1159 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1160 const _GRAPH_NODE_FIXED_SIZE: usize = core::mem::size_of::<RouteGraphNode>() - 64;
1162 /// A [`CandidateRouteHop::FirstHop`] entry.
1163 #[derive(Clone, Debug)]
1164 pub struct FirstHopCandidate<'a> {
1165 /// Channel details of the first hop
1167 /// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1168 /// has been funded and is able to pay), and accessor methods may panic otherwise.
1170 /// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1172 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1173 pub details: &'a ChannelDetails,
1174 /// The node id of the payer, which is also the source side of this candidate route hop.
1176 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1177 pub payer_node_id: &'a NodeId,
1180 /// A [`CandidateRouteHop::PublicHop`] entry.
1181 #[derive(Clone, Debug)]
1182 pub struct PublicHopCandidate<'a> {
1183 /// Information about the channel, including potentially its capacity and
1184 /// direction-specific information.
1186 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1187 pub info: DirectedChannelInfo<'a>,
1188 /// The short channel ID of the channel, i.e. the identifier by which we refer to this
1190 pub short_channel_id: u64,
1193 /// A [`CandidateRouteHop::PrivateHop`] entry.
1194 #[derive(Clone, Debug)]
1195 pub struct PrivateHopCandidate<'a> {
1196 /// Information about the private hop communicated via BOLT 11.
1198 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1199 pub hint: &'a RouteHintHop,
1200 /// Node id of the next hop in BOLT 11 route hint.
1202 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1203 pub target_node_id: &'a NodeId
1206 /// A [`CandidateRouteHop::Blinded`] entry.
1207 #[derive(Clone, Debug)]
1208 pub struct BlindedPathCandidate<'a> {
1209 /// The node id of the introduction node, resolved from either the [`NetworkGraph`] or first
1212 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1213 pub source_node_id: &'a NodeId,
1214 /// Information about the blinded path including the fee, HTLC amount limits, and
1215 /// cryptographic material required to build an HTLC through the given path.
1217 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1218 pub hint: &'a (BlindedPayInfo, BlindedPath),
1219 /// Index of the hint in the original list of blinded hints.
1221 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1222 /// a short channel ID for this hop.
1226 /// A [`CandidateRouteHop::OneHopBlinded`] entry.
1227 #[derive(Clone, Debug)]
1228 pub struct OneHopBlindedPathCandidate<'a> {
1229 /// The node id of the introduction node, resolved from either the [`NetworkGraph`] or first
1232 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1233 pub source_node_id: &'a NodeId,
1234 /// Information about the blinded path including the fee, HTLC amount limits, and
1235 /// cryptographic material required to build an HTLC terminating with the given path.
1237 /// Note that the [`BlindedPayInfo`] is ignored here.
1239 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1240 pub hint: &'a (BlindedPayInfo, BlindedPath),
1241 /// Index of the hint in the original list of blinded hints.
1243 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1244 /// a short channel ID for this hop.
1248 /// A wrapper around the various hop representations.
1250 /// Can be used to examine the properties of a hop,
1251 /// potentially to decide whether to include it in a route.
1252 #[derive(Clone, Debug)]
1253 pub enum CandidateRouteHop<'a> {
1254 /// A hop from the payer, where the outbound liquidity is known.
1255 FirstHop(FirstHopCandidate<'a>),
1256 /// A hop found in the [`ReadOnlyNetworkGraph`].
1257 PublicHop(PublicHopCandidate<'a>),
1258 /// A private hop communicated by the payee, generally via a BOLT 11 invoice.
1260 /// Because BOLT 11 route hints can take multiple hops to get to the destination, this may not
1261 /// terminate at the payee.
1262 PrivateHop(PrivateHopCandidate<'a>),
1263 /// A blinded path which starts with an introduction point and ultimately terminates with the
1266 /// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1267 /// `None` in this state.
1269 /// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1270 /// path, the full path is treated as a single [`CandidateRouteHop`].
1271 Blinded(BlindedPathCandidate<'a>),
1272 /// Similar to [`Self::Blinded`], but the path here only has one hop.
1274 /// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1275 /// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1276 /// payee's identity - it's the introduction point!
1278 /// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1279 /// to the hops *between* the introduction node and the destination.
1281 /// This primarily exists to track that we need to included a blinded path at the end of our
1282 /// [`Route`], even though it doesn't actually add an additional hop in the payment.
1283 OneHopBlinded(OneHopBlindedPathCandidate<'a>),
1286 impl<'a> CandidateRouteHop<'a> {
1287 /// Returns the short channel ID for this hop, if one is known.
1289 /// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1290 /// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1292 /// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1293 /// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1294 /// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1295 /// (which is always true for channels which are funded and ready for use).
1297 /// In other words, this should always return `Some` as long as the candidate hop is not a
1298 /// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1300 /// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1301 /// define a global namespace.
1303 fn short_channel_id(&self) -> Option<u64> {
1305 CandidateRouteHop::FirstHop(hop) => hop.details.get_outbound_payment_scid(),
1306 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1307 CandidateRouteHop::PrivateHop(hop) => Some(hop.hint.short_channel_id),
1308 CandidateRouteHop::Blinded(_) => None,
1309 CandidateRouteHop::OneHopBlinded(_) => None,
1313 /// Returns the globally unique short channel ID for this hop, if one is known.
1315 /// This only returns `Some` if the channel is public (either our own, or one we've learned
1316 /// from the public network graph), and thus the short channel ID we have for this channel is
1317 /// globally unique and identifies this channel in a global namespace.
1319 pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1321 CandidateRouteHop::FirstHop(hop) => if hop.details.is_public { hop.details.short_channel_id } else { None },
1322 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1323 CandidateRouteHop::PrivateHop(_) => None,
1324 CandidateRouteHop::Blinded(_) => None,
1325 CandidateRouteHop::OneHopBlinded(_) => None,
1329 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1330 fn features(&self) -> ChannelFeatures {
1332 CandidateRouteHop::FirstHop(hop) => hop.details.counterparty.features.to_context(),
1333 CandidateRouteHop::PublicHop(hop) => hop.info.channel().features.clone(),
1334 CandidateRouteHop::PrivateHop(_) => ChannelFeatures::empty(),
1335 CandidateRouteHop::Blinded(_) => ChannelFeatures::empty(),
1336 CandidateRouteHop::OneHopBlinded(_) => ChannelFeatures::empty(),
1340 /// Returns the required difference in HTLC CLTV expiry between the [`Self::source`] and the
1341 /// next-hop for an HTLC taking this hop.
1343 /// This is the time that the node(s) in this hop have to claim the HTLC on-chain if the
1344 /// next-hop goes on chain with a payment preimage.
1346 pub fn cltv_expiry_delta(&self) -> u32 {
1348 CandidateRouteHop::FirstHop(_) => 0,
1349 CandidateRouteHop::PublicHop(hop) => hop.info.direction().cltv_expiry_delta as u32,
1350 CandidateRouteHop::PrivateHop(hop) => hop.hint.cltv_expiry_delta as u32,
1351 CandidateRouteHop::Blinded(hop) => hop.hint.0.cltv_expiry_delta as u32,
1352 CandidateRouteHop::OneHopBlinded(_) => 0,
1356 /// Returns the minimum amount that can be sent over this hop, in millisatoshis.
1358 pub fn htlc_minimum_msat(&self) -> u64 {
1360 CandidateRouteHop::FirstHop(hop) => hop.details.next_outbound_htlc_minimum_msat,
1361 CandidateRouteHop::PublicHop(hop) => hop.info.direction().htlc_minimum_msat,
1362 CandidateRouteHop::PrivateHop(hop) => hop.hint.htlc_minimum_msat.unwrap_or(0),
1363 CandidateRouteHop::Blinded(hop) => hop.hint.0.htlc_minimum_msat,
1364 CandidateRouteHop::OneHopBlinded { .. } => 0,
1368 /// Returns the fees that must be paid to route an HTLC over this channel.
1370 pub fn fees(&self) -> RoutingFees {
1372 CandidateRouteHop::FirstHop(_) => RoutingFees {
1373 base_msat: 0, proportional_millionths: 0,
1375 CandidateRouteHop::PublicHop(hop) => hop.info.direction().fees,
1376 CandidateRouteHop::PrivateHop(hop) => hop.hint.fees,
1377 CandidateRouteHop::Blinded(hop) => {
1379 base_msat: hop.hint.0.fee_base_msat,
1380 proportional_millionths: hop.hint.0.fee_proportional_millionths
1383 CandidateRouteHop::OneHopBlinded(_) =>
1384 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1388 /// Fetch the effective capacity of this hop.
1390 /// Note that this may be somewhat expensive, so calls to this should be limited and results
1392 fn effective_capacity(&self) -> EffectiveCapacity {
1394 CandidateRouteHop::FirstHop(hop) => EffectiveCapacity::ExactLiquidity {
1395 liquidity_msat: hop.details.next_outbound_htlc_limit_msat,
1397 CandidateRouteHop::PublicHop(hop) => hop.info.effective_capacity(),
1398 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. }) =>
1399 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1400 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. }) =>
1401 EffectiveCapacity::Infinite,
1402 CandidateRouteHop::Blinded(hop) =>
1403 EffectiveCapacity::HintMaxHTLC { amount_msat: hop.hint.0.htlc_maximum_msat },
1404 CandidateRouteHop::OneHopBlinded(_) => EffectiveCapacity::Infinite,
1408 /// Returns an ID describing the given hop.
1410 /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1412 fn id(&self) -> CandidateHopId {
1414 CandidateRouteHop::Blinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1415 CandidateRouteHop::OneHopBlinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1416 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1419 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1421 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1427 fn blinded_hint_idx(&self) -> Option<usize> {
1429 Self::Blinded(BlindedPathCandidate { hint_idx, .. }) |
1430 Self::OneHopBlinded(OneHopBlindedPathCandidate { hint_idx, .. }) => {
1436 /// Returns the source node id of current hop.
1438 /// Source node id refers to the node forwarding the HTLC through this hop.
1440 /// For [`Self::FirstHop`] we return payer's node id.
1442 pub fn source(&self) -> NodeId {
1444 CandidateRouteHop::FirstHop(hop) => *hop.payer_node_id,
1445 CandidateRouteHop::PublicHop(hop) => *hop.info.source(),
1446 CandidateRouteHop::PrivateHop(hop) => hop.hint.src_node_id.into(),
1447 CandidateRouteHop::Blinded(hop) => *hop.source_node_id,
1448 CandidateRouteHop::OneHopBlinded(hop) => *hop.source_node_id,
1451 /// Returns the target node id of this hop, if known.
1453 /// Target node id refers to the node receiving the HTLC after this hop.
1455 /// For [`Self::Blinded`] we return `None` because the ultimate destination after the blinded
1456 /// path is unknown.
1458 /// For [`Self::OneHopBlinded`] we return `None` because the target is the same as the source,
1459 /// and such a return value would be somewhat nonsensical.
1461 pub fn target(&self) -> Option<NodeId> {
1463 CandidateRouteHop::FirstHop(hop) => Some(hop.details.counterparty.node_id.into()),
1464 CandidateRouteHop::PublicHop(hop) => Some(*hop.info.target()),
1465 CandidateRouteHop::PrivateHop(hop) => Some(*hop.target_node_id),
1466 CandidateRouteHop::Blinded(_) => None,
1467 CandidateRouteHop::OneHopBlinded(_) => None,
1472 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1474 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1476 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1477 /// isn't guaranteed to be unique at all.
1479 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1480 /// difficult-to-use API.
1481 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1482 enum CandidateHopId {
1483 /// Contains (scid, src_node_id < target_node_id)
1485 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1490 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1491 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1493 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1494 EffectiveCapacity::Infinite => u64::max_value(),
1495 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1496 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1497 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1498 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1499 // expected to have been generated from up-to-date capacity information.
1500 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1501 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1502 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1506 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1507 -> bool where I1::Item: PartialEq<I2::Item> {
1509 let a = iter_a.next();
1510 let b = iter_b.next();
1511 if a.is_none() && b.is_none() { return true; }
1512 if a.is_none() || b.is_none() { return false; }
1513 if a.unwrap().ne(&b.unwrap()) { return false; }
1517 /// It's useful to keep track of the hops associated with the fees required to use them,
1518 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1519 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1520 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1522 #[repr(C)] // Force fields to appear in the order we define them.
1523 struct PathBuildingHop<'a> {
1524 candidate: CandidateRouteHop<'a>,
1525 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1526 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1527 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1528 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1529 /// avoid processing them again.
1530 was_processed: bool,
1531 /// Used to compare channels when choosing the for routing.
1532 /// Includes paying for the use of a hop and the following hops, as well as
1533 /// an estimated cost of reaching this hop.
1534 /// Might get stale when fees are recomputed. Primarily for internal use.
1535 total_fee_msat: u64,
1536 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1537 /// walk and may be invalid thereafter.
1538 path_htlc_minimum_msat: u64,
1539 /// All penalties incurred from this channel on the way to the destination, as calculated using
1540 /// channel scoring.
1541 path_penalty_msat: u64,
1543 // The last 16 bytes are on the next cache line by default in glibc's malloc. Thus, we should
1544 // only place fields which are not hot there. Luckily, the next three fields are only read if
1545 // we end up on the selected path, and only in the final path layout phase, so we don't care
1546 // too much if reading them is slow.
1550 /// All the fees paid *after* this channel on the way to the destination
1551 next_hops_fee_msat: u64,
1552 /// Fee paid for the use of the current channel (see candidate.fees()).
1553 /// The value will be actually deducted from the counterparty balance on the previous link.
1554 hop_use_fee_msat: u64,
1556 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1557 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1558 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1559 // value_contribution_msat, which requires tracking it here. See comments below where it is
1560 // used for more info.
1561 value_contribution_msat: u64,
1564 // Checks that the entries in the `find_route` `dist` map fit in (exactly) two standard x86-64
1565 // cache lines. Sadly, they're not guaranteed to actually lie on a cache line (and in fact,
1566 // generally won't, because at least glibc's malloc will align to a nice, big, round
1567 // boundary...plus 16), but at least it will reduce the amount of data we'll need to load.
1569 // Note that these assertions only pass on somewhat recent rustc, and thus are gated on the
1572 const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::<(NodeId, PathBuildingHop)>();
1574 const _NODE_MAP_SIZE_EXACTLY_CACHE_LINES: usize = core::mem::size_of::<(NodeId, PathBuildingHop)>() - 128;
1576 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1577 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1578 let mut debug_struct = f.debug_struct("PathBuildingHop");
1580 .field("node_id", &self.candidate.target())
1581 .field("short_channel_id", &self.candidate.short_channel_id())
1582 .field("total_fee_msat", &self.total_fee_msat)
1583 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1584 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1585 .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)))
1586 .field("path_penalty_msat", &self.path_penalty_msat)
1587 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1588 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1589 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1590 let debug_struct = debug_struct
1591 .field("value_contribution_msat", &self.value_contribution_msat);
1592 debug_struct.finish()
1596 // Instantiated with a list of hops with correct data in them collected during path finding,
1597 // an instance of this struct should be further modified only via given methods.
1599 struct PaymentPath<'a> {
1600 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1603 impl<'a> PaymentPath<'a> {
1604 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1605 fn get_value_msat(&self) -> u64 {
1606 self.hops.last().unwrap().0.fee_msat
1609 fn get_path_penalty_msat(&self) -> u64 {
1610 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1613 fn get_total_fee_paid_msat(&self) -> u64 {
1614 if self.hops.len() < 1 {
1618 // Can't use next_hops_fee_msat because it gets outdated.
1619 for (i, (hop, _)) in self.hops.iter().enumerate() {
1620 if i != self.hops.len() - 1 {
1621 result += hop.fee_msat;
1627 fn get_cost_msat(&self) -> u64 {
1628 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1631 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1632 // to change fees may result in an inconsistency.
1634 // Sometimes we call this function right after constructing a path which is inconsistent in
1635 // that it the value being transferred has decreased while we were doing path finding, leading
1636 // to the fees being paid not lining up with the actual limits.
1638 // Note that this function is not aware of the available_liquidity limit, and thus does not
1639 // support increasing the value being transferred beyond what was selected during the initial
1642 // Returns the amount that this path contributes to the total payment value, which may be greater
1643 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1644 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1645 let mut extra_contribution_msat = 0;
1646 let mut total_fee_paid_msat = 0 as u64;
1647 for i in (0..self.hops.len()).rev() {
1648 let last_hop = i == self.hops.len() - 1;
1650 // For non-last-hop, this value will represent the fees paid on the current hop. It
1651 // will consist of the fees for the use of the next hop, and extra fees to match
1652 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1653 let mut cur_hop_fees_msat = 0;
1655 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1658 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1659 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1660 cur_hop.path_penalty_msat += extra_contribution_msat;
1661 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1662 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1663 // set it too high just to maliciously take more fees by exploiting this
1664 // match htlc_minimum_msat logic.
1665 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1666 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1667 // Note that there is a risk that *previous hops* (those closer to us, as we go
1668 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1670 // This might make us end up with a broken route, although this should be super-rare
1671 // in practice, both because of how healthy channels look like, and how we pick
1672 // channels in add_entry.
1673 // Also, this can't be exploited more heavily than *announce a free path and fail
1675 cur_hop_transferred_amount_msat += extra_fees_msat;
1677 // We remember and return the extra fees on the final hop to allow accounting for
1678 // them in the path's value contribution.
1680 extra_contribution_msat = extra_fees_msat;
1682 total_fee_paid_msat += extra_fees_msat;
1683 cur_hop_fees_msat += extra_fees_msat;
1688 // Final hop is a special case: it usually has just value_msat (by design), but also
1689 // it still could overpay for the htlc_minimum_msat.
1690 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1692 // Propagate updated fees for the use of the channels to one hop back, where they
1693 // will be actually paid (fee_msat). The last hop is handled above separately.
1694 cur_hop.fee_msat = cur_hop_fees_msat;
1697 // Fee for the use of the current hop which will be deducted on the previous hop.
1698 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1699 // this channel is free for us.
1701 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1702 cur_hop.hop_use_fee_msat = new_fee;
1703 total_fee_paid_msat += new_fee;
1705 // It should not be possible because this function is called only to reduce the
1706 // value. In that case, compute_fee was already called with the same fees for
1707 // larger amount and there was no overflow.
1712 value_msat + extra_contribution_msat
1717 /// Calculate the fees required to route the given amount over a channel with the given fees.
1718 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1719 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1720 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1724 /// Calculate the fees required to route the given amount over a channel with the given fees,
1725 /// saturating to [`u64::max_value`].
1726 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1727 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1728 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1729 .saturating_add(channel_fees.base_msat as u64)
1732 /// The default `features` we assume for a node in a route, when no `features` are known about that
1735 /// Default features are:
1736 /// * variable_length_onion_optional
1737 fn default_node_features() -> NodeFeatures {
1738 let mut features = NodeFeatures::empty();
1739 features.set_variable_length_onion_optional();
1743 struct LoggedPayeePubkey(Option<PublicKey>);
1744 impl fmt::Display for LoggedPayeePubkey {
1745 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1748 "payee node id ".fmt(f)?;
1752 "blinded payee".fmt(f)
1758 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1759 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1760 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1762 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1763 "blinded route hint with introduction node ".fmt(f)?;
1764 match &hint.1.introduction_node {
1765 IntroductionNode::NodeId(pubkey) => write!(f, "id {}", pubkey)?,
1766 IntroductionNode::DirectedShortChannelId(direction, scid) => {
1768 Direction::NodeOne => {
1769 write!(f, "one on channel with SCID {}", scid)?;
1771 Direction::NodeTwo => {
1772 write!(f, "two on channel with SCID {}", scid)?;
1777 " and blinding point ".fmt(f)?;
1778 hint.1.blinding_point.fmt(f)
1780 CandidateRouteHop::FirstHop(_) => {
1781 "first hop with SCID ".fmt(f)?;
1782 self.0.short_channel_id().unwrap().fmt(f)
1784 CandidateRouteHop::PrivateHop(_) => {
1785 "route hint with SCID ".fmt(f)?;
1786 self.0.short_channel_id().unwrap().fmt(f)
1790 self.0.short_channel_id().unwrap().fmt(f)
1797 fn sort_first_hop_channels(
1798 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1799 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1801 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1802 // most like to use.
1804 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1805 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1808 // Second, because simply always sorting in descending order would always use our largest
1809 // available outbound capacity, needlessly fragmenting our available channel capacities,
1810 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1811 // which have enough, but not too much, capacity for the payment.
1813 // Available outbound balances factor in liquidity already reserved for previously found paths.
1814 channels.sort_unstable_by(|chan_a, chan_b| {
1815 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1816 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1817 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1818 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1819 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1820 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1821 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1822 // Sort in descending order
1823 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1825 // Sort in ascending order
1826 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1831 /// Finds a route from us (payer) to the given target node (payee).
1833 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1834 /// in the given [`RouteParameters::payment_params`].
1835 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1837 /// Private routing paths between a public node and the target may be included in the `payee` field
1838 /// of [`RouteParameters::payment_params`].
1840 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1841 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1842 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1844 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1845 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1846 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1850 /// Panics if first_hops contains channels without `short_channel_id`s;
1851 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1853 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1854 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1855 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1856 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1857 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1858 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1859 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1860 ) -> Result<Route, LightningError>
1861 where L::Target: Logger, GL::Target: Logger {
1862 let graph_lock = network_graph.read_only();
1863 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1864 scorer, score_params, random_seed_bytes)?;
1865 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1869 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1870 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1871 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1872 _random_seed_bytes: &[u8; 32]
1873 ) -> Result<Route, LightningError>
1874 where L::Target: Logger {
1876 let payment_params = &route_params.payment_params;
1877 let max_path_length = core::cmp::min(payment_params.max_path_length, MAX_PATH_LENGTH_ESTIMATE);
1878 let final_value_msat = route_params.final_value_msat;
1879 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1880 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1881 // so use a dummy id for this in the blinded case.
1882 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1883 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1884 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1885 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1886 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1888 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1889 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1891 if our_node_id == maybe_dummy_payee_node_id {
1892 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1895 if final_value_msat > MAX_VALUE_MSAT {
1896 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1899 if final_value_msat == 0 {
1900 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1903 let introduction_node_id_cache = payment_params.payee.blinded_route_hints().iter()
1904 .map(|(_, path)| path.public_introduction_node_id(network_graph))
1905 .collect::<Vec<_>>();
1906 match &payment_params.payee {
1907 Payee::Clear { route_hints, node_id, .. } => {
1908 for route in route_hints.iter() {
1909 for hop in &route.0 {
1910 if hop.src_node_id == *node_id {
1911 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1916 Payee::Blinded { route_hints, .. } => {
1917 if introduction_node_id_cache.iter().all(|introduction_node_id| *introduction_node_id == Some(&our_node_id)) {
1918 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});
1920 for ((_, blinded_path), introduction_node_id) in route_hints.iter().zip(introduction_node_id_cache.iter()) {
1921 if blinded_path.blinded_hops.len() == 0 {
1922 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1923 } else if *introduction_node_id == Some(&our_node_id) {
1924 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1925 } else if blinded_path.blinded_hops.len() == 1 &&
1927 .iter().zip(introduction_node_id_cache.iter())
1928 .filter(|((_, p), _)| p.blinded_hops.len() == 1)
1929 .any(|(_, p_introduction_node_id)| p_introduction_node_id != introduction_node_id)
1931 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1936 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1937 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1938 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});
1941 // The general routing idea is the following:
1942 // 1. Fill first/last hops communicated by the caller.
1943 // 2. Attempt to construct a path from payer to payee for transferring
1944 // any ~sufficient (described later) value.
1945 // If succeed, remember which channels were used and how much liquidity they have available,
1946 // so that future paths don't rely on the same liquidity.
1947 // 3. Proceed to the next step if:
1948 // - we hit the recommended target value;
1949 // - OR if we could not construct a new path. Any next attempt will fail too.
1950 // Otherwise, repeat step 2.
1951 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1952 // (not recommended value).
1953 // 5. If yes, proceed. If not, fail routing.
1954 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1955 // transferred up to the transfer target value.
1956 // 7. Reduce the value of the last path until we are sending only the target value.
1957 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1958 // them so that we're not sending two HTLCs along the same path.
1960 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1961 // distance from the payee
1963 // We are not a faithful Dijkstra's implementation because we can change values which impact
1964 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1965 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1966 // the value we are currently attempting to send over a path, we simply reduce the value being
1967 // sent along the path for any hops after that channel. This may imply that later fees (which
1968 // we've already tabulated) are lower because a smaller value is passing through the channels
1969 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1970 // channels which were selected earlier (and which may still be used for other paths without a
1971 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1974 // One potentially problematic case for this algorithm would be if there are many
1975 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1976 // graph walking), we may never find a path which is not liquidity-limited and has lower
1977 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1978 // Because we only consider paths with at least 5% of the total value being sent, the damage
1979 // from such a case should be limited, however this could be further reduced in the future by
1980 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1981 // limits for the purposes of fee calculation.
1983 // Alternatively, we could store more detailed path information in the heap (targets, below)
1984 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1985 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1986 // and practically (as we would need to store dynamically-allocated path information in heap
1987 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1988 // results of such an algorithm would likely be biased towards lower-value paths.
1990 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1991 // outside of our current search value, running a path search more times to gather candidate
1992 // paths at different values. While this may be acceptable, further path searches may increase
1993 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1994 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1995 // the same time, remaining generic across different payment values.
1997 let network_channels = network_graph.channels();
1998 let network_nodes = network_graph.nodes();
2000 if payment_params.max_path_count == 0 {
2001 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
2004 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
2005 // it. If the payee supports it they're supposed to include it in the invoice, so that should
2007 let allow_mpp = if payment_params.max_path_count == 1 {
2009 } else if payment_params.payee.supports_basic_mpp() {
2011 } else if let Some(payee) = payee_node_id_opt {
2012 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
2013 |info| info.features().supports_basic_mpp()))
2016 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
2018 let first_hop_count = first_hops.map(|hops| hops.len()).unwrap_or(0);
2019 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph of {} nodes and {} channels with a fee limit of {} msat",
2020 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
2021 if allow_mpp { "with" } else { "without" },
2022 first_hop_count, if first_hops.is_some() { "" } else { "not " },
2023 network_graph.nodes().len(), network_graph.channels().len(),
2024 max_total_routing_fee_msat);
2026 if first_hop_count < 10 {
2027 if let Some(hops) = first_hops {
2031 " First hop through {}/{} can send between {}msat and {}msat (inclusive).",
2032 hop.counterparty.node_id,
2033 hop.get_outbound_payment_scid().unwrap_or(0),
2034 hop.next_outbound_htlc_minimum_msat,
2035 hop.next_outbound_htlc_limit_msat
2042 // Prepare the data we'll use for payee-to-payer search by
2043 // inserting first hops suggested by the caller as targets.
2044 // Our search will then attempt to reach them while traversing from the payee node.
2045 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
2046 hash_map_with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
2047 if let Some(hops) = first_hops {
2049 if chan.get_outbound_payment_scid().is_none() {
2050 panic!("first_hops should be filled in with usable channels, not pending ones");
2052 if chan.counterparty.node_id == *our_node_pubkey {
2053 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
2056 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
2057 .or_insert(Vec::new())
2060 if first_hop_targets.is_empty() {
2061 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
2065 let mut private_hop_key_cache = hash_map_with_capacity(
2066 payment_params.payee.unblinded_route_hints().iter().map(|path| path.0.len()).sum()
2069 // Because we store references to private hop node_ids in `dist`, below, we need them to exist
2070 // (as `NodeId`, not `PublicKey`) for the lifetime of `dist`. Thus, we calculate all the keys
2071 // we'll need here and simply fetch them when routing.
2072 private_hop_key_cache.insert(maybe_dummy_payee_pk, NodeId::from_pubkey(&maybe_dummy_payee_pk));
2073 for route in payment_params.payee.unblinded_route_hints().iter() {
2074 for hop in route.0.iter() {
2075 private_hop_key_cache.insert(hop.src_node_id, NodeId::from_pubkey(&hop.src_node_id));
2079 // The main heap containing all candidate next-hops sorted by their score (max(fee,
2080 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
2081 // adding duplicate entries when we find a better path to a given node.
2082 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
2084 // Map from node_id to information about the best current path to that node, including feerate
2086 let mut dist: HashMap<NodeId, PathBuildingHop> = hash_map_with_capacity(network_nodes.len());
2088 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
2089 // indicating that we may wish to try again with a higher value, potentially paying to meet an
2090 // htlc_minimum with extra fees while still finding a cheaper path.
2091 let mut hit_minimum_limit;
2093 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
2094 // We start with a path_value of the exact amount we want, and if that generates a route we may
2095 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
2096 // amount we want in total across paths, selecting the best subset at the end.
2097 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
2098 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
2099 let mut path_value_msat = final_value_msat;
2101 // Routing Fragmentation Mitigation heuristic:
2103 // Routing fragmentation across many payment paths increases the overall routing
2104 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
2105 // Taking too many smaller paths also increases the chance of payment failure.
2106 // Thus to avoid this effect, we require from our collected links to provide
2107 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
2108 // This requirement is currently set to be 1/max_path_count of the payment
2109 // value to ensure we only ever return routes that do not violate this limit.
2110 let minimal_value_contribution_msat: u64 = if allow_mpp {
2111 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
2116 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
2117 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
2118 // drop the requirement by setting this to 0.
2119 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
2121 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
2122 // determine if the channel can be used by additional MPP paths or to inform path finding
2123 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
2124 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
2126 let mut used_liquidities: HashMap<CandidateHopId, u64> =
2127 hash_map_with_capacity(network_nodes.len());
2129 // Keeping track of how much value we already collected across other paths. Helps to decide
2130 // when we want to stop looking for new paths.
2131 let mut already_collected_value_msat = 0;
2133 for (_, channels) in first_hop_targets.iter_mut() {
2134 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
2138 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
2139 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
2141 // Remember how many candidates we ignored to allow for some logging afterwards.
2142 let mut num_ignored_value_contribution: u32 = 0;
2143 let mut num_ignored_path_length_limit: u32 = 0;
2144 let mut num_ignored_cltv_delta_limit: u32 = 0;
2145 let mut num_ignored_previously_failed: u32 = 0;
2146 let mut num_ignored_total_fee_limit: u32 = 0;
2147 let mut num_ignored_avoid_overpayment: u32 = 0;
2148 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
2150 macro_rules! add_entry {
2151 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
2152 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
2153 // since that value has to be transferred over this channel.
2154 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
2155 ( $candidate: expr, $next_hops_fee_msat: expr,
2156 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
2157 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
2158 // We "return" whether we updated the path at the end, and how much we can route via
2159 // this channel, via this:
2160 let mut hop_contribution_amt_msat = None;
2161 // Channels to self should not be used. This is more of belt-and-suspenders, because in
2162 // practice these cases should be caught earlier:
2163 // - for regular channels at channel announcement (TODO)
2164 // - for first and last hops early in get_route
2165 let src_node_id = $candidate.source();
2166 if Some(src_node_id) != $candidate.target() {
2167 let scid_opt = $candidate.short_channel_id();
2168 let effective_capacity = $candidate.effective_capacity();
2169 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
2171 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
2172 // It may be misleading because we might later choose to reduce the value transferred
2173 // over these channels, and the channel which was insufficient might become sufficient.
2174 // Worst case: we drop a good channel here because it can't cover the high following
2175 // fees caused by one expensive channel, but then this channel could have been used
2176 // if the amount being transferred over this path is lower.
2177 // We do this for now, but this is a subject for removal.
2178 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
2179 let used_liquidity_msat = used_liquidities
2180 .get(&$candidate.id())
2181 .map_or(0, |used_liquidity_msat| {
2182 available_value_contribution_msat = available_value_contribution_msat
2183 .saturating_sub(*used_liquidity_msat);
2184 *used_liquidity_msat
2187 // Verify the liquidity offered by this channel complies to the minimal contribution.
2188 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
2189 // Do not consider candidate hops that would exceed the maximum path length.
2190 let path_length_to_node = $next_hops_path_length
2191 + if $candidate.blinded_hint_idx().is_some() { 0 } else { 1 };
2192 let exceeds_max_path_length = path_length_to_node > max_path_length;
2194 // Do not consider candidates that exceed the maximum total cltv expiry limit.
2195 // In order to already account for some of the privacy enhancing random CLTV
2196 // expiry delta offset we add on top later, we subtract a rough estimate
2197 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
2198 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
2199 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
2200 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
2201 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
2202 .saturating_add($candidate.cltv_expiry_delta());
2203 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
2205 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
2206 // Includes paying fees for the use of the following channels.
2207 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
2208 Some(result) => result,
2209 // Can't overflow due to how the values were computed right above.
2210 None => unreachable!(),
2212 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2213 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
2214 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
2216 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2217 let may_overpay_to_meet_path_minimum_msat =
2218 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
2219 recommended_value_msat >= $candidate.htlc_minimum_msat()) ||
2220 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
2221 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
2223 let payment_failed_on_this_channel = match scid_opt {
2224 Some(scid) => payment_params.previously_failed_channels.contains(&scid),
2225 None => match $candidate.blinded_hint_idx() {
2227 payment_params.previously_failed_blinded_path_idxs.contains(&(idx as u64))
2233 let (should_log_candidate, first_hop_details) = match $candidate {
2234 CandidateRouteHop::FirstHop(hop) => (true, Some(hop.details)),
2235 CandidateRouteHop::PrivateHop(_) => (true, None),
2236 CandidateRouteHop::Blinded(_) => (true, None),
2237 CandidateRouteHop::OneHopBlinded(_) => (true, None),
2241 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
2242 // bother considering this channel. If retrying with recommended_value_msat may
2243 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
2244 // around again with a higher amount.
2245 if !contributes_sufficient_value {
2246 if should_log_candidate {
2247 log_trace!(logger, "Ignoring {} due to insufficient value contribution (channel max {:?}).",
2248 LoggedCandidateHop(&$candidate),
2249 effective_capacity);
2251 num_ignored_value_contribution += 1;
2252 } else if exceeds_max_path_length {
2253 if should_log_candidate {
2254 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
2256 num_ignored_path_length_limit += 1;
2257 } else if exceeds_cltv_delta_limit {
2258 if should_log_candidate {
2259 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
2261 if let Some(_) = first_hop_details {
2263 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
2264 hop_total_cltv_delta,
2265 max_total_cltv_expiry_delta,
2269 num_ignored_cltv_delta_limit += 1;
2270 } else if payment_failed_on_this_channel {
2271 if should_log_candidate {
2272 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
2274 num_ignored_previously_failed += 1;
2275 } else if may_overpay_to_meet_path_minimum_msat {
2276 if should_log_candidate {
2278 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit ({}).",
2279 LoggedCandidateHop(&$candidate), $candidate.htlc_minimum_msat());
2281 num_ignored_avoid_overpayment += 1;
2282 hit_minimum_limit = true;
2283 } else if over_path_minimum_msat {
2284 // Note that low contribution here (limited by available_liquidity_msat)
2285 // might violate htlc_minimum_msat on the hops which are next along the
2286 // payment path (upstream to the payee). To avoid that, we recompute
2287 // path fees knowing the final path contribution after constructing it.
2288 let curr_min = cmp::max(
2289 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
2291 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
2292 .saturating_add(curr_min);
2293 let hm_entry = dist.entry(src_node_id);
2294 let old_entry = hm_entry.or_insert_with(|| {
2295 // If there was previously no known way to access the source node
2296 // (recall it goes payee-to-payer) of short_channel_id, first add a
2297 // semi-dummy record just to compute the fees to reach the source node.
2298 // This will affect our decision on selecting short_channel_id
2299 // as a way to reach the $candidate.target() node.
2301 candidate: $candidate.clone(),
2303 next_hops_fee_msat: u64::max_value(),
2304 hop_use_fee_msat: u64::max_value(),
2305 total_fee_msat: u64::max_value(),
2306 path_htlc_minimum_msat,
2307 path_penalty_msat: u64::max_value(),
2308 was_processed: false,
2309 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2310 value_contribution_msat,
2314 #[allow(unused_mut)] // We only use the mut in cfg(test)
2315 let mut should_process = !old_entry.was_processed;
2316 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2318 // In test/fuzzing builds, we do extra checks to make sure the skipping
2319 // of already-seen nodes only happens in cases we expect (see below).
2320 if !should_process { should_process = true; }
2324 let mut hop_use_fee_msat = 0;
2325 let mut total_fee_msat: u64 = $next_hops_fee_msat;
2327 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2328 // will have the same effective-fee
2329 if src_node_id != our_node_id {
2330 // Note that `u64::max_value` means we'll always fail the
2331 // `old_entry.total_fee_msat > total_fee_msat` check below
2332 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
2333 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2336 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2337 if total_fee_msat > max_total_routing_fee_msat {
2338 if should_log_candidate {
2339 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2341 if let Some(_) = first_hop_details {
2343 "First hop candidate routing fee: {}. Limit: {}",
2345 max_total_routing_fee_msat,
2349 num_ignored_total_fee_limit += 1;
2351 let channel_usage = ChannelUsage {
2352 amount_msat: amount_to_transfer_over_msat,
2353 inflight_htlc_msat: used_liquidity_msat,
2356 let channel_penalty_msat =
2357 scorer.channel_penalty_msat($candidate,
2360 let path_penalty_msat = $next_hops_path_penalty_msat
2361 .saturating_add(channel_penalty_msat);
2363 // Update the way of reaching $candidate.source()
2364 // with the given short_channel_id (from $candidate.target()),
2365 // if this way is cheaper than the already known
2366 // (considering the cost to "reach" this channel from the route destination,
2367 // the cost of using this channel,
2368 // and the cost of routing to the source node of this channel).
2369 // Also, consider that htlc_minimum_msat_difference, because we might end up
2370 // paying it. Consider the following exploit:
2371 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2372 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2373 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2374 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2376 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2377 // but it may require additional tracking - we don't want to double-count
2378 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2379 // can't use something that may decrease on future hops.
2380 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2381 .saturating_add(old_entry.path_penalty_msat);
2382 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2383 .saturating_add(path_penalty_msat);
2385 if !old_entry.was_processed && new_cost < old_cost {
2386 let new_graph_node = RouteGraphNode {
2387 node_id: src_node_id,
2388 score: cmp::max(total_fee_msat, path_htlc_minimum_msat).saturating_add(path_penalty_msat),
2389 total_cltv_delta: hop_total_cltv_delta,
2390 value_contribution_msat,
2391 path_length_to_node,
2393 targets.push(new_graph_node);
2394 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2395 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2396 old_entry.total_fee_msat = total_fee_msat;
2397 old_entry.candidate = $candidate.clone();
2398 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2399 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2400 old_entry.path_penalty_msat = path_penalty_msat;
2401 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2403 old_entry.value_contribution_msat = value_contribution_msat;
2405 hop_contribution_amt_msat = Some(value_contribution_msat);
2406 } else if old_entry.was_processed && new_cost < old_cost {
2407 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2409 // If we're skipping processing a node which was previously
2410 // processed even though we found another path to it with a
2411 // cheaper fee, check that it was because the second path we
2412 // found (which we are processing now) has a lower value
2413 // contribution due to an HTLC minimum limit.
2415 // e.g. take a graph with two paths from node 1 to node 2, one
2416 // through channel A, and one through channel B. Channel A and
2417 // B are both in the to-process heap, with their scores set by
2418 // a higher htlc_minimum than fee.
2419 // Channel A is processed first, and the channels onwards from
2420 // node 1 are added to the to-process heap. Thereafter, we pop
2421 // Channel B off of the heap, note that it has a much more
2422 // restrictive htlc_maximum_msat, and recalculate the fees for
2423 // all of node 1's channels using the new, reduced, amount.
2425 // This would be bogus - we'd be selecting a higher-fee path
2426 // with a lower htlc_maximum_msat instead of the one we'd
2427 // already decided to use.
2428 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2430 value_contribution_msat + path_penalty_msat <
2431 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2438 if should_log_candidate {
2440 "Ignoring {} due to its htlc_minimum_msat limit.",
2441 LoggedCandidateHop(&$candidate));
2443 if let Some(details) = first_hop_details {
2445 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2446 details.next_outbound_htlc_minimum_msat,
2450 num_ignored_htlc_minimum_msat_limit += 1;
2454 hop_contribution_amt_msat
2458 let default_node_features = default_node_features();
2460 // Find ways (channels with destination) to reach a given node and store them
2461 // in the corresponding data structures (routing graph etc).
2462 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2463 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2464 // This data can later be helpful to optimize routing (pay lower fees).
2465 macro_rules! add_entries_to_cheapest_to_target_node {
2466 ( $node: expr, $node_id: expr, $next_hops_value_contribution: expr,
2467 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2468 let fee_to_target_msat;
2469 let next_hops_path_htlc_minimum_msat;
2470 let next_hops_path_penalty_msat;
2471 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
2472 let was_processed = elem.was_processed;
2473 elem.was_processed = true;
2474 fee_to_target_msat = elem.total_fee_msat;
2475 next_hops_path_htlc_minimum_msat = elem.path_htlc_minimum_msat;
2476 next_hops_path_penalty_msat = elem.path_penalty_msat;
2479 // Entries are added to dist in add_entry!() when there is a channel from a node.
2480 // Because there are no channels from payee, it will not have a dist entry at this point.
2481 // If we're processing any other node, it is always be the result of a channel from it.
2482 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2483 fee_to_target_msat = 0;
2484 next_hops_path_htlc_minimum_msat = 0;
2485 next_hops_path_penalty_msat = 0;
2490 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
2491 for details in first_channels {
2492 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2493 details, payer_node_id: &our_node_id,
2495 add_entry!(&candidate, fee_to_target_msat,
2496 $next_hops_value_contribution,
2497 next_hops_path_htlc_minimum_msat, next_hops_path_penalty_msat,
2498 $next_hops_cltv_delta, $next_hops_path_length);
2502 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2503 &node_info.features()
2505 &default_node_features
2508 if !features.requires_unknown_bits() {
2509 for chan_id in $node.channels.iter() {
2510 let chan = network_channels.get(chan_id).unwrap();
2511 if !chan.features.requires_unknown_bits() {
2512 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2513 if first_hops.is_none() || *source != our_node_id {
2514 if directed_channel.direction().enabled {
2515 let candidate = CandidateRouteHop::PublicHop(PublicHopCandidate {
2516 info: directed_channel,
2517 short_channel_id: *chan_id,
2519 add_entry!(&candidate,
2521 $next_hops_value_contribution,
2522 next_hops_path_htlc_minimum_msat,
2523 next_hops_path_penalty_msat,
2524 $next_hops_cltv_delta, $next_hops_path_length);
2535 let mut payment_paths = Vec::<PaymentPath>::new();
2537 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2538 'paths_collection: loop {
2539 // For every new path, start from scratch, except for used_liquidities, which
2540 // helps to avoid reusing previously selected paths in future iterations.
2543 hit_minimum_limit = false;
2545 // If first hop is a private channel and the only way to reach the payee, this is the only
2546 // place where it could be added.
2547 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2548 for details in first_channels {
2549 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2550 details, payer_node_id: &our_node_id,
2552 let added = add_entry!(&candidate, 0, path_value_msat,
2553 0, 0u64, 0, 0).is_some();
2554 log_trace!(logger, "{} direct route to payee via {}",
2555 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2559 // Add the payee as a target, so that the payee-to-payer
2560 // search algorithm knows what to start with.
2561 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2562 // The payee is not in our network graph, so nothing to add here.
2563 // There is still a chance of reaching them via last_hops though,
2564 // so don't yet fail the payment here.
2565 // If not, targets.pop() will not even let us enter the loop in step 2.
2568 add_entries_to_cheapest_to_target_node!(node, payee, path_value_msat, 0, 0);
2573 // If a caller provided us with last hops, add them to routing targets. Since this happens
2574 // earlier than general path finding, they will be somewhat prioritized, although currently
2575 // it matters only if the fees are exactly the same.
2576 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2577 // Only add the hops in this route to our candidate set if either
2578 // we have a direct channel to the first hop or the first hop is
2579 // in the regular network graph.
2580 let source_node_id = match introduction_node_id_cache[hint_idx] {
2581 Some(node_id) => node_id,
2582 None => match &hint.1.introduction_node {
2583 IntroductionNode::NodeId(pubkey) => {
2584 let node_id = NodeId::from_pubkey(&pubkey);
2585 match first_hop_targets.get_key_value(&node_id).map(|(key, _)| key) {
2586 Some(node_id) => node_id,
2590 IntroductionNode::DirectedShortChannelId(direction, scid) => {
2591 let first_hop = first_hop_targets.iter().find(|(_, channels)|
2594 .any(|details| Some(*scid) == details.get_outbound_payment_scid())
2597 Some((counterparty_node_id, _)) => {
2598 direction.select_node_id(&our_node_id, counterparty_node_id)
2605 if our_node_id == *source_node_id { continue }
2606 let candidate = if hint.1.blinded_hops.len() == 1 {
2607 CandidateRouteHop::OneHopBlinded(
2608 OneHopBlindedPathCandidate { source_node_id, hint, hint_idx }
2611 CandidateRouteHop::Blinded(BlindedPathCandidate { source_node_id, hint, hint_idx })
2613 let mut path_contribution_msat = path_value_msat;
2614 if let Some(hop_used_msat) = add_entry!(&candidate,
2615 0, path_contribution_msat, 0, 0_u64, 0, 0)
2617 path_contribution_msat = hop_used_msat;
2619 if let Some(first_channels) = first_hop_targets.get(source_node_id) {
2620 let mut first_channels = first_channels.clone();
2621 sort_first_hop_channels(
2622 &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2624 for details in first_channels {
2625 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2626 details, payer_node_id: &our_node_id,
2628 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2632 let path_min = candidate.htlc_minimum_msat().saturating_add(
2633 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2634 add_entry!(&first_hop_candidate, blinded_path_fee, path_contribution_msat, path_min,
2635 0_u64, candidate.cltv_expiry_delta(), 0);
2639 for route in payment_params.payee.unblinded_route_hints().iter()
2640 .filter(|route| !route.0.is_empty())
2642 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2643 let first_hop_src_is_reachable =
2644 // Only add the hops in this route to our candidate set if either we are part of
2645 // the first hop, we have a direct channel to the first hop, or the first hop is in
2646 // the regular network graph.
2647 our_node_id == first_hop_src_id ||
2648 first_hop_targets.get(&first_hop_src_id).is_some() ||
2649 network_nodes.get(&first_hop_src_id).is_some();
2650 if first_hop_src_is_reachable {
2651 // We start building the path from reverse, i.e., from payee
2652 // to the first RouteHintHop in the path.
2653 let hop_iter = route.0.iter().rev();
2654 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2655 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2656 let mut hop_used = true;
2657 let mut aggregate_next_hops_fee_msat: u64 = 0;
2658 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2659 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2660 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2661 let mut aggregate_next_hops_path_length: u8 = 0;
2662 let mut aggregate_path_contribution_msat = path_value_msat;
2664 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2665 let target = private_hop_key_cache.get(prev_hop_id).unwrap();
2667 if let Some(first_channels) = first_hop_targets.get(target) {
2668 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2669 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2670 hop.short_channel_id);
2675 let candidate = network_channels
2676 .get(&hop.short_channel_id)
2677 .and_then(|channel| channel.as_directed_to(target))
2678 .map(|(info, _)| CandidateRouteHop::PublicHop(PublicHopCandidate {
2680 short_channel_id: hop.short_channel_id,
2682 .unwrap_or_else(|| CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: hop, target_node_id: target }));
2684 if let Some(hop_used_msat) = add_entry!(&candidate,
2685 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2686 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2687 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2689 aggregate_path_contribution_msat = hop_used_msat;
2691 // If this hop was not used then there is no use checking the preceding
2692 // hops in the RouteHint. We can break by just searching for a direct
2693 // channel between last checked hop and first_hop_targets.
2697 let used_liquidity_msat = used_liquidities
2698 .get(&candidate.id()).copied()
2700 let channel_usage = ChannelUsage {
2701 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2702 inflight_htlc_msat: used_liquidity_msat,
2703 effective_capacity: candidate.effective_capacity(),
2705 let channel_penalty_msat = scorer.channel_penalty_msat(
2706 &candidate, channel_usage, score_params
2708 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2709 .saturating_add(channel_penalty_msat);
2711 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2712 .saturating_add(hop.cltv_expiry_delta as u32);
2714 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2717 // Searching for a direct channel between last checked hop and first_hop_targets
2718 if let Some(first_channels) = first_hop_targets.get(target) {
2719 let mut first_channels = first_channels.clone();
2720 sort_first_hop_channels(
2721 &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2723 for details in first_channels {
2724 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2725 details, payer_node_id: &our_node_id,
2727 add_entry!(&first_hop_candidate,
2728 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2729 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2730 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2738 // In the next values of the iterator, the aggregate fees already reflects
2739 // the sum of value sent from payer (final_value_msat) and routing fees
2740 // for the last node in the RouteHint. We need to just add the fees to
2741 // route through the current node so that the preceding node (next iteration)
2743 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2744 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2745 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2747 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2748 // this route hint's source node to forward said min over this channel.
2749 aggregate_next_hops_path_htlc_minimum_msat = {
2750 let curr_htlc_min = cmp::max(
2751 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2753 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2754 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2757 if idx == route.0.len() - 1 {
2758 // The last hop in this iterator is the first hop in
2759 // overall RouteHint.
2760 // If this hop connects to a node with which we have a direct channel,
2761 // ignore the network graph and, if the last hop was added, add our
2762 // direct channel to the candidate set.
2764 // Note that we *must* check if the last hop was added as `add_entry`
2765 // always assumes that the third argument is a node to which we have a
2767 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
2768 let mut first_channels = first_channels.clone();
2769 sort_first_hop_channels(
2770 &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2772 for details in first_channels {
2773 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2774 details, payer_node_id: &our_node_id,
2776 add_entry!(&first_hop_candidate,
2777 aggregate_next_hops_fee_msat,
2778 aggregate_path_contribution_msat,
2779 aggregate_next_hops_path_htlc_minimum_msat,
2780 aggregate_next_hops_path_penalty_msat,
2781 aggregate_next_hops_cltv_delta,
2782 aggregate_next_hops_path_length);
2790 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2792 // At this point, targets are filled with the data from first and
2793 // last hops communicated by the caller, and the payment receiver.
2794 let mut found_new_path = false;
2797 // If this loop terminates due the exhaustion of targets, two situations are possible:
2798 // - not enough outgoing liquidity:
2799 // 0 < already_collected_value_msat < final_value_msat
2800 // - enough outgoing liquidity:
2801 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2802 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2803 // paths_collection will be stopped because found_new_path==false.
2804 // This is not necessarily a routing failure.
2805 'path_construction: while let Some(RouteGraphNode { node_id, total_cltv_delta, mut value_contribution_msat, path_length_to_node, .. }) = targets.pop() {
2807 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2808 // traversing the graph and arrange the path out of what we found.
2809 if node_id == our_node_id {
2810 let mut new_entry = dist.remove(&our_node_id).unwrap();
2811 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2814 let mut features_set = false;
2815 let target = ordered_hops.last().unwrap().0.candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2816 if let Some(first_channels) = first_hop_targets.get(&target) {
2817 for details in first_channels {
2818 if let CandidateRouteHop::FirstHop(FirstHopCandidate { details: last_hop_details, .. })
2819 = ordered_hops.last().unwrap().0.candidate
2821 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2822 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2823 features_set = true;
2830 if let Some(node) = network_nodes.get(&target) {
2831 if let Some(node_info) = node.announcement_info.as_ref() {
2832 ordered_hops.last_mut().unwrap().1 = node_info.features().clone();
2834 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2837 // We can fill in features for everything except hops which were
2838 // provided via the invoice we're paying. We could guess based on the
2839 // recipient's features but for now we simply avoid guessing at all.
2843 // Means we successfully traversed from the payer to the payee, now
2844 // save this path for the payment route. Also, update the liquidity
2845 // remaining on the used hops, so that we take them into account
2846 // while looking for more paths.
2847 if target == maybe_dummy_payee_node_id {
2851 new_entry = match dist.remove(&target) {
2852 Some(payment_hop) => payment_hop,
2853 // We can't arrive at None because, if we ever add an entry to targets,
2854 // we also fill in the entry in dist (see add_entry!).
2855 None => unreachable!(),
2857 // We "propagate" the fees one hop backward (topologically) here,
2858 // so that fees paid for a HTLC forwarding on the current channel are
2859 // associated with the previous channel (where they will be subtracted).
2860 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2861 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2863 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2864 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2866 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2867 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2869 let mut payment_path = PaymentPath {hops: ordered_hops};
2871 // We could have possibly constructed a slightly inconsistent path: since we reduce
2872 // value being transferred along the way, we could have violated htlc_minimum_msat
2873 // on some channels we already passed (assuming dest->source direction). Here, we
2874 // recompute the fees again, so that if that's the case, we match the currently
2875 // underpaid htlc_minimum_msat with fees.
2876 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2877 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2878 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2880 // Since a path allows to transfer as much value as
2881 // the smallest channel it has ("bottleneck"), we should recompute
2882 // the fees so sender HTLC don't overpay fees when traversing
2883 // larger channels than the bottleneck. This may happen because
2884 // when we were selecting those channels we were not aware how much value
2885 // this path will transfer, and the relative fee for them
2886 // might have been computed considering a larger value.
2887 // Remember that we used these channels so that we don't rely
2888 // on the same liquidity in future paths.
2889 let mut prevented_redundant_path_selection = false;
2890 for (hop, _) in payment_path.hops.iter() {
2891 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2892 let used_liquidity_msat = used_liquidities
2893 .entry(hop.candidate.id())
2894 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2895 .or_insert(spent_on_hop_msat);
2896 let hop_capacity = hop.candidate.effective_capacity();
2897 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2898 if *used_liquidity_msat == hop_max_msat {
2899 // If this path used all of this channel's available liquidity, we know
2900 // this path will not be selected again in the next loop iteration.
2901 prevented_redundant_path_selection = true;
2903 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2905 if !prevented_redundant_path_selection {
2906 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2907 // we'll probably end up picking the same path again on the next iteration.
2908 // Decrease the available liquidity of a hop in the middle of the path.
2909 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2910 let exhausted = u64::max_value();
2912 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2913 LoggedCandidateHop(victim_candidate));
2914 if let Some(scid) = victim_candidate.short_channel_id() {
2915 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2916 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2920 // Track the total amount all our collected paths allow to send so that we know
2921 // when to stop looking for more paths
2922 already_collected_value_msat += value_contribution_msat;
2924 payment_paths.push(payment_path);
2925 found_new_path = true;
2926 break 'path_construction;
2929 // If we found a path back to the payee, we shouldn't try to process it again. This is
2930 // the equivalent of the `elem.was_processed` check in
2931 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2932 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2934 // Otherwise, since the current target node is not us,
2935 // keep "unrolling" the payment graph from payee to payer by
2936 // finding a way to reach the current target from the payer side.
2937 match network_nodes.get(&node_id) {
2940 add_entries_to_cheapest_to_target_node!(node, node_id,
2941 value_contribution_msat,
2942 total_cltv_delta, path_length_to_node);
2948 if !found_new_path && channel_saturation_pow_half != 0 {
2949 channel_saturation_pow_half = 0;
2950 continue 'paths_collection;
2952 // If we don't support MPP, no use trying to gather more value ever.
2953 break 'paths_collection;
2957 // Stop either when the recommended value is reached or if no new path was found in this
2959 // In the latter case, making another path finding attempt won't help,
2960 // because we deterministically terminated the search due to low liquidity.
2961 if !found_new_path && channel_saturation_pow_half != 0 {
2962 channel_saturation_pow_half = 0;
2963 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2964 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
2965 path_value_msat = recommended_value_msat;
2966 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2967 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2968 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2969 break 'paths_collection;
2970 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2971 // Further, if this was our first walk of the graph, and we weren't limited by an
2972 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2973 // limited by an htlc_minimum_msat value, find another path with a higher value,
2974 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2975 // still keeping a lower total fee than this path.
2976 if !hit_minimum_limit {
2977 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2978 break 'paths_collection;
2980 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.");
2981 path_value_msat = recommended_value_msat;
2985 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2986 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
2987 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
2988 num_ignored_total_fee_limit;
2989 if num_ignored_total > 0 {
2991 "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.",
2992 num_ignored_value_contribution, num_ignored_path_length_limit,
2993 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
2994 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
2995 num_ignored_total_fee_limit, num_ignored_total);
2999 if payment_paths.len() == 0 {
3000 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
3003 if already_collected_value_msat < final_value_msat {
3004 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
3008 let mut selected_route = payment_paths;
3010 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
3011 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
3013 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
3014 // the value they contribute towards the payment amount.
3015 // We sort in descending order as we will remove from the front in `retain`, next.
3016 selected_route.sort_unstable_by(|a, b|
3017 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
3018 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
3021 // We should make sure that at least 1 path left.
3022 let mut paths_left = selected_route.len();
3023 selected_route.retain(|path| {
3024 if paths_left == 1 {
3027 let path_value_msat = path.get_value_msat();
3028 if path_value_msat <= overpaid_value_msat {
3029 overpaid_value_msat -= path_value_msat;
3035 debug_assert!(selected_route.len() > 0);
3037 if overpaid_value_msat != 0 {
3039 // Now, subtract the remaining overpaid value from the most-expensive path.
3040 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
3041 // so that the sender pays less fees overall. And also htlc_minimum_msat.
3042 selected_route.sort_unstable_by(|a, b| {
3043 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3044 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3045 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
3047 let expensive_payment_path = selected_route.first_mut().unwrap();
3049 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
3050 // can't go negative.
3051 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
3052 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
3056 // Sort by the path itself and combine redundant paths.
3057 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
3058 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
3060 selected_route.sort_unstable_by_key(|path| {
3061 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
3062 debug_assert!(path.hops.len() <= key.len());
3063 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
3068 for idx in 0..(selected_route.len() - 1) {
3069 if idx + 1 >= selected_route.len() { break; }
3070 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
3071 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
3072 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
3073 selected_route[idx].update_value_and_recompute_fees(new_value);
3074 selected_route.remove(idx + 1);
3078 let mut paths = Vec::new();
3079 for payment_path in selected_route {
3080 let mut hops = Vec::with_capacity(payment_path.hops.len());
3081 for (hop, node_features) in payment_path.hops.iter()
3082 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
3084 let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
3085 let maybe_announced_channel = if let CandidateRouteHop::PublicHop(_) = hop.candidate {
3086 // If we sourced the hop from the graph we're sure the target node is announced.
3088 } else if let CandidateRouteHop::FirstHop(first_hop) = &hop.candidate {
3089 // If this is a first hop we also know if it's announced.
3090 first_hop.details.is_public
3092 // If we sourced it any other way, we double-check the network graph to see if
3093 // there are announced channels between the endpoints. If so, the hop might be
3094 // referring to any of the announced channels, as its `short_channel_id` might be
3095 // an alias, in which case we don't take any chances here.
3096 network_graph.node(&target).map_or(false, |hop_node|
3097 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
3098 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
3102 hops.push(RouteHop {
3103 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
3104 node_features: node_features.clone(),
3105 short_channel_id: hop.candidate.short_channel_id().unwrap(),
3106 channel_features: hop.candidate.features(),
3107 fee_msat: hop.fee_msat,
3108 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
3109 maybe_announced_channel,
3112 let mut final_cltv_delta = final_cltv_expiry_delta;
3113 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
3114 if let Some(blinded_path) = h.candidate.blinded_path() {
3115 final_cltv_delta = h.candidate.cltv_expiry_delta();
3117 hops: blinded_path.blinded_hops.clone(),
3118 blinding_point: blinded_path.blinding_point,
3119 excess_final_cltv_expiry_delta: 0,
3120 final_value_msat: h.fee_msat,
3124 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
3125 // applicable for the previous hop.
3126 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
3127 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
3130 paths.push(Path { hops, blinded_tail });
3132 // Make sure we would never create a route with more paths than we allow.
3133 debug_assert!(paths.len() <= payment_params.max_path_count.into());
3135 if let Some(node_features) = payment_params.payee.node_features() {
3136 for path in paths.iter_mut() {
3137 path.hops.last_mut().unwrap().node_features = node_features.clone();
3141 let route = Route { paths, route_params: Some(route_params.clone()) };
3143 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
3144 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
3145 if route.get_total_fees() > max_total_routing_fee_msat {
3146 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
3147 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
3151 log_info!(logger, "Got route: {}", log_route!(route));
3155 // When an adversarial intermediary node observes a payment, it may be able to infer its
3156 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
3157 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
3158 // payment path by adding a randomized 'shadow route' offset to the final hop.
3159 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
3160 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
3162 let network_channels = network_graph.channels();
3163 let network_nodes = network_graph.nodes();
3165 for path in route.paths.iter_mut() {
3166 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
3168 // Remember the last three nodes of the random walk and avoid looping back on them.
3169 // Init with the last three nodes from the actual path, if possible.
3170 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
3171 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
3172 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
3174 // Choose the last publicly known node as the starting point for the random walk.
3175 let mut cur_hop: Option<NodeId> = None;
3176 let mut path_nonce = [0u8; 12];
3177 if let Some(starting_hop) = path.hops.iter().rev()
3178 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
3179 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
3180 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
3183 // Init PRNG with the path-dependant nonce, which is static for private paths.
3184 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
3185 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
3187 // Pick a random path length in [1 .. 3]
3188 prng.process_in_place(&mut random_path_bytes);
3189 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
3191 for random_hop in 0..random_walk_length {
3192 // If we don't find a suitable offset in the public network graph, we default to
3193 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3194 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
3196 if let Some(cur_node_id) = cur_hop {
3197 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
3198 // Randomly choose the next unvisited hop.
3199 prng.process_in_place(&mut random_path_bytes);
3200 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
3201 .checked_rem(cur_node.channels.len())
3202 .and_then(|index| cur_node.channels.get(index))
3203 .and_then(|id| network_channels.get(id)) {
3204 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
3205 if !nodes_to_avoid.iter().any(|x| x == next_id) {
3206 nodes_to_avoid[random_hop] = *next_id;
3207 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
3208 cur_hop = Some(*next_id);
3215 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
3216 .checked_add(random_hop_offset)
3217 .unwrap_or(shadow_ctlv_expiry_delta_offset);
3220 // Limit the total offset to reduce the worst-case locked liquidity timevalue
3221 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
3222 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
3224 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
3225 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3226 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
3227 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
3228 max_path_offset = cmp::max(
3229 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
3230 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
3231 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
3233 // Add 'shadow' CLTV offset to the final hop
3234 if let Some(tail) = path.blinded_tail.as_mut() {
3235 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
3236 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
3238 if let Some(last_hop) = path.hops.last_mut() {
3239 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
3240 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
3245 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
3246 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
3248 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
3249 pub fn build_route_from_hops<L: Deref, GL: Deref>(
3250 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3251 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
3252 ) -> Result<Route, LightningError>
3253 where L::Target: Logger, GL::Target: Logger {
3254 let graph_lock = network_graph.read_only();
3255 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
3256 &graph_lock, logger, random_seed_bytes)?;
3257 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
3261 fn build_route_from_hops_internal<L: Deref>(
3262 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3263 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
3264 ) -> Result<Route, LightningError> where L::Target: Logger {
3267 our_node_id: NodeId,
3268 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
3271 impl ScoreLookUp for HopScorer {
3272 type ScoreParams = ();
3273 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
3274 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
3276 let mut cur_id = self.our_node_id;
3277 for i in 0..self.hop_ids.len() {
3278 if let Some(next_id) = self.hop_ids[i] {
3279 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
3291 impl<'a> Writeable for HopScorer {
3293 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
3298 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
3299 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
3302 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
3303 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
3304 for i in 0..hops.len() {
3305 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
3308 let scorer = HopScorer { our_node_id, hop_ids };
3310 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
3315 use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode};
3316 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
3317 use crate::routing::utxo::UtxoResult;
3318 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
3319 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
3320 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop, PublicHopCandidate};
3321 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
3322 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
3323 use crate::chain::transaction::OutPoint;
3324 use crate::ln::channel_state::{ChannelCounterparty, ChannelDetails, ChannelShutdownState};
3325 use crate::ln::types::ChannelId;
3326 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
3327 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
3328 use crate::ln::channelmanager;
3329 use crate::offers::invoice::BlindedPayInfo;
3330 use crate::util::config::UserConfig;
3331 use crate::util::test_utils as ln_test_utils;
3332 use crate::crypto::chacha20::ChaCha20;
3333 use crate::util::ser::{Readable, Writeable};
3335 use crate::util::ser::Writer;
3337 use bitcoin::amount::Amount;
3338 use bitcoin::hashes::Hash;
3339 use bitcoin::network::Network;
3340 use bitcoin::blockdata::constants::ChainHash;
3341 use bitcoin::blockdata::script::Builder;
3342 use bitcoin::blockdata::opcodes;
3343 use bitcoin::blockdata::transaction::TxOut;
3344 use bitcoin::hashes::hex::FromHex;
3345 use bitcoin::secp256k1::{PublicKey,SecretKey};
3346 use bitcoin::secp256k1::Secp256k1;
3348 use crate::io::Cursor;
3349 use crate::prelude::*;
3350 use crate::sync::Arc;
3352 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3353 features: InitFeatures, outbound_capacity_msat: u64) -> ChannelDetails {
3355 channel_id: ChannelId::new_zero(),
3356 counterparty: ChannelCounterparty {
3359 unspendable_punishment_reserve: 0,
3360 forwarding_info: None,
3361 outbound_htlc_minimum_msat: None,
3362 outbound_htlc_maximum_msat: None,
3364 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3367 outbound_scid_alias: None,
3368 inbound_scid_alias: None,
3369 channel_value_satoshis: 0,
3372 outbound_capacity_msat,
3373 next_outbound_htlc_limit_msat: outbound_capacity_msat,
3374 next_outbound_htlc_minimum_msat: 0,
3375 inbound_capacity_msat: 42,
3376 unspendable_punishment_reserve: None,
3377 confirmations_required: None,
3378 confirmations: None,
3379 force_close_spend_delay: None,
3380 is_outbound: true, is_channel_ready: true,
3381 is_usable: true, is_public: true,
3382 inbound_htlc_minimum_msat: None,
3383 inbound_htlc_maximum_msat: None,
3385 feerate_sat_per_1000_weight: None,
3386 channel_shutdown_state: Some(ChannelShutdownState::NotShuttingDown),
3387 pending_inbound_htlcs: Vec::new(),
3388 pending_outbound_htlcs: Vec::new(),
3393 fn simple_route_test() {
3394 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3395 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3396 let mut payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3397 let scorer = ln_test_utils::TestScorer::new();
3398 let random_seed_bytes = [42; 32];
3400 // Simple route to 2 via 1
3402 let route_params = RouteParameters::from_payment_params_and_value(
3403 payment_params.clone(), 0);
3404 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3405 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3406 &Default::default(), &random_seed_bytes) {
3407 assert_eq!(err, "Cannot send a payment of 0 msat");
3408 } else { panic!(); }
3410 payment_params.max_path_length = 2;
3411 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3412 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3413 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3414 assert_eq!(route.paths[0].hops.len(), 2);
3416 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3417 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3418 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3419 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3420 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3421 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3423 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3424 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3425 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3426 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3427 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3428 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3430 route_params.payment_params.max_path_length = 1;
3431 get_route(&our_id, &route_params, &network_graph.read_only(), None,
3432 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap_err();
3436 fn invalid_first_hop_test() {
3437 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3438 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3439 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3440 let scorer = ln_test_utils::TestScorer::new();
3441 let random_seed_bytes = [42; 32];
3443 // Simple route to 2 via 1
3445 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3447 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3448 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3449 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3450 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3451 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3452 } else { panic!(); }
3454 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3455 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3456 assert_eq!(route.paths[0].hops.len(), 2);
3460 fn htlc_minimum_test() {
3461 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3462 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3463 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3464 let scorer = ln_test_utils::TestScorer::new();
3465 let random_seed_bytes = [42; 32];
3467 // Simple route to 2 via 1
3469 // Disable other paths
3470 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3471 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3472 short_channel_id: 12,
3474 flags: 2, // to disable
3475 cltv_expiry_delta: 0,
3476 htlc_minimum_msat: 0,
3477 htlc_maximum_msat: MAX_VALUE_MSAT,
3479 fee_proportional_millionths: 0,
3480 excess_data: Vec::new()
3482 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3483 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3484 short_channel_id: 3,
3486 flags: 2, // to disable
3487 cltv_expiry_delta: 0,
3488 htlc_minimum_msat: 0,
3489 htlc_maximum_msat: MAX_VALUE_MSAT,
3491 fee_proportional_millionths: 0,
3492 excess_data: Vec::new()
3494 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3495 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3496 short_channel_id: 13,
3498 flags: 2, // to disable
3499 cltv_expiry_delta: 0,
3500 htlc_minimum_msat: 0,
3501 htlc_maximum_msat: MAX_VALUE_MSAT,
3503 fee_proportional_millionths: 0,
3504 excess_data: Vec::new()
3506 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3507 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3508 short_channel_id: 6,
3510 flags: 2, // to disable
3511 cltv_expiry_delta: 0,
3512 htlc_minimum_msat: 0,
3513 htlc_maximum_msat: MAX_VALUE_MSAT,
3515 fee_proportional_millionths: 0,
3516 excess_data: Vec::new()
3518 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3519 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3520 short_channel_id: 7,
3522 flags: 2, // to disable
3523 cltv_expiry_delta: 0,
3524 htlc_minimum_msat: 0,
3525 htlc_maximum_msat: MAX_VALUE_MSAT,
3527 fee_proportional_millionths: 0,
3528 excess_data: Vec::new()
3531 // Check against amount_to_transfer_over_msat.
3532 // Set minimal HTLC of 200_000_000 msat.
3533 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3534 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3535 short_channel_id: 2,
3538 cltv_expiry_delta: 0,
3539 htlc_minimum_msat: 200_000_000,
3540 htlc_maximum_msat: MAX_VALUE_MSAT,
3542 fee_proportional_millionths: 0,
3543 excess_data: Vec::new()
3546 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3548 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3549 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3550 short_channel_id: 4,
3553 cltv_expiry_delta: 0,
3554 htlc_minimum_msat: 0,
3555 htlc_maximum_msat: 199_999_999,
3557 fee_proportional_millionths: 0,
3558 excess_data: Vec::new()
3561 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3562 let route_params = RouteParameters::from_payment_params_and_value(
3563 payment_params, 199_999_999);
3564 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3565 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3566 &Default::default(), &random_seed_bytes) {
3567 assert_eq!(err, "Failed to find a path to the given destination");
3568 } else { panic!(); }
3570 // Lift the restriction on the first hop.
3571 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3572 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3573 short_channel_id: 2,
3576 cltv_expiry_delta: 0,
3577 htlc_minimum_msat: 0,
3578 htlc_maximum_msat: MAX_VALUE_MSAT,
3580 fee_proportional_millionths: 0,
3581 excess_data: Vec::new()
3584 // A payment above the minimum should pass
3585 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3586 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3587 assert_eq!(route.paths[0].hops.len(), 2);
3591 fn htlc_minimum_overpay_test() {
3592 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3593 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3594 let config = UserConfig::default();
3595 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3596 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3598 let scorer = ln_test_utils::TestScorer::new();
3599 let random_seed_bytes = [42; 32];
3601 // A route to node#2 via two paths.
3602 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3603 // Thus, they can't send 60 without overpaying.
3604 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3605 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3606 short_channel_id: 2,
3609 cltv_expiry_delta: 0,
3610 htlc_minimum_msat: 35_000,
3611 htlc_maximum_msat: 40_000,
3613 fee_proportional_millionths: 0,
3614 excess_data: Vec::new()
3616 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3617 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3618 short_channel_id: 12,
3621 cltv_expiry_delta: 0,
3622 htlc_minimum_msat: 35_000,
3623 htlc_maximum_msat: 40_000,
3625 fee_proportional_millionths: 0,
3626 excess_data: Vec::new()
3630 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3631 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3632 short_channel_id: 13,
3635 cltv_expiry_delta: 0,
3636 htlc_minimum_msat: 0,
3637 htlc_maximum_msat: MAX_VALUE_MSAT,
3639 fee_proportional_millionths: 0,
3640 excess_data: Vec::new()
3642 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3643 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3644 short_channel_id: 4,
3647 cltv_expiry_delta: 0,
3648 htlc_minimum_msat: 0,
3649 htlc_maximum_msat: MAX_VALUE_MSAT,
3651 fee_proportional_millionths: 0,
3652 excess_data: Vec::new()
3655 // Disable other paths
3656 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3657 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3658 short_channel_id: 1,
3660 flags: 2, // to disable
3661 cltv_expiry_delta: 0,
3662 htlc_minimum_msat: 0,
3663 htlc_maximum_msat: MAX_VALUE_MSAT,
3665 fee_proportional_millionths: 0,
3666 excess_data: Vec::new()
3669 let mut route_params = RouteParameters::from_payment_params_and_value(
3670 payment_params.clone(), 60_000);
3671 route_params.max_total_routing_fee_msat = Some(15_000);
3672 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3673 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3674 // Overpay fees to hit htlc_minimum_msat.
3675 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3676 // TODO: this could be better balanced to overpay 10k and not 15k.
3677 assert_eq!(overpaid_fees, 15_000);
3679 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3680 // while taking even more fee to match htlc_minimum_msat.
3681 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3682 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3683 short_channel_id: 12,
3686 cltv_expiry_delta: 0,
3687 htlc_minimum_msat: 65_000,
3688 htlc_maximum_msat: 80_000,
3690 fee_proportional_millionths: 0,
3691 excess_data: Vec::new()
3693 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3694 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3695 short_channel_id: 2,
3698 cltv_expiry_delta: 0,
3699 htlc_minimum_msat: 0,
3700 htlc_maximum_msat: MAX_VALUE_MSAT,
3702 fee_proportional_millionths: 0,
3703 excess_data: Vec::new()
3705 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3706 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3707 short_channel_id: 4,
3710 cltv_expiry_delta: 0,
3711 htlc_minimum_msat: 0,
3712 htlc_maximum_msat: MAX_VALUE_MSAT,
3714 fee_proportional_millionths: 100_000,
3715 excess_data: Vec::new()
3718 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3719 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3720 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3721 assert_eq!(route.paths.len(), 1);
3722 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3723 let fees = route.paths[0].hops[0].fee_msat;
3724 assert_eq!(fees, 5_000);
3726 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3727 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3728 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3729 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3730 // the other channel.
3731 assert_eq!(route.paths.len(), 1);
3732 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3733 let fees = route.paths[0].hops[0].fee_msat;
3734 assert_eq!(fees, 5_000);
3738 fn htlc_minimum_recipient_overpay_test() {
3739 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3740 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3741 let config = UserConfig::default();
3742 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3743 let scorer = ln_test_utils::TestScorer::new();
3744 let random_seed_bytes = [42; 32];
3746 // Route to node2 over a single path which requires overpaying the recipient themselves.
3748 // First disable all paths except the us -> node1 -> node2 path
3749 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3750 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3751 short_channel_id: 13,
3754 cltv_expiry_delta: 0,
3755 htlc_minimum_msat: 0,
3756 htlc_maximum_msat: 0,
3758 fee_proportional_millionths: 0,
3759 excess_data: Vec::new()
3762 // Set channel 4 to free but with a high htlc_minimum_msat
3763 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3764 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3765 short_channel_id: 4,
3768 cltv_expiry_delta: 0,
3769 htlc_minimum_msat: 15_000,
3770 htlc_maximum_msat: MAX_VALUE_MSAT,
3772 fee_proportional_millionths: 0,
3773 excess_data: Vec::new()
3776 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3777 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3778 // what we try to find a route for, so this test only just happens to work out to exactly
3780 let mut route_params = RouteParameters::from_payment_params_and_value(
3781 payment_params.clone(), 5_000);
3782 route_params.max_total_routing_fee_msat = Some(9_999);
3783 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3784 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3785 &Default::default(), &random_seed_bytes) {
3786 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3787 } else { panic!(); }
3789 let mut route_params = RouteParameters::from_payment_params_and_value(
3790 payment_params.clone(), 5_000);
3791 route_params.max_total_routing_fee_msat = Some(10_000);
3792 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3793 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3794 assert_eq!(route.get_total_fees(), 10_000);
3798 fn disable_channels_test() {
3799 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3800 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3801 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3802 let scorer = ln_test_utils::TestScorer::new();
3803 let random_seed_bytes = [42; 32];
3805 // // Disable channels 4 and 12 by flags=2
3806 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3807 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3808 short_channel_id: 4,
3810 flags: 2, // to disable
3811 cltv_expiry_delta: 0,
3812 htlc_minimum_msat: 0,
3813 htlc_maximum_msat: MAX_VALUE_MSAT,
3815 fee_proportional_millionths: 0,
3816 excess_data: Vec::new()
3818 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3819 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3820 short_channel_id: 12,
3822 flags: 2, // to disable
3823 cltv_expiry_delta: 0,
3824 htlc_minimum_msat: 0,
3825 htlc_maximum_msat: MAX_VALUE_MSAT,
3827 fee_proportional_millionths: 0,
3828 excess_data: Vec::new()
3831 // If all the channels require some features we don't understand, route should fail
3832 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3833 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3834 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3835 &Default::default(), &random_seed_bytes) {
3836 assert_eq!(err, "Failed to find a path to the given destination");
3837 } else { panic!(); }
3839 // If we specify a channel to node7, that overrides our local channel view and that gets used
3840 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3841 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3842 route_params.payment_params.max_path_length = 2;
3843 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3844 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3845 &Default::default(), &random_seed_bytes).unwrap();
3846 assert_eq!(route.paths[0].hops.len(), 2);
3848 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3849 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3850 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3851 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3852 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3853 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3855 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3856 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3857 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3858 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3859 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3860 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3864 fn disable_node_test() {
3865 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3866 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3867 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3868 let scorer = ln_test_utils::TestScorer::new();
3869 let random_seed_bytes = [42; 32];
3871 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3872 let mut unknown_features = NodeFeatures::empty();
3873 unknown_features.set_unknown_feature_required();
3874 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3875 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3876 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3878 // If all nodes require some features we don't understand, route should fail
3879 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3880 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3881 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3882 &Default::default(), &random_seed_bytes) {
3883 assert_eq!(err, "Failed to find a path to the given destination");
3884 } else { panic!(); }
3886 // If we specify a channel to node7, that overrides our local channel view and that gets used
3887 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3888 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3889 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3890 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3891 &Default::default(), &random_seed_bytes).unwrap();
3892 assert_eq!(route.paths[0].hops.len(), 2);
3894 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3895 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3896 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3897 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3898 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3899 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3901 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3902 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3903 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3904 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3905 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3906 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3908 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3909 // naively) assume that the user checked the feature bits on the invoice, which override
3910 // the node_announcement.
3914 fn our_chans_test() {
3915 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3916 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3917 let scorer = ln_test_utils::TestScorer::new();
3918 let random_seed_bytes = [42; 32];
3920 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3921 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3922 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3923 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3924 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3925 assert_eq!(route.paths[0].hops.len(), 3);
3927 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3928 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3929 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3930 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3931 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3932 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3934 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3935 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3936 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3937 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3938 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3939 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3941 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3942 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3943 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3944 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3945 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3946 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3948 // If we specify a channel to node7, that overrides our local channel view and that gets used
3949 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3950 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3951 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3952 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3953 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3954 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3955 &Default::default(), &random_seed_bytes).unwrap();
3956 assert_eq!(route.paths[0].hops.len(), 2);
3958 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3959 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3960 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3961 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3962 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3963 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3965 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3966 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3967 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3968 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3969 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3970 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3973 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3974 let zero_fees = RoutingFees {
3976 proportional_millionths: 0,
3978 vec![RouteHint(vec![RouteHintHop {
3979 src_node_id: nodes[3],
3980 short_channel_id: 8,
3982 cltv_expiry_delta: (8 << 4) | 1,
3983 htlc_minimum_msat: None,
3984 htlc_maximum_msat: None,
3986 ]), RouteHint(vec![RouteHintHop {
3987 src_node_id: nodes[4],
3988 short_channel_id: 9,
3991 proportional_millionths: 0,
3993 cltv_expiry_delta: (9 << 4) | 1,
3994 htlc_minimum_msat: None,
3995 htlc_maximum_msat: None,
3996 }]), RouteHint(vec![RouteHintHop {
3997 src_node_id: nodes[5],
3998 short_channel_id: 10,
4000 cltv_expiry_delta: (10 << 4) | 1,
4001 htlc_minimum_msat: None,
4002 htlc_maximum_msat: None,
4006 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4007 let zero_fees = RoutingFees {
4009 proportional_millionths: 0,
4011 vec![RouteHint(vec![RouteHintHop {
4012 src_node_id: nodes[2],
4013 short_channel_id: 5,
4016 proportional_millionths: 0,
4018 cltv_expiry_delta: (5 << 4) | 1,
4019 htlc_minimum_msat: None,
4020 htlc_maximum_msat: None,
4022 src_node_id: nodes[3],
4023 short_channel_id: 8,
4025 cltv_expiry_delta: (8 << 4) | 1,
4026 htlc_minimum_msat: None,
4027 htlc_maximum_msat: None,
4029 ]), RouteHint(vec![RouteHintHop {
4030 src_node_id: nodes[4],
4031 short_channel_id: 9,
4034 proportional_millionths: 0,
4036 cltv_expiry_delta: (9 << 4) | 1,
4037 htlc_minimum_msat: None,
4038 htlc_maximum_msat: None,
4039 }]), RouteHint(vec![RouteHintHop {
4040 src_node_id: nodes[5],
4041 short_channel_id: 10,
4043 cltv_expiry_delta: (10 << 4) | 1,
4044 htlc_minimum_msat: None,
4045 htlc_maximum_msat: None,
4050 fn partial_route_hint_test() {
4051 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4052 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4053 let scorer = ln_test_utils::TestScorer::new();
4054 let random_seed_bytes = [42; 32];
4056 // Simple test across 2, 3, 5, and 4 via a last_hop channel
4057 // Tests the behaviour when the RouteHint contains a suboptimal hop.
4058 // RouteHint may be partially used by the algo to build the best path.
4060 // First check that last hop can't have its source as the payee.
4061 let invalid_last_hop = RouteHint(vec![RouteHintHop {
4062 src_node_id: nodes[6],
4063 short_channel_id: 8,
4066 proportional_millionths: 0,
4068 cltv_expiry_delta: (8 << 4) | 1,
4069 htlc_minimum_msat: None,
4070 htlc_maximum_msat: None,
4073 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
4074 invalid_last_hops.push(invalid_last_hop);
4076 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4077 .with_route_hints(invalid_last_hops).unwrap();
4078 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4079 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
4080 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
4081 &Default::default(), &random_seed_bytes) {
4082 assert_eq!(err, "Route hint cannot have the payee as the source.");
4083 } else { panic!(); }
4086 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4087 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
4088 payment_params.max_path_length = 5;
4089 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4090 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4091 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4092 assert_eq!(route.paths[0].hops.len(), 5);
4094 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4095 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4096 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4097 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4098 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4099 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4101 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4102 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4103 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4104 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4105 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4106 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4108 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4109 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4110 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4111 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4112 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4113 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4115 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4116 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4117 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4118 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4119 // If we have a peer in the node map, we'll use their features here since we don't have
4120 // a way of figuring out their features from the invoice:
4121 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4122 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4124 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4125 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4126 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4127 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4128 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4129 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4132 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4133 let zero_fees = RoutingFees {
4135 proportional_millionths: 0,
4137 vec![RouteHint(vec![RouteHintHop {
4138 src_node_id: nodes[3],
4139 short_channel_id: 8,
4141 cltv_expiry_delta: (8 << 4) | 1,
4142 htlc_minimum_msat: None,
4143 htlc_maximum_msat: None,
4144 }]), RouteHint(vec![
4146 ]), RouteHint(vec![RouteHintHop {
4147 src_node_id: nodes[5],
4148 short_channel_id: 10,
4150 cltv_expiry_delta: (10 << 4) | 1,
4151 htlc_minimum_msat: None,
4152 htlc_maximum_msat: None,
4157 fn ignores_empty_last_hops_test() {
4158 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4159 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4160 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
4161 let scorer = ln_test_utils::TestScorer::new();
4162 let random_seed_bytes = [42; 32];
4164 // Test handling of an empty RouteHint passed in Invoice.
4165 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4166 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4167 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4168 assert_eq!(route.paths[0].hops.len(), 5);
4170 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4171 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4172 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4173 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4174 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4175 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4177 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4178 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4179 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4180 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4181 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4182 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4184 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4185 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4186 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4187 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4188 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4189 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4191 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4192 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4193 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4194 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4195 // If we have a peer in the node map, we'll use their features here since we don't have
4196 // a way of figuring out their features from the invoice:
4197 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4198 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4200 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4201 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4202 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4203 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4204 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4205 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4208 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
4210 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
4211 let zero_fees = RoutingFees {
4213 proportional_millionths: 0,
4215 vec![RouteHint(vec![RouteHintHop {
4216 src_node_id: hint_hops[0],
4217 short_channel_id: 0xff00,
4220 proportional_millionths: 0,
4222 cltv_expiry_delta: (5 << 4) | 1,
4223 htlc_minimum_msat: None,
4224 htlc_maximum_msat: None,
4226 src_node_id: hint_hops[1],
4227 short_channel_id: 0xff01,
4229 cltv_expiry_delta: (8 << 4) | 1,
4230 htlc_minimum_msat: None,
4231 htlc_maximum_msat: None,
4236 fn multi_hint_last_hops_test() {
4237 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4238 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4239 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
4240 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4241 let scorer = ln_test_utils::TestScorer::new();
4242 let random_seed_bytes = [42; 32];
4244 // Test through channels 2, 3, 0xff00, 0xff01.
4245 // Test shows that multi-hop route hints are considered and factored correctly into the
4248 // Disabling channels 6 & 7 by flags=2
4249 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4250 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4251 short_channel_id: 6,
4253 flags: 2, // to disable
4254 cltv_expiry_delta: 0,
4255 htlc_minimum_msat: 0,
4256 htlc_maximum_msat: MAX_VALUE_MSAT,
4258 fee_proportional_millionths: 0,
4259 excess_data: Vec::new()
4261 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4262 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4263 short_channel_id: 7,
4265 flags: 2, // to disable
4266 cltv_expiry_delta: 0,
4267 htlc_minimum_msat: 0,
4268 htlc_maximum_msat: MAX_VALUE_MSAT,
4270 fee_proportional_millionths: 0,
4271 excess_data: Vec::new()
4274 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4275 route_params.payment_params.max_path_length = 4;
4276 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4277 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4278 assert_eq!(route.paths[0].hops.len(), 4);
4280 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4281 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4282 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4283 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4284 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4285 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4287 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4288 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4289 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4290 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4291 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4292 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4294 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4295 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4296 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4297 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4298 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4299 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4301 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4302 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4303 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4304 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4305 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4306 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4307 route_params.payment_params.max_path_length = 3;
4308 get_route(&our_id, &route_params, &network_graph.read_only(), None,
4309 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap_err();
4313 fn private_multi_hint_last_hops_test() {
4314 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4315 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4317 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4318 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4320 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4321 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4322 let scorer = ln_test_utils::TestScorer::new();
4323 // Test through channels 2, 3, 0xff00, 0xff01.
4324 // Test shows that multiple hop hints are considered.
4326 // Disabling channels 6 & 7 by flags=2
4327 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4328 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4329 short_channel_id: 6,
4331 flags: 2, // to disable
4332 cltv_expiry_delta: 0,
4333 htlc_minimum_msat: 0,
4334 htlc_maximum_msat: MAX_VALUE_MSAT,
4336 fee_proportional_millionths: 0,
4337 excess_data: Vec::new()
4339 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4340 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4341 short_channel_id: 7,
4343 flags: 2, // to disable
4344 cltv_expiry_delta: 0,
4345 htlc_minimum_msat: 0,
4346 htlc_maximum_msat: MAX_VALUE_MSAT,
4348 fee_proportional_millionths: 0,
4349 excess_data: Vec::new()
4352 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4353 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4354 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4355 assert_eq!(route.paths[0].hops.len(), 4);
4357 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4358 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4359 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4360 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4361 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4362 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4364 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4365 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4366 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4367 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4368 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4369 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4371 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4372 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4373 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4374 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4375 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4376 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4378 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4379 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4380 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4381 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4382 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4383 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4386 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4387 let zero_fees = RoutingFees {
4389 proportional_millionths: 0,
4391 vec![RouteHint(vec![RouteHintHop {
4392 src_node_id: nodes[4],
4393 short_channel_id: 11,
4395 cltv_expiry_delta: (11 << 4) | 1,
4396 htlc_minimum_msat: None,
4397 htlc_maximum_msat: None,
4399 src_node_id: nodes[3],
4400 short_channel_id: 8,
4402 cltv_expiry_delta: (8 << 4) | 1,
4403 htlc_minimum_msat: None,
4404 htlc_maximum_msat: None,
4405 }]), RouteHint(vec![RouteHintHop {
4406 src_node_id: nodes[4],
4407 short_channel_id: 9,
4410 proportional_millionths: 0,
4412 cltv_expiry_delta: (9 << 4) | 1,
4413 htlc_minimum_msat: None,
4414 htlc_maximum_msat: None,
4415 }]), RouteHint(vec![RouteHintHop {
4416 src_node_id: nodes[5],
4417 short_channel_id: 10,
4419 cltv_expiry_delta: (10 << 4) | 1,
4420 htlc_minimum_msat: None,
4421 htlc_maximum_msat: None,
4426 fn last_hops_with_public_channel_test() {
4427 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4428 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4429 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4430 let scorer = ln_test_utils::TestScorer::new();
4431 let random_seed_bytes = [42; 32];
4433 // This test shows that public routes can be present in the invoice
4434 // which would be handled in the same manner.
4436 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4437 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4438 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4439 assert_eq!(route.paths[0].hops.len(), 5);
4441 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4442 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4443 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4444 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4445 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4446 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4448 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4449 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4450 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4451 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4452 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4453 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4455 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4456 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4457 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4458 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4459 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4460 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4462 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4463 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4464 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4465 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4466 // If we have a peer in the node map, we'll use their features here since we don't have
4467 // a way of figuring out their features from the invoice:
4468 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4469 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4471 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4472 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4473 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4474 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4475 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4476 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4480 fn our_chans_last_hop_connect_test() {
4481 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4482 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4483 let scorer = ln_test_utils::TestScorer::new();
4484 let random_seed_bytes = [42; 32];
4486 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4487 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4488 let mut last_hops = last_hops(&nodes);
4489 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4490 .with_route_hints(last_hops.clone()).unwrap();
4491 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4492 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4493 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4494 &Default::default(), &random_seed_bytes).unwrap();
4495 assert_eq!(route.paths[0].hops.len(), 2);
4497 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4498 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4499 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4500 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4501 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4502 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4504 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4505 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4506 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4507 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4508 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4509 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4511 last_hops[0].0[0].fees.base_msat = 1000;
4513 // Revert to via 6 as the fee on 8 goes up
4514 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4515 .with_route_hints(last_hops).unwrap();
4516 let route_params = RouteParameters::from_payment_params_and_value(
4517 payment_params.clone(), 100);
4518 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4519 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4520 assert_eq!(route.paths[0].hops.len(), 4);
4522 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4523 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4524 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4525 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4526 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4527 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4529 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4530 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4531 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4532 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4533 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4534 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4536 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4537 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4538 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4539 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4540 // If we have a peer in the node map, we'll use their features here since we don't have
4541 // a way of figuring out their features from the invoice:
4542 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4543 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4545 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4546 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4547 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4548 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4549 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4550 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4552 // ...but still use 8 for larger payments as 6 has a variable feerate
4553 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4554 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4555 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4556 assert_eq!(route.paths[0].hops.len(), 5);
4558 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4559 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4560 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4561 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4562 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4563 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4565 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4566 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4567 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4568 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4569 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4570 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4572 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4573 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4574 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4575 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4576 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4577 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4579 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4580 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4581 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4582 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4583 // If we have a peer in the node map, we'll use their features here since we don't have
4584 // a way of figuring out their features from the invoice:
4585 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4586 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4588 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4589 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4590 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4591 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4592 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4593 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4596 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> {
4597 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4598 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4599 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4601 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4602 let last_hops = RouteHint(vec![RouteHintHop {
4603 src_node_id: middle_node_id,
4604 short_channel_id: 8,
4607 proportional_millionths: last_hop_fee_prop,
4609 cltv_expiry_delta: (8 << 4) | 1,
4610 htlc_minimum_msat: None,
4611 htlc_maximum_msat: last_hop_htlc_max,
4613 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4614 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4615 let scorer = ln_test_utils::TestScorer::new();
4616 let random_seed_bytes = [42; 32];
4617 let logger = ln_test_utils::TestLogger::new();
4618 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4619 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4620 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4621 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4622 &random_seed_bytes);
4627 fn unannounced_path_test() {
4628 // We should be able to send a payment to a destination without any help of a routing graph
4629 // if we have a channel with a common counterparty that appears in the first and last hop
4631 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4633 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4634 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4635 assert_eq!(route.paths[0].hops.len(), 2);
4637 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4638 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4639 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4640 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4641 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4642 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4644 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4645 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4646 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4647 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4648 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4649 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4653 fn overflow_unannounced_path_test_liquidity_underflow() {
4654 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4655 // the last-hop had a fee which overflowed a u64, we'd panic.
4656 // This was due to us adding the first-hop from us unconditionally, causing us to think
4657 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4658 // In this test, we previously hit a subtraction underflow due to having less available
4659 // liquidity at the last hop than 0.
4660 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());
4664 fn overflow_unannounced_path_test_feerate_overflow() {
4665 // This tests for the same case as above, except instead of hitting a subtraction
4666 // underflow, we hit a case where the fee charged at a hop overflowed.
4667 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());
4671 fn available_amount_while_routing_test() {
4672 // Tests whether we choose the correct available channel amount while routing.
4674 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4675 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4676 let scorer = ln_test_utils::TestScorer::new();
4677 let random_seed_bytes = [42; 32];
4678 let config = UserConfig::default();
4679 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4680 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4683 // We will use a simple single-path route from
4684 // our node to node2 via node0: channels {1, 3}.
4686 // First disable all other paths.
4687 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4688 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4689 short_channel_id: 2,
4692 cltv_expiry_delta: 0,
4693 htlc_minimum_msat: 0,
4694 htlc_maximum_msat: 100_000,
4696 fee_proportional_millionths: 0,
4697 excess_data: Vec::new()
4699 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4700 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4701 short_channel_id: 12,
4704 cltv_expiry_delta: 0,
4705 htlc_minimum_msat: 0,
4706 htlc_maximum_msat: 100_000,
4708 fee_proportional_millionths: 0,
4709 excess_data: Vec::new()
4712 // Make the first channel (#1) very permissive,
4713 // and we will be testing all limits on the second channel.
4714 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4715 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4716 short_channel_id: 1,
4719 cltv_expiry_delta: 0,
4720 htlc_minimum_msat: 0,
4721 htlc_maximum_msat: 1_000_000_000,
4723 fee_proportional_millionths: 0,
4724 excess_data: Vec::new()
4727 // First, let's see if routing works if we have absolutely no idea about the available amount.
4728 // In this case, it should be set to 250_000 sats.
4729 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4730 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4731 short_channel_id: 3,
4734 cltv_expiry_delta: 0,
4735 htlc_minimum_msat: 0,
4736 htlc_maximum_msat: 250_000_000,
4738 fee_proportional_millionths: 0,
4739 excess_data: Vec::new()
4743 // Attempt to route more than available results in a failure.
4744 let route_params = RouteParameters::from_payment_params_and_value(
4745 payment_params.clone(), 250_000_001);
4746 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4747 &our_id, &route_params, &network_graph.read_only(), None,
4748 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4749 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4750 } else { panic!(); }
4754 // Now, attempt to route an exact amount we have should be fine.
4755 let route_params = RouteParameters::from_payment_params_and_value(
4756 payment_params.clone(), 250_000_000);
4757 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4758 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4759 assert_eq!(route.paths.len(), 1);
4760 let path = route.paths.last().unwrap();
4761 assert_eq!(path.hops.len(), 2);
4762 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4763 assert_eq!(path.final_value_msat(), 250_000_000);
4766 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4767 // Disable channel #1 and use another first hop.
4768 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4769 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4770 short_channel_id: 1,
4773 cltv_expiry_delta: 0,
4774 htlc_minimum_msat: 0,
4775 htlc_maximum_msat: 1_000_000_000,
4777 fee_proportional_millionths: 0,
4778 excess_data: Vec::new()
4781 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4782 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4785 // Attempt to route more than available results in a failure.
4786 let route_params = RouteParameters::from_payment_params_and_value(
4787 payment_params.clone(), 200_000_001);
4788 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4789 &our_id, &route_params, &network_graph.read_only(),
4790 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4791 &Default::default(), &random_seed_bytes) {
4792 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4793 } else { panic!(); }
4797 // Now, attempt to route an exact amount we have should be fine.
4798 let route_params = RouteParameters::from_payment_params_and_value(
4799 payment_params.clone(), 200_000_000);
4800 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4801 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4802 &Default::default(), &random_seed_bytes).unwrap();
4803 assert_eq!(route.paths.len(), 1);
4804 let path = route.paths.last().unwrap();
4805 assert_eq!(path.hops.len(), 2);
4806 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4807 assert_eq!(path.final_value_msat(), 200_000_000);
4810 // Enable channel #1 back.
4811 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4812 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4813 short_channel_id: 1,
4816 cltv_expiry_delta: 0,
4817 htlc_minimum_msat: 0,
4818 htlc_maximum_msat: 1_000_000_000,
4820 fee_proportional_millionths: 0,
4821 excess_data: Vec::new()
4825 // Now let's see if routing works if we know only htlc_maximum_msat.
4826 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4827 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4828 short_channel_id: 3,
4831 cltv_expiry_delta: 0,
4832 htlc_minimum_msat: 0,
4833 htlc_maximum_msat: 15_000,
4835 fee_proportional_millionths: 0,
4836 excess_data: Vec::new()
4840 // Attempt to route more than available results in a failure.
4841 let route_params = RouteParameters::from_payment_params_and_value(
4842 payment_params.clone(), 15_001);
4843 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4844 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4845 &scorer, &Default::default(), &random_seed_bytes) {
4846 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4847 } else { panic!(); }
4851 // Now, attempt to route an exact amount we have should be fine.
4852 let route_params = RouteParameters::from_payment_params_and_value(
4853 payment_params.clone(), 15_000);
4854 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4855 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4856 assert_eq!(route.paths.len(), 1);
4857 let path = route.paths.last().unwrap();
4858 assert_eq!(path.hops.len(), 2);
4859 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4860 assert_eq!(path.final_value_msat(), 15_000);
4863 // Now let's see if routing works if we know only capacity from the UTXO.
4865 // We can't change UTXO capacity on the fly, so we'll disable
4866 // the existing channel and add another one with the capacity we need.
4867 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4868 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4869 short_channel_id: 3,
4872 cltv_expiry_delta: 0,
4873 htlc_minimum_msat: 0,
4874 htlc_maximum_msat: MAX_VALUE_MSAT,
4876 fee_proportional_millionths: 0,
4877 excess_data: Vec::new()
4880 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4881 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4882 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4883 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4884 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_p2wsh();
4886 *chain_monitor.utxo_ret.lock().unwrap() =
4887 UtxoResult::Sync(Ok(TxOut { value: Amount::from_sat(15), script_pubkey: good_script.clone() }));
4888 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4890 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4891 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4892 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4893 short_channel_id: 333,
4896 cltv_expiry_delta: (3 << 4) | 1,
4897 htlc_minimum_msat: 0,
4898 htlc_maximum_msat: 15_000,
4900 fee_proportional_millionths: 0,
4901 excess_data: Vec::new()
4903 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4904 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4905 short_channel_id: 333,
4908 cltv_expiry_delta: (3 << 4) | 2,
4909 htlc_minimum_msat: 0,
4910 htlc_maximum_msat: 15_000,
4912 fee_proportional_millionths: 0,
4913 excess_data: Vec::new()
4917 // Attempt to route more than available results in a failure.
4918 let route_params = RouteParameters::from_payment_params_and_value(
4919 payment_params.clone(), 15_001);
4920 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4921 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4922 &scorer, &Default::default(), &random_seed_bytes) {
4923 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4924 } else { panic!(); }
4928 // Now, attempt to route an exact amount we have should be fine.
4929 let route_params = RouteParameters::from_payment_params_and_value(
4930 payment_params.clone(), 15_000);
4931 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4932 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4933 assert_eq!(route.paths.len(), 1);
4934 let path = route.paths.last().unwrap();
4935 assert_eq!(path.hops.len(), 2);
4936 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4937 assert_eq!(path.final_value_msat(), 15_000);
4940 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4941 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4942 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4943 short_channel_id: 333,
4946 cltv_expiry_delta: 0,
4947 htlc_minimum_msat: 0,
4948 htlc_maximum_msat: 10_000,
4950 fee_proportional_millionths: 0,
4951 excess_data: Vec::new()
4955 // Attempt to route more than available results in a failure.
4956 let route_params = RouteParameters::from_payment_params_and_value(
4957 payment_params.clone(), 10_001);
4958 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4959 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4960 &scorer, &Default::default(), &random_seed_bytes) {
4961 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4962 } else { panic!(); }
4966 // Now, attempt to route an exact amount we have should be fine.
4967 let route_params = RouteParameters::from_payment_params_and_value(
4968 payment_params.clone(), 10_000);
4969 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4970 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4971 assert_eq!(route.paths.len(), 1);
4972 let path = route.paths.last().unwrap();
4973 assert_eq!(path.hops.len(), 2);
4974 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4975 assert_eq!(path.final_value_msat(), 10_000);
4980 fn available_liquidity_last_hop_test() {
4981 // Check that available liquidity properly limits the path even when only
4982 // one of the latter hops is limited.
4983 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4984 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4985 let scorer = ln_test_utils::TestScorer::new();
4986 let random_seed_bytes = [42; 32];
4987 let config = UserConfig::default();
4988 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4989 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4992 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4993 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4994 // Total capacity: 50 sats.
4996 // Disable other potential paths.
4997 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4998 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4999 short_channel_id: 2,
5002 cltv_expiry_delta: 0,
5003 htlc_minimum_msat: 0,
5004 htlc_maximum_msat: 100_000,
5006 fee_proportional_millionths: 0,
5007 excess_data: Vec::new()
5009 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5010 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5011 short_channel_id: 7,
5014 cltv_expiry_delta: 0,
5015 htlc_minimum_msat: 0,
5016 htlc_maximum_msat: 100_000,
5018 fee_proportional_millionths: 0,
5019 excess_data: Vec::new()
5024 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5025 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5026 short_channel_id: 12,
5029 cltv_expiry_delta: 0,
5030 htlc_minimum_msat: 0,
5031 htlc_maximum_msat: 100_000,
5033 fee_proportional_millionths: 0,
5034 excess_data: Vec::new()
5036 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5037 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5038 short_channel_id: 13,
5041 cltv_expiry_delta: 0,
5042 htlc_minimum_msat: 0,
5043 htlc_maximum_msat: 100_000,
5045 fee_proportional_millionths: 0,
5046 excess_data: Vec::new()
5049 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5050 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5051 short_channel_id: 6,
5054 cltv_expiry_delta: 0,
5055 htlc_minimum_msat: 0,
5056 htlc_maximum_msat: 50_000,
5058 fee_proportional_millionths: 0,
5059 excess_data: Vec::new()
5061 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5062 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5063 short_channel_id: 11,
5066 cltv_expiry_delta: 0,
5067 htlc_minimum_msat: 0,
5068 htlc_maximum_msat: 100_000,
5070 fee_proportional_millionths: 0,
5071 excess_data: Vec::new()
5074 // Attempt to route more than available results in a failure.
5075 let route_params = RouteParameters::from_payment_params_and_value(
5076 payment_params.clone(), 60_000);
5077 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5078 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5079 &scorer, &Default::default(), &random_seed_bytes) {
5080 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5081 } else { panic!(); }
5085 // Now, attempt to route 49 sats (just a bit below the capacity).
5086 let route_params = RouteParameters::from_payment_params_and_value(
5087 payment_params.clone(), 49_000);
5088 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5089 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5090 assert_eq!(route.paths.len(), 1);
5091 let mut total_amount_paid_msat = 0;
5092 for path in &route.paths {
5093 assert_eq!(path.hops.len(), 4);
5094 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5095 total_amount_paid_msat += path.final_value_msat();
5097 assert_eq!(total_amount_paid_msat, 49_000);
5101 // Attempt to route an exact amount is also fine
5102 let route_params = RouteParameters::from_payment_params_and_value(
5103 payment_params, 50_000);
5104 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5105 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5106 assert_eq!(route.paths.len(), 1);
5107 let mut total_amount_paid_msat = 0;
5108 for path in &route.paths {
5109 assert_eq!(path.hops.len(), 4);
5110 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5111 total_amount_paid_msat += path.final_value_msat();
5113 assert_eq!(total_amount_paid_msat, 50_000);
5118 fn ignore_fee_first_hop_test() {
5119 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5120 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5121 let scorer = ln_test_utils::TestScorer::new();
5122 let random_seed_bytes = [42; 32];
5123 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5125 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5126 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5127 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5128 short_channel_id: 1,
5131 cltv_expiry_delta: 0,
5132 htlc_minimum_msat: 0,
5133 htlc_maximum_msat: 100_000,
5134 fee_base_msat: 1_000_000,
5135 fee_proportional_millionths: 0,
5136 excess_data: Vec::new()
5138 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5139 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5140 short_channel_id: 3,
5143 cltv_expiry_delta: 0,
5144 htlc_minimum_msat: 0,
5145 htlc_maximum_msat: 50_000,
5147 fee_proportional_millionths: 0,
5148 excess_data: Vec::new()
5152 let route_params = RouteParameters::from_payment_params_and_value(
5153 payment_params, 50_000);
5154 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5155 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5156 assert_eq!(route.paths.len(), 1);
5157 let mut total_amount_paid_msat = 0;
5158 for path in &route.paths {
5159 assert_eq!(path.hops.len(), 2);
5160 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5161 total_amount_paid_msat += path.final_value_msat();
5163 assert_eq!(total_amount_paid_msat, 50_000);
5168 fn simple_mpp_route_test() {
5169 let (secp_ctx, _, _, _, _) = build_graph();
5170 let (_, _, _, nodes) = get_nodes(&secp_ctx);
5171 let config = UserConfig::default();
5172 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5173 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5175 do_simple_mpp_route_test(clear_payment_params);
5177 // MPP to a 1-hop blinded path for nodes[2]
5178 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
5179 let blinded_path = BlindedPath {
5180 introduction_node: IntroductionNode::NodeId(nodes[2]),
5181 blinding_point: ln_test_utils::pubkey(42),
5182 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
5184 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
5186 fee_proportional_millionths: 0,
5187 htlc_minimum_msat: 0,
5188 htlc_maximum_msat: 0,
5189 cltv_expiry_delta: 0,
5190 features: BlindedHopFeatures::empty(),
5192 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
5193 .with_bolt12_features(bolt12_features.clone()).unwrap();
5194 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
5196 // MPP to 3 2-hop blinded paths
5197 let mut blinded_path_node_0 = blinded_path.clone();
5198 blinded_path_node_0.introduction_node = IntroductionNode::NodeId(nodes[0]);
5199 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
5200 let mut node_0_payinfo = blinded_payinfo.clone();
5201 node_0_payinfo.htlc_maximum_msat = 50_000;
5203 let mut blinded_path_node_7 = blinded_path_node_0.clone();
5204 blinded_path_node_7.introduction_node = IntroductionNode::NodeId(nodes[7]);
5205 let mut node_7_payinfo = blinded_payinfo.clone();
5206 node_7_payinfo.htlc_maximum_msat = 60_000;
5208 let mut blinded_path_node_1 = blinded_path_node_0.clone();
5209 blinded_path_node_1.introduction_node = IntroductionNode::NodeId(nodes[1]);
5210 let mut node_1_payinfo = blinded_payinfo.clone();
5211 node_1_payinfo.htlc_maximum_msat = 180_000;
5213 let two_hop_blinded_payment_params = PaymentParameters::blinded(
5215 (node_0_payinfo, blinded_path_node_0),
5216 (node_7_payinfo, blinded_path_node_7),
5217 (node_1_payinfo, blinded_path_node_1)
5219 .with_bolt12_features(bolt12_features).unwrap();
5220 do_simple_mpp_route_test(two_hop_blinded_payment_params);
5224 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
5225 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5226 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5227 let scorer = ln_test_utils::TestScorer::new();
5228 let random_seed_bytes = [42; 32];
5230 // We need a route consisting of 3 paths:
5231 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5232 // To achieve this, the amount being transferred should be around
5233 // the total capacity of these 3 paths.
5235 // First, we set limits on these (previously unlimited) channels.
5236 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
5238 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5239 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5240 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5241 short_channel_id: 1,
5244 cltv_expiry_delta: 0,
5245 htlc_minimum_msat: 0,
5246 htlc_maximum_msat: 100_000,
5248 fee_proportional_millionths: 0,
5249 excess_data: Vec::new()
5251 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5252 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5253 short_channel_id: 3,
5256 cltv_expiry_delta: 0,
5257 htlc_minimum_msat: 0,
5258 htlc_maximum_msat: 50_000,
5260 fee_proportional_millionths: 0,
5261 excess_data: Vec::new()
5264 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
5265 // (total limit 60).
5266 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5267 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5268 short_channel_id: 12,
5271 cltv_expiry_delta: 0,
5272 htlc_minimum_msat: 0,
5273 htlc_maximum_msat: 60_000,
5275 fee_proportional_millionths: 0,
5276 excess_data: Vec::new()
5278 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5279 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5280 short_channel_id: 13,
5283 cltv_expiry_delta: 0,
5284 htlc_minimum_msat: 0,
5285 htlc_maximum_msat: 60_000,
5287 fee_proportional_millionths: 0,
5288 excess_data: Vec::new()
5291 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5292 // (total capacity 180 sats).
5293 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5294 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5295 short_channel_id: 2,
5298 cltv_expiry_delta: 0,
5299 htlc_minimum_msat: 0,
5300 htlc_maximum_msat: 200_000,
5302 fee_proportional_millionths: 0,
5303 excess_data: Vec::new()
5305 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5306 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5307 short_channel_id: 4,
5310 cltv_expiry_delta: 0,
5311 htlc_minimum_msat: 0,
5312 htlc_maximum_msat: 180_000,
5314 fee_proportional_millionths: 0,
5315 excess_data: Vec::new()
5319 // Attempt to route more than available results in a failure.
5320 let route_params = RouteParameters::from_payment_params_and_value(
5321 payment_params.clone(), 300_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 // Attempt to route while setting max_path_count to 0 results in a failure.
5331 let zero_payment_params = payment_params.clone().with_max_path_count(0);
5332 let route_params = RouteParameters::from_payment_params_and_value(
5333 zero_payment_params, 100);
5334 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5335 &our_id, &route_params, &network_graph.read_only(), None,
5336 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5337 assert_eq!(err, "Can't find a route with no paths allowed.");
5338 } else { panic!(); }
5342 // Attempt to route while setting max_path_count to 3 results in a failure.
5343 // This is the case because the minimal_value_contribution_msat would require each path
5344 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5345 let fail_payment_params = payment_params.clone().with_max_path_count(3);
5346 let route_params = RouteParameters::from_payment_params_and_value(
5347 fail_payment_params, 250_000);
5348 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5349 &our_id, &route_params, &network_graph.read_only(), None,
5350 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5351 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5352 } else { panic!(); }
5356 // Now, attempt to route 250 sats (just a bit below the capacity).
5357 // Our algorithm should provide us with these 3 paths.
5358 let route_params = RouteParameters::from_payment_params_and_value(
5359 payment_params.clone(), 250_000);
5360 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5361 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5362 assert_eq!(route.paths.len(), 3);
5363 let mut total_amount_paid_msat = 0;
5364 for path in &route.paths {
5365 if let Some(bt) = &path.blinded_tail {
5366 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5368 assert_eq!(path.hops.len(), 2);
5369 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5371 total_amount_paid_msat += path.final_value_msat();
5373 assert_eq!(total_amount_paid_msat, 250_000);
5377 // Attempt to route an exact amount is also fine
5378 let route_params = RouteParameters::from_payment_params_and_value(
5379 payment_params.clone(), 290_000);
5380 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5381 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5382 assert_eq!(route.paths.len(), 3);
5383 let mut total_amount_paid_msat = 0;
5384 for path in &route.paths {
5385 if payment_params.payee.blinded_route_hints().len() != 0 {
5386 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5387 if let Some(bt) = &path.blinded_tail {
5388 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5389 if bt.hops.len() > 1 {
5390 let network_graph = network_graph.read_only();
5392 NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
5393 payment_params.payee.blinded_route_hints().iter()
5394 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5395 .and_then(|(_, p)| p.public_introduction_node_id(&network_graph))
5400 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5403 assert_eq!(path.hops.len(), 2);
5404 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5406 total_amount_paid_msat += path.final_value_msat();
5408 assert_eq!(total_amount_paid_msat, 290_000);
5413 fn long_mpp_route_test() {
5414 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5415 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5416 let scorer = ln_test_utils::TestScorer::new();
5417 let random_seed_bytes = [42; 32];
5418 let config = UserConfig::default();
5419 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5420 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5423 // We need a route consisting of 3 paths:
5424 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5425 // Note that these paths overlap (channels 5, 12, 13).
5426 // We will route 300 sats.
5427 // Each path will have 100 sats capacity, those channels which
5428 // are used twice will have 200 sats capacity.
5430 // Disable other potential paths.
5431 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5432 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5433 short_channel_id: 2,
5436 cltv_expiry_delta: 0,
5437 htlc_minimum_msat: 0,
5438 htlc_maximum_msat: 100_000,
5440 fee_proportional_millionths: 0,
5441 excess_data: Vec::new()
5443 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5444 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5445 short_channel_id: 7,
5448 cltv_expiry_delta: 0,
5449 htlc_minimum_msat: 0,
5450 htlc_maximum_msat: 100_000,
5452 fee_proportional_millionths: 0,
5453 excess_data: Vec::new()
5456 // Path via {node0, node2} is channels {1, 3, 5}.
5457 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5458 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5459 short_channel_id: 1,
5462 cltv_expiry_delta: 0,
5463 htlc_minimum_msat: 0,
5464 htlc_maximum_msat: 100_000,
5466 fee_proportional_millionths: 0,
5467 excess_data: Vec::new()
5469 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5470 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5471 short_channel_id: 3,
5474 cltv_expiry_delta: 0,
5475 htlc_minimum_msat: 0,
5476 htlc_maximum_msat: 100_000,
5478 fee_proportional_millionths: 0,
5479 excess_data: Vec::new()
5482 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5483 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5484 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5485 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5486 short_channel_id: 5,
5489 cltv_expiry_delta: 0,
5490 htlc_minimum_msat: 0,
5491 htlc_maximum_msat: 200_000,
5493 fee_proportional_millionths: 0,
5494 excess_data: Vec::new()
5496 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5497 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5498 short_channel_id: 5,
5500 flags: 3, // disable direction 1
5501 cltv_expiry_delta: 0,
5502 htlc_minimum_msat: 0,
5503 htlc_maximum_msat: 200_000,
5505 fee_proportional_millionths: 0,
5506 excess_data: Vec::new()
5509 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5510 // Add 100 sats to the capacities of {12, 13}, because these channels
5511 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5512 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5513 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5514 short_channel_id: 12,
5517 cltv_expiry_delta: 0,
5518 htlc_minimum_msat: 0,
5519 htlc_maximum_msat: 200_000,
5521 fee_proportional_millionths: 0,
5522 excess_data: Vec::new()
5524 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5525 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5526 short_channel_id: 13,
5529 cltv_expiry_delta: 0,
5530 htlc_minimum_msat: 0,
5531 htlc_maximum_msat: 200_000,
5533 fee_proportional_millionths: 0,
5534 excess_data: Vec::new()
5537 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5538 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5539 short_channel_id: 6,
5542 cltv_expiry_delta: 0,
5543 htlc_minimum_msat: 0,
5544 htlc_maximum_msat: 100_000,
5546 fee_proportional_millionths: 0,
5547 excess_data: Vec::new()
5549 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5550 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5551 short_channel_id: 11,
5554 cltv_expiry_delta: 0,
5555 htlc_minimum_msat: 0,
5556 htlc_maximum_msat: 100_000,
5558 fee_proportional_millionths: 0,
5559 excess_data: Vec::new()
5562 // Path via {node7, node2} is channels {12, 13, 5}.
5563 // We already limited them to 200 sats (they are used twice for 100 sats).
5564 // Nothing to do here.
5567 // Attempt to route more than available results in a failure.
5568 let route_params = RouteParameters::from_payment_params_and_value(
5569 payment_params.clone(), 350_000);
5570 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5571 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5572 &scorer, &Default::default(), &random_seed_bytes) {
5573 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5574 } else { panic!(); }
5578 // Now, attempt to route 300 sats (exact amount we can route).
5579 // Our algorithm should provide us with these 3 paths, 100 sats each.
5580 let route_params = RouteParameters::from_payment_params_and_value(
5581 payment_params, 300_000);
5582 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5583 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5584 assert_eq!(route.paths.len(), 3);
5586 let mut total_amount_paid_msat = 0;
5587 for path in &route.paths {
5588 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5589 total_amount_paid_msat += path.final_value_msat();
5591 assert_eq!(total_amount_paid_msat, 300_000);
5597 fn mpp_cheaper_route_test() {
5598 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5599 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5600 let scorer = ln_test_utils::TestScorer::new();
5601 let random_seed_bytes = [42; 32];
5602 let config = UserConfig::default();
5603 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5604 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5607 // This test checks that if we have two cheaper paths and one more expensive path,
5608 // so that liquidity-wise any 2 of 3 combination is sufficient,
5609 // two cheaper paths will be taken.
5610 // These paths have equal available liquidity.
5612 // We need a combination of 3 paths:
5613 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5614 // Note that these paths overlap (channels 5, 12, 13).
5615 // Each path will have 100 sats capacity, those channels which
5616 // are used twice will have 200 sats capacity.
5618 // Disable other potential paths.
5619 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5620 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5621 short_channel_id: 2,
5624 cltv_expiry_delta: 0,
5625 htlc_minimum_msat: 0,
5626 htlc_maximum_msat: 100_000,
5628 fee_proportional_millionths: 0,
5629 excess_data: Vec::new()
5631 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5632 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5633 short_channel_id: 7,
5636 cltv_expiry_delta: 0,
5637 htlc_minimum_msat: 0,
5638 htlc_maximum_msat: 100_000,
5640 fee_proportional_millionths: 0,
5641 excess_data: Vec::new()
5644 // Path via {node0, node2} is channels {1, 3, 5}.
5645 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5646 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5647 short_channel_id: 1,
5650 cltv_expiry_delta: 0,
5651 htlc_minimum_msat: 0,
5652 htlc_maximum_msat: 100_000,
5654 fee_proportional_millionths: 0,
5655 excess_data: Vec::new()
5657 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5658 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5659 short_channel_id: 3,
5662 cltv_expiry_delta: 0,
5663 htlc_minimum_msat: 0,
5664 htlc_maximum_msat: 100_000,
5666 fee_proportional_millionths: 0,
5667 excess_data: Vec::new()
5670 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5671 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5672 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5673 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5674 short_channel_id: 5,
5677 cltv_expiry_delta: 0,
5678 htlc_minimum_msat: 0,
5679 htlc_maximum_msat: 200_000,
5681 fee_proportional_millionths: 0,
5682 excess_data: Vec::new()
5684 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5685 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5686 short_channel_id: 5,
5688 flags: 3, // disable direction 1
5689 cltv_expiry_delta: 0,
5690 htlc_minimum_msat: 0,
5691 htlc_maximum_msat: 200_000,
5693 fee_proportional_millionths: 0,
5694 excess_data: Vec::new()
5697 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5698 // Add 100 sats to the capacities of {12, 13}, because these channels
5699 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5700 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5701 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5702 short_channel_id: 12,
5705 cltv_expiry_delta: 0,
5706 htlc_minimum_msat: 0,
5707 htlc_maximum_msat: 200_000,
5709 fee_proportional_millionths: 0,
5710 excess_data: Vec::new()
5712 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5713 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5714 short_channel_id: 13,
5717 cltv_expiry_delta: 0,
5718 htlc_minimum_msat: 0,
5719 htlc_maximum_msat: 200_000,
5721 fee_proportional_millionths: 0,
5722 excess_data: Vec::new()
5725 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5726 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5727 short_channel_id: 6,
5730 cltv_expiry_delta: 0,
5731 htlc_minimum_msat: 0,
5732 htlc_maximum_msat: 100_000,
5733 fee_base_msat: 1_000,
5734 fee_proportional_millionths: 0,
5735 excess_data: Vec::new()
5737 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5738 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5739 short_channel_id: 11,
5742 cltv_expiry_delta: 0,
5743 htlc_minimum_msat: 0,
5744 htlc_maximum_msat: 100_000,
5746 fee_proportional_millionths: 0,
5747 excess_data: Vec::new()
5750 // Path via {node7, node2} is channels {12, 13, 5}.
5751 // We already limited them to 200 sats (they are used twice for 100 sats).
5752 // Nothing to do here.
5755 // Now, attempt to route 180 sats.
5756 // Our algorithm should provide us with these 2 paths.
5757 let route_params = RouteParameters::from_payment_params_and_value(
5758 payment_params, 180_000);
5759 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5760 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5761 assert_eq!(route.paths.len(), 2);
5763 let mut total_value_transferred_msat = 0;
5764 let mut total_paid_msat = 0;
5765 for path in &route.paths {
5766 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5767 total_value_transferred_msat += path.final_value_msat();
5768 for hop in &path.hops {
5769 total_paid_msat += hop.fee_msat;
5772 // If we paid fee, this would be higher.
5773 assert_eq!(total_value_transferred_msat, 180_000);
5774 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5775 assert_eq!(total_fees_paid, 0);
5780 fn fees_on_mpp_route_test() {
5781 // This test makes sure that MPP algorithm properly takes into account
5782 // fees charged on the channels, by making the fees impactful:
5783 // if the fee is not properly accounted for, the behavior is different.
5784 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5785 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5786 let scorer = ln_test_utils::TestScorer::new();
5787 let random_seed_bytes = [42; 32];
5788 let config = UserConfig::default();
5789 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5790 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5793 // We need a route consisting of 2 paths:
5794 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5795 // We will route 200 sats, Each path will have 100 sats capacity.
5797 // This test is not particularly stable: e.g.,
5798 // there's a way to route via {node0, node2, node4}.
5799 // It works while pathfinding is deterministic, but can be broken otherwise.
5800 // It's fine to ignore this concern for now.
5802 // Disable other potential paths.
5803 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5804 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5805 short_channel_id: 2,
5808 cltv_expiry_delta: 0,
5809 htlc_minimum_msat: 0,
5810 htlc_maximum_msat: 100_000,
5812 fee_proportional_millionths: 0,
5813 excess_data: Vec::new()
5816 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5817 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5818 short_channel_id: 7,
5821 cltv_expiry_delta: 0,
5822 htlc_minimum_msat: 0,
5823 htlc_maximum_msat: 100_000,
5825 fee_proportional_millionths: 0,
5826 excess_data: Vec::new()
5829 // Path via {node0, node2} is channels {1, 3, 5}.
5830 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5831 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5832 short_channel_id: 1,
5835 cltv_expiry_delta: 0,
5836 htlc_minimum_msat: 0,
5837 htlc_maximum_msat: 100_000,
5839 fee_proportional_millionths: 0,
5840 excess_data: Vec::new()
5842 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5843 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5844 short_channel_id: 3,
5847 cltv_expiry_delta: 0,
5848 htlc_minimum_msat: 0,
5849 htlc_maximum_msat: 100_000,
5851 fee_proportional_millionths: 0,
5852 excess_data: Vec::new()
5855 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5856 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5857 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5858 short_channel_id: 5,
5861 cltv_expiry_delta: 0,
5862 htlc_minimum_msat: 0,
5863 htlc_maximum_msat: 100_000,
5865 fee_proportional_millionths: 0,
5866 excess_data: Vec::new()
5868 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5869 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5870 short_channel_id: 5,
5872 flags: 3, // Disable direction 1
5873 cltv_expiry_delta: 0,
5874 htlc_minimum_msat: 0,
5875 htlc_maximum_msat: 100_000,
5877 fee_proportional_millionths: 0,
5878 excess_data: Vec::new()
5881 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5882 // All channels should be 100 sats capacity. But for the fee experiment,
5883 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5884 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5885 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5886 // so no matter how large are other channels,
5887 // the whole path will be limited by 100 sats with just these 2 conditions:
5888 // - channel 12 capacity is 250 sats
5889 // - fee for channel 6 is 150 sats
5890 // Let's test this by enforcing these 2 conditions and removing other limits.
5891 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5892 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5893 short_channel_id: 12,
5896 cltv_expiry_delta: 0,
5897 htlc_minimum_msat: 0,
5898 htlc_maximum_msat: 250_000,
5900 fee_proportional_millionths: 0,
5901 excess_data: Vec::new()
5903 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5904 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5905 short_channel_id: 13,
5908 cltv_expiry_delta: 0,
5909 htlc_minimum_msat: 0,
5910 htlc_maximum_msat: MAX_VALUE_MSAT,
5912 fee_proportional_millionths: 0,
5913 excess_data: Vec::new()
5916 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5917 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5918 short_channel_id: 6,
5921 cltv_expiry_delta: 0,
5922 htlc_minimum_msat: 0,
5923 htlc_maximum_msat: MAX_VALUE_MSAT,
5924 fee_base_msat: 150_000,
5925 fee_proportional_millionths: 0,
5926 excess_data: Vec::new()
5928 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5929 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5930 short_channel_id: 11,
5933 cltv_expiry_delta: 0,
5934 htlc_minimum_msat: 0,
5935 htlc_maximum_msat: MAX_VALUE_MSAT,
5937 fee_proportional_millionths: 0,
5938 excess_data: Vec::new()
5942 // Attempt to route more than available results in a failure.
5943 let route_params = RouteParameters::from_payment_params_and_value(
5944 payment_params.clone(), 210_000);
5945 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5946 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5947 &scorer, &Default::default(), &random_seed_bytes) {
5948 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5949 } else { panic!(); }
5953 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5954 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5955 max_total_routing_fee_msat: Some(149_999) };
5956 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5957 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5958 &scorer, &Default::default(), &random_seed_bytes) {
5959 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5960 } else { panic!(); }
5964 // Now, attempt to route 200 sats (exact amount we can route).
5965 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5966 max_total_routing_fee_msat: Some(150_000) };
5967 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5968 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5969 assert_eq!(route.paths.len(), 2);
5971 let mut total_amount_paid_msat = 0;
5972 for path in &route.paths {
5973 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5974 total_amount_paid_msat += path.final_value_msat();
5976 assert_eq!(total_amount_paid_msat, 200_000);
5977 assert_eq!(route.get_total_fees(), 150_000);
5982 fn mpp_with_last_hops() {
5983 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5984 // via a single last-hop route hint, we'd fail to route if we first collected routes
5985 // totaling close but not quite enough to fund the full payment.
5987 // This was because we considered last-hop hints to have exactly the sought payment amount
5988 // instead of the amount we were trying to collect, needlessly limiting our path searching
5989 // at the very first hop.
5991 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5992 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5993 // to only have the remaining to-collect amount in available liquidity.
5995 // This bug appeared in production in some specific channel configurations.
5996 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5997 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5998 let scorer = ln_test_utils::TestScorer::new();
5999 let random_seed_bytes = [42; 32];
6000 let config = UserConfig::default();
6001 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
6002 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
6003 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
6004 src_node_id: nodes[2],
6005 short_channel_id: 42,
6006 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
6007 cltv_expiry_delta: 42,
6008 htlc_minimum_msat: None,
6009 htlc_maximum_msat: None,
6010 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
6012 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
6013 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
6014 // would first use the no-fee route and then fail to find a path along the second route as
6015 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
6016 // under 5% of our payment amount.
6017 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6018 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6019 short_channel_id: 1,
6022 cltv_expiry_delta: (5 << 4) | 5,
6023 htlc_minimum_msat: 0,
6024 htlc_maximum_msat: 99_000,
6025 fee_base_msat: u32::max_value(),
6026 fee_proportional_millionths: u32::max_value(),
6027 excess_data: Vec::new()
6029 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6030 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6031 short_channel_id: 2,
6034 cltv_expiry_delta: (5 << 4) | 3,
6035 htlc_minimum_msat: 0,
6036 htlc_maximum_msat: 99_000,
6037 fee_base_msat: u32::max_value(),
6038 fee_proportional_millionths: u32::max_value(),
6039 excess_data: Vec::new()
6041 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6042 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6043 short_channel_id: 4,
6046 cltv_expiry_delta: (4 << 4) | 1,
6047 htlc_minimum_msat: 0,
6048 htlc_maximum_msat: MAX_VALUE_MSAT,
6050 fee_proportional_millionths: 0,
6051 excess_data: Vec::new()
6053 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6054 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6055 short_channel_id: 13,
6057 flags: 0|2, // Channel disabled
6058 cltv_expiry_delta: (13 << 4) | 1,
6059 htlc_minimum_msat: 0,
6060 htlc_maximum_msat: MAX_VALUE_MSAT,
6062 fee_proportional_millionths: 2000000,
6063 excess_data: Vec::new()
6066 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
6068 let route_params = RouteParameters::from_payment_params_and_value(
6069 payment_params, 100_000);
6070 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6071 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6072 assert_eq!(route.paths.len(), 2);
6073 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
6074 // Paths are manually ordered ordered by SCID, so:
6075 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
6076 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
6077 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
6078 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
6079 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
6080 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
6081 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
6082 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
6083 assert_eq!(route.get_total_fees(), 1);
6084 assert_eq!(route.get_total_amount(), 100_000);
6088 fn drop_lowest_channel_mpp_route_test() {
6089 // This test checks that low-capacity channel is dropped when after
6090 // path finding we realize that we found more capacity than we need.
6091 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6092 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6093 let scorer = ln_test_utils::TestScorer::new();
6094 let random_seed_bytes = [42; 32];
6095 let config = UserConfig::default();
6096 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6097 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6099 .with_max_channel_saturation_power_of_half(0);
6101 // We need a route consisting of 3 paths:
6102 // From our node to node2 via node0, node7, node1 (three paths one hop each).
6104 // The first and the second paths should be sufficient, but the third should be
6105 // cheaper, so that we select it but drop later.
6107 // First, we set limits on these (previously unlimited) channels.
6108 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
6110 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
6111 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6112 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6113 short_channel_id: 1,
6116 cltv_expiry_delta: 0,
6117 htlc_minimum_msat: 0,
6118 htlc_maximum_msat: 100_000,
6120 fee_proportional_millionths: 0,
6121 excess_data: Vec::new()
6123 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6124 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6125 short_channel_id: 3,
6128 cltv_expiry_delta: 0,
6129 htlc_minimum_msat: 0,
6130 htlc_maximum_msat: 50_000,
6132 fee_proportional_millionths: 0,
6133 excess_data: Vec::new()
6136 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
6137 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6138 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6139 short_channel_id: 12,
6142 cltv_expiry_delta: 0,
6143 htlc_minimum_msat: 0,
6144 htlc_maximum_msat: 60_000,
6146 fee_proportional_millionths: 0,
6147 excess_data: Vec::new()
6149 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6150 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6151 short_channel_id: 13,
6154 cltv_expiry_delta: 0,
6155 htlc_minimum_msat: 0,
6156 htlc_maximum_msat: 60_000,
6158 fee_proportional_millionths: 0,
6159 excess_data: Vec::new()
6162 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
6163 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6164 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6165 short_channel_id: 2,
6168 cltv_expiry_delta: 0,
6169 htlc_minimum_msat: 0,
6170 htlc_maximum_msat: 20_000,
6172 fee_proportional_millionths: 0,
6173 excess_data: Vec::new()
6175 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6176 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6177 short_channel_id: 4,
6180 cltv_expiry_delta: 0,
6181 htlc_minimum_msat: 0,
6182 htlc_maximum_msat: 20_000,
6184 fee_proportional_millionths: 0,
6185 excess_data: Vec::new()
6189 // Attempt to route more than available results in a failure.
6190 let route_params = RouteParameters::from_payment_params_and_value(
6191 payment_params.clone(), 150_000);
6192 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6193 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6194 &scorer, &Default::default(), &random_seed_bytes) {
6195 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6196 } else { panic!(); }
6200 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
6201 // Our algorithm should provide us with these 3 paths.
6202 let route_params = RouteParameters::from_payment_params_and_value(
6203 payment_params.clone(), 125_000);
6204 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6205 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6206 assert_eq!(route.paths.len(), 3);
6207 let mut total_amount_paid_msat = 0;
6208 for path in &route.paths {
6209 assert_eq!(path.hops.len(), 2);
6210 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6211 total_amount_paid_msat += path.final_value_msat();
6213 assert_eq!(total_amount_paid_msat, 125_000);
6217 // Attempt to route without the last small cheap channel
6218 let route_params = RouteParameters::from_payment_params_and_value(
6219 payment_params, 90_000);
6220 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6221 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6222 assert_eq!(route.paths.len(), 2);
6223 let mut total_amount_paid_msat = 0;
6224 for path in &route.paths {
6225 assert_eq!(path.hops.len(), 2);
6226 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6227 total_amount_paid_msat += path.final_value_msat();
6229 assert_eq!(total_amount_paid_msat, 90_000);
6234 fn min_criteria_consistency() {
6235 // Test that we don't use an inconsistent metric between updating and walking nodes during
6236 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
6237 // was updated with a different criterion from the heap sorting, resulting in loops in
6238 // calculated paths. We test for that specific case here.
6240 // We construct a network that looks like this:
6242 // node2 -1(3)2- node3
6246 // node1 -1(5)2- node4 -1(1)2- node6
6252 // We create a loop on the side of our real path - our destination is node 6, with a
6253 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
6254 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
6255 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
6256 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
6257 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
6258 // "previous hop" being set to node 3, creating a loop in the path.
6259 let secp_ctx = Secp256k1::new();
6260 let logger = Arc::new(ln_test_utils::TestLogger::new());
6261 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6262 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
6263 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6264 let scorer = ln_test_utils::TestScorer::new();
6265 let random_seed_bytes = [42; 32];
6266 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
6268 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
6269 for (key, flags) in [(&our_privkey, 0), (&privkeys[1], 3)] {
6270 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6271 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6272 short_channel_id: 6,
6275 cltv_expiry_delta: (6 << 4) | 0,
6276 htlc_minimum_msat: 0,
6277 htlc_maximum_msat: MAX_VALUE_MSAT,
6279 fee_proportional_millionths: 0,
6280 excess_data: Vec::new()
6283 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
6285 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6286 for (key, flags) in [(&privkeys[1], 0), (&privkeys[4], 3)] {
6287 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6288 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6289 short_channel_id: 5,
6292 cltv_expiry_delta: (5 << 4) | 0,
6293 htlc_minimum_msat: 0,
6294 htlc_maximum_msat: MAX_VALUE_MSAT,
6296 fee_proportional_millionths: 0,
6297 excess_data: Vec::new()
6300 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
6302 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
6303 for (key, flags) in [(&privkeys[4], 0), (&privkeys[3], 3)] {
6304 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6305 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6306 short_channel_id: 4,
6309 cltv_expiry_delta: (4 << 4) | 0,
6310 htlc_minimum_msat: 0,
6311 htlc_maximum_msat: MAX_VALUE_MSAT,
6313 fee_proportional_millionths: 0,
6314 excess_data: Vec::new()
6317 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6319 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6320 for (key, flags) in [(&privkeys[3], 0), (&privkeys[2], 3)] {
6321 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6322 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6323 short_channel_id: 3,
6326 cltv_expiry_delta: (3 << 4) | 0,
6327 htlc_minimum_msat: 0,
6328 htlc_maximum_msat: MAX_VALUE_MSAT,
6330 fee_proportional_millionths: 0,
6331 excess_data: Vec::new()
6334 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6336 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6337 for (key, flags) in [(&privkeys[2], 0), (&privkeys[4], 3)] {
6338 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6339 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6340 short_channel_id: 2,
6343 cltv_expiry_delta: (2 << 4) | 0,
6344 htlc_minimum_msat: 0,
6345 htlc_maximum_msat: MAX_VALUE_MSAT,
6347 fee_proportional_millionths: 0,
6348 excess_data: Vec::new()
6352 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6353 for (key, flags) in [(&privkeys[4], 0), (&privkeys[6], 3)] {
6354 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6355 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6356 short_channel_id: 1,
6359 cltv_expiry_delta: (1 << 4) | 0,
6360 htlc_minimum_msat: 100,
6361 htlc_maximum_msat: MAX_VALUE_MSAT,
6363 fee_proportional_millionths: 0,
6364 excess_data: Vec::new()
6367 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6370 // Now ensure the route flows simply over nodes 1 and 4 to 6.
6371 let route_params = RouteParameters::from_payment_params_and_value(
6372 payment_params, 10_000);
6373 let route = get_route(&our_id, &route_params, &network.read_only(), None,
6374 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6375 assert_eq!(route.paths.len(), 1);
6376 assert_eq!(route.paths[0].hops.len(), 3);
6378 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6379 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6380 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6381 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6382 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6383 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6385 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6386 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6387 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6388 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6389 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6390 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6392 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6393 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6394 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6395 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6396 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6397 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6403 fn exact_fee_liquidity_limit() {
6404 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6405 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6406 // we calculated fees on a higher value, resulting in us ignoring such paths.
6407 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6408 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6409 let scorer = ln_test_utils::TestScorer::new();
6410 let random_seed_bytes = [42; 32];
6411 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6413 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6415 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6416 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6417 short_channel_id: 2,
6420 cltv_expiry_delta: 0,
6421 htlc_minimum_msat: 0,
6422 htlc_maximum_msat: 85_000,
6424 fee_proportional_millionths: 0,
6425 excess_data: Vec::new()
6428 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6429 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6430 short_channel_id: 12,
6433 cltv_expiry_delta: (4 << 4) | 1,
6434 htlc_minimum_msat: 0,
6435 htlc_maximum_msat: 270_000,
6437 fee_proportional_millionths: 1000000,
6438 excess_data: Vec::new()
6442 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6443 // 200% fee charged channel 13 in the 1-to-2 direction.
6444 let mut route_params = RouteParameters::from_payment_params_and_value(
6445 payment_params, 90_000);
6446 route_params.max_total_routing_fee_msat = Some(90_000*2);
6447 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6448 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6449 assert_eq!(route.paths.len(), 1);
6450 assert_eq!(route.paths[0].hops.len(), 2);
6452 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6453 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6454 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6455 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6456 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6457 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6459 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6460 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6461 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6462 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6463 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6464 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6469 fn htlc_max_reduction_below_min() {
6470 // Test that if, while walking the graph, we reduce the value being sent to meet an
6471 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6472 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6473 // resulting in us thinking there is no possible path, even if other paths exist.
6474 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6475 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6476 let scorer = ln_test_utils::TestScorer::new();
6477 let random_seed_bytes = [42; 32];
6478 let config = UserConfig::default();
6479 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6480 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6483 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6484 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6485 // then try to send 90_000.
6486 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6487 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6488 short_channel_id: 2,
6491 cltv_expiry_delta: 0,
6492 htlc_minimum_msat: 0,
6493 htlc_maximum_msat: 80_000,
6495 fee_proportional_millionths: 0,
6496 excess_data: Vec::new()
6498 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6499 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6500 short_channel_id: 4,
6503 cltv_expiry_delta: (4 << 4) | 1,
6504 htlc_minimum_msat: 90_000,
6505 htlc_maximum_msat: MAX_VALUE_MSAT,
6507 fee_proportional_millionths: 0,
6508 excess_data: Vec::new()
6512 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6513 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6514 // expensive) channels 12-13 path.
6515 let mut route_params = RouteParameters::from_payment_params_and_value(
6516 payment_params, 90_000);
6517 route_params.max_total_routing_fee_msat = Some(90_000*2);
6518 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6519 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6520 assert_eq!(route.paths.len(), 1);
6521 assert_eq!(route.paths[0].hops.len(), 2);
6523 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6524 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6525 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6526 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6527 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6528 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6530 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6531 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6532 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6533 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6534 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6535 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6540 fn multiple_direct_first_hops() {
6541 // Previously we'd only ever considered one first hop path per counterparty.
6542 // However, as we don't restrict users to one channel per peer, we really need to support
6543 // looking at all first hop paths.
6544 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6545 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6546 // route over multiple channels with the same first hop.
6547 let secp_ctx = Secp256k1::new();
6548 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6549 let logger = Arc::new(ln_test_utils::TestLogger::new());
6550 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6551 let scorer = ln_test_utils::TestScorer::new();
6552 let config = UserConfig::default();
6553 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6554 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6556 let random_seed_bytes = [42; 32];
6559 let route_params = RouteParameters::from_payment_params_and_value(
6560 payment_params.clone(), 100_000);
6561 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6562 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6563 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6564 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6565 assert_eq!(route.paths.len(), 1);
6566 assert_eq!(route.paths[0].hops.len(), 1);
6568 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6569 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6570 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6573 let route_params = RouteParameters::from_payment_params_and_value(
6574 payment_params.clone(), 100_000);
6575 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6576 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6577 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6578 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6579 assert_eq!(route.paths.len(), 2);
6580 assert_eq!(route.paths[0].hops.len(), 1);
6581 assert_eq!(route.paths[1].hops.len(), 1);
6583 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6584 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6586 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6587 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6589 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6590 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6594 // If we have a bunch of outbound channels to the same node, where most are not
6595 // sufficient to pay the full payment, but one is, we should default to just using the
6596 // one single channel that has sufficient balance, avoiding MPP.
6598 // If we have several options above the 3xpayment value threshold, we should pick the
6599 // smallest of them, avoiding further fragmenting our available outbound balance to
6601 let route_params = RouteParameters::from_payment_params_and_value(
6602 payment_params, 100_000);
6603 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6604 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6605 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6606 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6607 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6608 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6609 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6610 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6611 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6612 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6613 assert_eq!(route.paths.len(), 1);
6614 assert_eq!(route.paths[0].hops.len(), 1);
6616 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6617 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6618 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6623 fn prefers_shorter_route_with_higher_fees() {
6624 let (secp_ctx, network_graph, _, _, 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();
6628 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6629 let scorer = ln_test_utils::TestScorer::new();
6630 let random_seed_bytes = [42; 32];
6631 let route_params = RouteParameters::from_payment_params_and_value(
6632 payment_params.clone(), 100);
6633 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6634 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6635 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6637 assert_eq!(route.get_total_fees(), 100);
6638 assert_eq!(route.get_total_amount(), 100);
6639 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6641 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6642 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6643 let scorer = FixedPenaltyScorer::with_penalty(100);
6644 let route_params = RouteParameters::from_payment_params_and_value(
6645 payment_params, 100);
6646 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6647 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6648 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6650 assert_eq!(route.get_total_fees(), 300);
6651 assert_eq!(route.get_total_amount(), 100);
6652 assert_eq!(path, vec![2, 4, 7, 10]);
6655 struct BadChannelScorer {
6656 short_channel_id: u64,
6660 impl Writeable for BadChannelScorer {
6661 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6663 impl ScoreLookUp for BadChannelScorer {
6664 type ScoreParams = ();
6665 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6666 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6670 struct BadNodeScorer {
6675 impl Writeable for BadNodeScorer {
6676 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6679 impl ScoreLookUp for BadNodeScorer {
6680 type ScoreParams = ();
6681 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6682 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6687 fn avoids_routing_through_bad_channels_and_nodes() {
6688 let (secp_ctx, network, _, _, logger) = build_graph();
6689 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6690 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6691 let network_graph = network.read_only();
6693 // A path to nodes[6] exists when no penalties are applied to any channel.
6694 let scorer = ln_test_utils::TestScorer::new();
6695 let random_seed_bytes = [42; 32];
6696 let route_params = RouteParameters::from_payment_params_and_value(
6697 payment_params, 100);
6698 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6699 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6700 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6702 assert_eq!(route.get_total_fees(), 100);
6703 assert_eq!(route.get_total_amount(), 100);
6704 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6706 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6707 let scorer = BadChannelScorer { short_channel_id: 6 };
6708 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6709 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6710 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6712 assert_eq!(route.get_total_fees(), 300);
6713 assert_eq!(route.get_total_amount(), 100);
6714 assert_eq!(path, vec![2, 4, 7, 10]);
6716 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6717 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6718 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6719 &scorer, &Default::default(), &random_seed_bytes) {
6720 Err(LightningError { err, .. } ) => {
6721 assert_eq!(err, "Failed to find a path to the given destination");
6723 Ok(_) => panic!("Expected error"),
6728 fn total_fees_single_path() {
6730 paths: vec![Path { hops: vec![
6732 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6733 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6734 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6737 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6738 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6739 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6742 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6743 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6744 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6746 ], blinded_tail: None }],
6750 assert_eq!(route.get_total_fees(), 250);
6751 assert_eq!(route.get_total_amount(), 225);
6755 fn total_fees_multi_path() {
6757 paths: vec![Path { hops: vec![
6759 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6760 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6761 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6764 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6765 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6766 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6768 ], blinded_tail: None }, Path { hops: vec![
6770 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6771 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6772 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6775 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6776 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6777 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6779 ], blinded_tail: None }],
6783 assert_eq!(route.get_total_fees(), 200);
6784 assert_eq!(route.get_total_amount(), 300);
6788 fn total_empty_route_no_panic() {
6789 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6790 // would both panic if the route was completely empty. We test to ensure they return 0
6791 // here, even though its somewhat nonsensical as a route.
6792 let route = Route { paths: Vec::new(), route_params: None };
6794 assert_eq!(route.get_total_fees(), 0);
6795 assert_eq!(route.get_total_amount(), 0);
6799 fn limits_total_cltv_delta() {
6800 let (secp_ctx, network, _, _, logger) = build_graph();
6801 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6802 let network_graph = network.read_only();
6804 let scorer = ln_test_utils::TestScorer::new();
6806 // Make sure that generally there is at least one route available
6807 let feasible_max_total_cltv_delta = 1008;
6808 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6809 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6810 let random_seed_bytes = [42; 32];
6811 let route_params = RouteParameters::from_payment_params_and_value(
6812 feasible_payment_params, 100);
6813 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6814 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6815 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6816 assert_ne!(path.len(), 0);
6818 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6819 let fail_max_total_cltv_delta = 23;
6820 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6821 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6822 let route_params = RouteParameters::from_payment_params_and_value(
6823 fail_payment_params, 100);
6824 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6825 &Default::default(), &random_seed_bytes)
6827 Err(LightningError { err, .. } ) => {
6828 assert_eq!(err, "Failed to find a path to the given destination");
6830 Ok(_) => panic!("Expected error"),
6835 fn avoids_recently_failed_paths() {
6836 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6837 // randomly inserting channels into it until we can't find a route anymore.
6838 let (secp_ctx, network, _, _, logger) = build_graph();
6839 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6840 let network_graph = network.read_only();
6842 let scorer = ln_test_utils::TestScorer::new();
6843 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6844 .with_max_path_count(1);
6845 let random_seed_bytes = [42; 32];
6847 // We should be able to find a route initially, and then after we fail a few random
6848 // channels eventually we won't be able to any longer.
6849 let route_params = RouteParameters::from_payment_params_and_value(
6850 payment_params.clone(), 100);
6851 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6852 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6854 let route_params = RouteParameters::from_payment_params_and_value(
6855 payment_params.clone(), 100);
6856 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6857 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6859 for chan in route.paths[0].hops.iter() {
6860 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6862 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6863 % route.paths[0].hops.len();
6864 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6870 fn limits_path_length() {
6871 let (secp_ctx, network, _, _, logger) = build_line_graph();
6872 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6873 let network_graph = network.read_only();
6875 let scorer = ln_test_utils::TestScorer::new();
6876 let random_seed_bytes = [42; 32];
6878 // First check we can actually create a long route on this graph.
6879 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6880 let route_params = RouteParameters::from_payment_params_and_value(
6881 feasible_payment_params, 100);
6882 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6883 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6884 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6885 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6887 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6888 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6889 let route_params = RouteParameters::from_payment_params_and_value(
6890 fail_payment_params, 100);
6891 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6892 &Default::default(), &random_seed_bytes)
6894 Err(LightningError { err, .. } ) => {
6895 assert_eq!(err, "Failed to find a path to the given destination");
6897 Ok(_) => panic!("Expected error"),
6902 fn adds_and_limits_cltv_offset() {
6903 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6904 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6906 let scorer = ln_test_utils::TestScorer::new();
6908 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6909 let random_seed_bytes = [42; 32];
6910 let route_params = RouteParameters::from_payment_params_and_value(
6911 payment_params.clone(), 100);
6912 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6913 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6914 assert_eq!(route.paths.len(), 1);
6916 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6918 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6919 let mut route_default = route.clone();
6920 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6921 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6922 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6923 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6924 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6926 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6927 let mut route_limited = route.clone();
6928 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6929 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6930 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6931 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6932 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6936 fn adds_plausible_cltv_offset() {
6937 let (secp_ctx, network, _, _, logger) = build_graph();
6938 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6939 let network_graph = network.read_only();
6940 let network_nodes = network_graph.nodes();
6941 let network_channels = network_graph.channels();
6942 let scorer = ln_test_utils::TestScorer::new();
6943 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6944 let random_seed_bytes = [42; 32];
6946 let route_params = RouteParameters::from_payment_params_and_value(
6947 payment_params.clone(), 100);
6948 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6949 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6950 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6952 let mut path_plausibility = vec![];
6954 for p in route.paths {
6955 // 1. Select random observation point
6956 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6957 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6959 prng.process_in_place(&mut random_bytes);
6960 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6961 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6963 // 2. Calculate what CLTV expiry delta we would observe there
6964 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6966 // 3. Starting from the observation point, find candidate paths
6967 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6968 candidates.push_back((observation_point, vec![]));
6970 let mut found_plausible_candidate = false;
6972 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6973 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6974 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6975 found_plausible_candidate = true;
6976 break 'candidate_loop;
6980 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6981 for channel_id in &cur_node.channels {
6982 if let Some(channel_info) = network_channels.get(&channel_id) {
6983 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6984 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6985 if cur_path_cltv_deltas.iter().sum::<u32>()
6986 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6987 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6988 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6989 candidates.push_back((*next_id, new_path_cltv_deltas));
6997 path_plausibility.push(found_plausible_candidate);
6999 assert!(path_plausibility.iter().all(|x| *x));
7003 fn builds_correct_path_from_hops() {
7004 let (secp_ctx, network, _, _, logger) = build_graph();
7005 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7006 let network_graph = network.read_only();
7008 let random_seed_bytes = [42; 32];
7009 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
7010 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
7011 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
7012 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
7013 Arc::clone(&logger), &random_seed_bytes).unwrap();
7014 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
7015 assert_eq!(hops.len(), route.paths[0].hops.len());
7016 for (idx, hop_pubkey) in hops.iter().enumerate() {
7017 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
7022 fn avoids_saturating_channels() {
7023 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
7024 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
7025 let decay_params = ProbabilisticScoringDecayParameters::default();
7026 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
7028 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
7029 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
7030 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7031 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7032 short_channel_id: 4,
7035 cltv_expiry_delta: (4 << 4) | 1,
7036 htlc_minimum_msat: 0,
7037 htlc_maximum_msat: 250_000_000,
7039 fee_proportional_millionths: 0,
7040 excess_data: Vec::new()
7042 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
7043 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7044 short_channel_id: 13,
7047 cltv_expiry_delta: (13 << 4) | 1,
7048 htlc_minimum_msat: 0,
7049 htlc_maximum_msat: 250_000_000,
7051 fee_proportional_millionths: 0,
7052 excess_data: Vec::new()
7055 let config = UserConfig::default();
7056 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
7057 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7059 let random_seed_bytes = [42; 32];
7061 // 100,000 sats is less than the available liquidity on each channel, set above.
7062 let route_params = RouteParameters::from_payment_params_and_value(
7063 payment_params, 100_000_000);
7064 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
7065 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
7066 assert_eq!(route.paths.len(), 2);
7067 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
7068 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
7071 #[cfg(feature = "std")]
7072 pub(super) fn random_init_seed() -> u64 {
7073 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
7074 use core::hash::{BuildHasher, Hasher};
7075 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
7076 println!("Using seed of {}", seed);
7081 #[cfg(feature = "std")]
7082 fn generate_routes() {
7083 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7085 let logger = ln_test_utils::TestLogger::new();
7086 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7094 let params = ProbabilisticScoringFeeParameters::default();
7095 let features = super::Bolt11InvoiceFeatures::empty();
7097 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7101 #[cfg(feature = "std")]
7102 fn generate_routes_mpp() {
7103 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7105 let logger = ln_test_utils::TestLogger::new();
7106 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7114 let params = ProbabilisticScoringFeeParameters::default();
7115 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7117 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7121 #[cfg(feature = "std")]
7122 fn generate_large_mpp_routes() {
7123 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7125 let logger = ln_test_utils::TestLogger::new();
7126 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7134 let params = ProbabilisticScoringFeeParameters::default();
7135 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7137 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
7141 fn honors_manual_penalties() {
7142 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
7143 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7145 let random_seed_bytes = [42; 32];
7146 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
7147 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
7149 // First check set manual penalties are returned by the scorer.
7150 let usage = ChannelUsage {
7152 inflight_htlc_msat: 0,
7153 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
7155 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
7156 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
7157 let network_graph = network_graph.read_only();
7158 let channels = network_graph.channels();
7159 let channel = channels.get(&5).unwrap();
7160 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
7161 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop(PublicHopCandidate {
7163 short_channel_id: 5,
7165 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
7167 // Then check we can get a normal route
7168 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
7169 let route_params = RouteParameters::from_payment_params_and_value(
7170 payment_params, 100);
7171 let route = get_route(&our_id, &route_params, &network_graph, None,
7172 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
7173 assert!(route.is_ok());
7175 // Then check that we can't get a route if we ban an intermediate node.
7176 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
7177 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7178 assert!(route.is_err());
7180 // Finally make sure we can route again, when we remove the ban.
7181 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
7182 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7183 assert!(route.is_ok());
7187 fn abide_by_route_hint_max_htlc() {
7188 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
7189 // params in the final route.
7190 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7191 let netgraph = network_graph.read_only();
7192 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7193 let scorer = ln_test_utils::TestScorer::new();
7194 let random_seed_bytes = [42; 32];
7195 let config = UserConfig::default();
7197 let max_htlc_msat = 50_000;
7198 let route_hint_1 = RouteHint(vec![RouteHintHop {
7199 src_node_id: nodes[2],
7200 short_channel_id: 42,
7203 proportional_millionths: 0,
7205 cltv_expiry_delta: 10,
7206 htlc_minimum_msat: None,
7207 htlc_maximum_msat: Some(max_htlc_msat),
7209 let dest_node_id = ln_test_utils::pubkey(42);
7210 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7211 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
7212 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7215 // Make sure we'll error if our route hints don't have enough liquidity according to their
7216 // htlc_maximum_msat.
7217 let mut route_params = RouteParameters::from_payment_params_and_value(
7218 payment_params, max_htlc_msat + 1);
7219 route_params.max_total_routing_fee_msat = None;
7220 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
7221 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
7224 assert_eq!(err, "Failed to find a sufficient route to the given destination");
7225 } else { panic!(); }
7227 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
7228 let mut route_hint_2 = route_hint_1.clone();
7229 route_hint_2.0[0].short_channel_id = 43;
7230 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7231 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7232 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7234 let mut route_params = RouteParameters::from_payment_params_and_value(
7235 payment_params, max_htlc_msat + 1);
7236 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
7237 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
7238 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7239 assert_eq!(route.paths.len(), 2);
7240 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7241 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7245 fn direct_channel_to_hints_with_max_htlc() {
7246 // Check that if we have a first hop channel peer that's connected to multiple provided route
7247 // hints, that we properly split the payment between the route hints if needed.
7248 let logger = Arc::new(ln_test_utils::TestLogger::new());
7249 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7250 let scorer = ln_test_utils::TestScorer::new();
7251 let random_seed_bytes = [42; 32];
7252 let config = UserConfig::default();
7254 let our_node_id = ln_test_utils::pubkey(42);
7255 let intermed_node_id = ln_test_utils::pubkey(43);
7256 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7258 let amt_msat = 900_000;
7259 let max_htlc_msat = 500_000;
7260 let route_hint_1 = RouteHint(vec![RouteHintHop {
7261 src_node_id: intermed_node_id,
7262 short_channel_id: 44,
7265 proportional_millionths: 0,
7267 cltv_expiry_delta: 10,
7268 htlc_minimum_msat: None,
7269 htlc_maximum_msat: Some(max_htlc_msat),
7271 src_node_id: intermed_node_id,
7272 short_channel_id: 45,
7275 proportional_millionths: 0,
7277 cltv_expiry_delta: 10,
7278 htlc_minimum_msat: None,
7279 // Check that later route hint max htlcs don't override earlier ones
7280 htlc_maximum_msat: Some(max_htlc_msat - 50),
7282 let mut route_hint_2 = route_hint_1.clone();
7283 route_hint_2.0[0].short_channel_id = 46;
7284 route_hint_2.0[1].short_channel_id = 47;
7285 let dest_node_id = ln_test_utils::pubkey(44);
7286 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7287 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7288 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7291 let route_params = RouteParameters::from_payment_params_and_value(
7292 payment_params, amt_msat);
7293 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7294 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7295 &Default::default(), &random_seed_bytes).unwrap();
7296 assert_eq!(route.paths.len(), 2);
7297 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7298 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7299 assert_eq!(route.get_total_amount(), amt_msat);
7301 // Re-run but with two first hop channels connected to the same route hint peers that must be
7303 let first_hops = vec![
7304 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7305 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7307 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7308 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7309 &Default::default(), &random_seed_bytes).unwrap();
7310 assert_eq!(route.paths.len(), 2);
7311 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7312 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7313 assert_eq!(route.get_total_amount(), amt_msat);
7315 // Make sure this works for blinded route hints.
7316 let blinded_path = BlindedPath {
7317 introduction_node: IntroductionNode::NodeId(intermed_node_id),
7318 blinding_point: ln_test_utils::pubkey(42),
7320 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
7321 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
7324 let blinded_payinfo = BlindedPayInfo {
7326 fee_proportional_millionths: 0,
7327 htlc_minimum_msat: 1,
7328 htlc_maximum_msat: max_htlc_msat,
7329 cltv_expiry_delta: 10,
7330 features: BlindedHopFeatures::empty(),
7332 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7333 let payment_params = PaymentParameters::blinded(vec![
7334 (blinded_payinfo.clone(), blinded_path.clone()),
7335 (blinded_payinfo.clone(), blinded_path.clone())])
7336 .with_bolt12_features(bolt12_features).unwrap();
7337 let route_params = RouteParameters::from_payment_params_and_value(
7338 payment_params, amt_msat);
7339 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7340 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7341 &Default::default(), &random_seed_bytes).unwrap();
7342 assert_eq!(route.paths.len(), 2);
7343 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7344 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7345 assert_eq!(route.get_total_amount(), amt_msat);
7349 fn blinded_route_ser() {
7350 let blinded_path_1 = BlindedPath {
7351 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(42)),
7352 blinding_point: ln_test_utils::pubkey(43),
7354 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7355 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7358 let blinded_path_2 = BlindedPath {
7359 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(46)),
7360 blinding_point: ln_test_utils::pubkey(47),
7362 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7363 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7366 // (De)serialize a Route with 1 blinded path out of two total paths.
7367 let mut route = Route { paths: vec![Path {
7368 hops: vec![RouteHop {
7369 pubkey: ln_test_utils::pubkey(50),
7370 node_features: NodeFeatures::empty(),
7371 short_channel_id: 42,
7372 channel_features: ChannelFeatures::empty(),
7374 cltv_expiry_delta: 0,
7375 maybe_announced_channel: true,
7377 blinded_tail: Some(BlindedTail {
7378 hops: blinded_path_1.blinded_hops,
7379 blinding_point: blinded_path_1.blinding_point,
7380 excess_final_cltv_expiry_delta: 40,
7381 final_value_msat: 100,
7383 hops: vec![RouteHop {
7384 pubkey: ln_test_utils::pubkey(51),
7385 node_features: NodeFeatures::empty(),
7386 short_channel_id: 43,
7387 channel_features: ChannelFeatures::empty(),
7389 cltv_expiry_delta: 0,
7390 maybe_announced_channel: true,
7391 }], blinded_tail: None }],
7394 let encoded_route = route.encode();
7395 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7396 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7397 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7399 // (De)serialize a Route with two paths, each containing a blinded tail.
7400 route.paths[1].blinded_tail = Some(BlindedTail {
7401 hops: blinded_path_2.blinded_hops,
7402 blinding_point: blinded_path_2.blinding_point,
7403 excess_final_cltv_expiry_delta: 41,
7404 final_value_msat: 101,
7406 let encoded_route = route.encode();
7407 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7408 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7409 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7413 fn blinded_path_inflight_processing() {
7414 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7415 // account for the blinded tail's final amount_msat.
7416 let mut inflight_htlcs = InFlightHtlcs::new();
7417 let blinded_path = BlindedPath {
7418 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(43)),
7419 blinding_point: ln_test_utils::pubkey(48),
7420 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7423 hops: vec![RouteHop {
7424 pubkey: ln_test_utils::pubkey(42),
7425 node_features: NodeFeatures::empty(),
7426 short_channel_id: 42,
7427 channel_features: ChannelFeatures::empty(),
7429 cltv_expiry_delta: 0,
7430 maybe_announced_channel: false,
7433 pubkey: ln_test_utils::pubkey(43),
7434 node_features: NodeFeatures::empty(),
7435 short_channel_id: 43,
7436 channel_features: ChannelFeatures::empty(),
7438 cltv_expiry_delta: 0,
7439 maybe_announced_channel: false,
7441 blinded_tail: Some(BlindedTail {
7442 hops: blinded_path.blinded_hops,
7443 blinding_point: blinded_path.blinding_point,
7444 excess_final_cltv_expiry_delta: 0,
7445 final_value_msat: 200,
7448 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7449 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7450 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7454 fn blinded_path_cltv_shadow_offset() {
7455 // Make sure we add a shadow offset when sending to blinded paths.
7456 let blinded_path = BlindedPath {
7457 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(43)),
7458 blinding_point: ln_test_utils::pubkey(44),
7460 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7461 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7464 let mut route = Route { paths: vec![Path {
7465 hops: vec![RouteHop {
7466 pubkey: ln_test_utils::pubkey(42),
7467 node_features: NodeFeatures::empty(),
7468 short_channel_id: 42,
7469 channel_features: ChannelFeatures::empty(),
7471 cltv_expiry_delta: 0,
7472 maybe_announced_channel: false,
7475 pubkey: ln_test_utils::pubkey(43),
7476 node_features: NodeFeatures::empty(),
7477 short_channel_id: 43,
7478 channel_features: ChannelFeatures::empty(),
7480 cltv_expiry_delta: 0,
7481 maybe_announced_channel: false,
7484 blinded_tail: Some(BlindedTail {
7485 hops: blinded_path.blinded_hops,
7486 blinding_point: blinded_path.blinding_point,
7487 excess_final_cltv_expiry_delta: 0,
7488 final_value_msat: 200,
7490 }], route_params: None};
7492 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7493 let (_, network_graph, _, _, _) = build_line_graph();
7494 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7495 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7496 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7500 fn simple_blinded_route_hints() {
7501 do_simple_blinded_route_hints(1);
7502 do_simple_blinded_route_hints(2);
7503 do_simple_blinded_route_hints(3);
7506 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7507 // Check that we can generate a route to a blinded path with the expected hops.
7508 let (secp_ctx, network, _, _, logger) = build_graph();
7509 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7510 let network_graph = network.read_only();
7512 let scorer = ln_test_utils::TestScorer::new();
7513 let random_seed_bytes = [42; 32];
7515 let mut blinded_path = BlindedPath {
7516 introduction_node: IntroductionNode::NodeId(nodes[2]),
7517 blinding_point: ln_test_utils::pubkey(42),
7518 blinded_hops: Vec::with_capacity(num_blinded_hops),
7520 for i in 0..num_blinded_hops {
7521 blinded_path.blinded_hops.push(
7522 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7525 let blinded_payinfo = BlindedPayInfo {
7527 fee_proportional_millionths: 500,
7528 htlc_minimum_msat: 1000,
7529 htlc_maximum_msat: 100_000_000,
7530 cltv_expiry_delta: 15,
7531 features: BlindedHopFeatures::empty(),
7534 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7535 let route_params = RouteParameters::from_payment_params_and_value(
7536 payment_params, 1001);
7537 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7538 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7539 assert_eq!(route.paths.len(), 1);
7540 assert_eq!(route.paths[0].hops.len(), 2);
7542 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7543 assert_eq!(tail.hops, blinded_path.blinded_hops);
7544 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7545 assert_eq!(tail.final_value_msat, 1001);
7547 let final_hop = route.paths[0].hops.last().unwrap();
7549 NodeId::from_pubkey(&final_hop.pubkey),
7550 *blinded_path.public_introduction_node_id(&network_graph).unwrap()
7552 if tail.hops.len() > 1 {
7553 assert_eq!(final_hop.fee_msat,
7554 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7555 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7557 assert_eq!(final_hop.fee_msat, 0);
7558 assert_eq!(final_hop.cltv_expiry_delta, 0);
7563 fn blinded_path_routing_errors() {
7564 // Check that we can generate a route to a blinded path with the expected hops.
7565 let (secp_ctx, network, _, _, logger) = build_graph();
7566 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7567 let network_graph = network.read_only();
7569 let scorer = ln_test_utils::TestScorer::new();
7570 let random_seed_bytes = [42; 32];
7572 let mut invalid_blinded_path = BlindedPath {
7573 introduction_node: IntroductionNode::NodeId(nodes[2]),
7574 blinding_point: ln_test_utils::pubkey(42),
7576 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7579 let blinded_payinfo = BlindedPayInfo {
7581 fee_proportional_millionths: 500,
7582 htlc_minimum_msat: 1000,
7583 htlc_maximum_msat: 100_000_000,
7584 cltv_expiry_delta: 15,
7585 features: BlindedHopFeatures::empty(),
7588 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7589 invalid_blinded_path_2.introduction_node = IntroductionNode::NodeId(ln_test_utils::pubkey(45));
7590 let payment_params = PaymentParameters::blinded(vec![
7591 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7592 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7593 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7594 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7595 &scorer, &Default::default(), &random_seed_bytes)
7597 Err(LightningError { err, .. }) => {
7598 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7600 _ => panic!("Expected error")
7603 invalid_blinded_path.introduction_node = IntroductionNode::NodeId(our_id);
7604 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7605 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7606 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7607 &Default::default(), &random_seed_bytes)
7609 Err(LightningError { err, .. }) => {
7610 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7612 _ => panic!("Expected error")
7615 invalid_blinded_path.introduction_node = IntroductionNode::NodeId(ln_test_utils::pubkey(46));
7616 invalid_blinded_path.blinded_hops.clear();
7617 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7618 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7619 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7620 &Default::default(), &random_seed_bytes)
7622 Err(LightningError { err, .. }) => {
7623 assert_eq!(err, "0-hop blinded path provided");
7625 _ => panic!("Expected error")
7630 fn matching_intro_node_paths_provided() {
7631 // Check that if multiple blinded paths with the same intro node are provided in payment
7632 // parameters, we'll return the correct paths in the resulting MPP route.
7633 let (secp_ctx, network, _, _, logger) = build_graph();
7634 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7635 let network_graph = network.read_only();
7637 let scorer = ln_test_utils::TestScorer::new();
7638 let random_seed_bytes = [42; 32];
7639 let config = UserConfig::default();
7641 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7642 let blinded_path_1 = BlindedPath {
7643 introduction_node: IntroductionNode::NodeId(nodes[2]),
7644 blinding_point: ln_test_utils::pubkey(42),
7646 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7647 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7650 let blinded_payinfo_1 = BlindedPayInfo {
7652 fee_proportional_millionths: 0,
7653 htlc_minimum_msat: 0,
7654 htlc_maximum_msat: 30_000,
7655 cltv_expiry_delta: 0,
7656 features: BlindedHopFeatures::empty(),
7659 let mut blinded_path_2 = blinded_path_1.clone();
7660 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7661 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7662 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7664 let blinded_hints = vec![
7665 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7666 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7668 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7669 .with_bolt12_features(bolt12_features).unwrap();
7671 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7672 route_params.max_total_routing_fee_msat = Some(100_000);
7673 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7674 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7675 assert_eq!(route.paths.len(), 2);
7676 let mut total_amount_paid_msat = 0;
7677 for path in route.paths.into_iter() {
7678 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7679 if let Some(bt) = &path.blinded_tail {
7680 assert_eq!(bt.blinding_point,
7681 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7682 .map(|(_, bp)| bp.blinding_point).unwrap());
7683 } else { panic!(); }
7684 total_amount_paid_msat += path.final_value_msat();
7686 assert_eq!(total_amount_paid_msat, 100_000);
7690 fn direct_to_intro_node() {
7691 // This previously caused a debug panic in the router when asserting
7692 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7693 // direct channels we failed to account for the fee charged for use of the blinded path.
7696 // node0 -1(1)2 - node1
7697 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7698 // doesn't account for the blinded path fee.
7700 let secp_ctx = Secp256k1::new();
7701 let logger = Arc::new(ln_test_utils::TestLogger::new());
7702 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7703 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7704 let scorer = ln_test_utils::TestScorer::new();
7705 let random_seed_bytes = [42; 32];
7707 let amt_msat = 10_000_000;
7708 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7709 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7710 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7711 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7712 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7713 short_channel_id: 1,
7716 cltv_expiry_delta: 42,
7717 htlc_minimum_msat: 1_000,
7718 htlc_maximum_msat: 10_000_000,
7720 fee_proportional_millionths: 0,
7721 excess_data: Vec::new()
7723 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7724 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7725 short_channel_id: 1,
7728 cltv_expiry_delta: 42,
7729 htlc_minimum_msat: 1_000,
7730 htlc_maximum_msat: 10_000_000,
7732 fee_proportional_millionths: 0,
7733 excess_data: Vec::new()
7735 let first_hops = vec![
7736 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7738 let blinded_path = BlindedPath {
7739 introduction_node: IntroductionNode::NodeId(nodes[1]),
7740 blinding_point: ln_test_utils::pubkey(42),
7742 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7743 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7746 let blinded_payinfo = BlindedPayInfo {
7747 fee_base_msat: 1000,
7748 fee_proportional_millionths: 0,
7749 htlc_minimum_msat: 1000,
7750 htlc_maximum_msat: MAX_VALUE_MSAT,
7751 cltv_expiry_delta: 0,
7752 features: BlindedHopFeatures::empty(),
7754 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7756 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7758 let netgraph = network_graph.read_only();
7759 let route_params = RouteParameters::from_payment_params_and_value(
7760 payment_params.clone(), amt_msat);
7761 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7762 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7763 &Default::default(), &random_seed_bytes) {
7764 assert_eq!(err, "Failed to find a path to the given destination");
7765 } else { panic!("Expected error") }
7767 // Sending an exact amount accounting for the blinded path fee works.
7768 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7769 let route_params = RouteParameters::from_payment_params_and_value(
7770 payment_params, amt_minus_blinded_path_fee);
7771 let route = get_route(&nodes[0], &route_params, &netgraph,
7772 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7773 &Default::default(), &random_seed_bytes).unwrap();
7774 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7775 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7779 fn direct_to_matching_intro_nodes() {
7780 // This previously caused us to enter `unreachable` code in the following situation:
7781 // 1. We add a route candidate for intro_node contributing a high amount
7782 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7783 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7784 // amount, and update our route candidate for intro_node for the lower amount
7785 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7786 // lower contribution amount, but fail (this was previously caused by failure to account for
7787 // blinded path fees when adding first_hop<>intro_node candidates)
7788 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7789 // candidate still thinks its path is contributing the original higher amount. This caused us
7790 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7792 let secp_ctx = Secp256k1::new();
7793 let logger = Arc::new(ln_test_utils::TestLogger::new());
7794 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7795 let scorer = ln_test_utils::TestScorer::new();
7796 let random_seed_bytes = [42; 32];
7797 let config = UserConfig::default();
7799 // Values are taken from the fuzz input that uncovered this panic.
7800 let amt_msat = 21_7020_5185_1403_2640;
7801 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7802 let first_hops = vec![
7803 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7804 18446744073709551615)];
7806 let blinded_path = BlindedPath {
7807 introduction_node: IntroductionNode::NodeId(nodes[1]),
7808 blinding_point: ln_test_utils::pubkey(42),
7810 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7811 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7814 let blinded_payinfo = BlindedPayInfo {
7815 fee_base_msat: 5046_2720,
7816 fee_proportional_millionths: 0,
7817 htlc_minimum_msat: 4503_5996_2737_0496,
7818 htlc_maximum_msat: 45_0359_9627_3704_9600,
7819 cltv_expiry_delta: 0,
7820 features: BlindedHopFeatures::empty(),
7822 let mut blinded_hints = vec![
7823 (blinded_payinfo.clone(), blinded_path.clone()),
7824 (blinded_payinfo.clone(), blinded_path.clone()),
7826 blinded_hints[1].0.fee_base_msat = 419_4304;
7827 blinded_hints[1].0.fee_proportional_millionths = 257;
7828 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7829 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7830 blinded_hints[1].0.cltv_expiry_delta = 0;
7832 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7833 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7834 .with_bolt12_features(bolt12_features).unwrap();
7836 let netgraph = network_graph.read_only();
7837 let route_params = RouteParameters::from_payment_params_and_value(
7838 payment_params, amt_msat);
7839 let route = get_route(&nodes[0], &route_params, &netgraph,
7840 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7841 &Default::default(), &random_seed_bytes).unwrap();
7842 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7843 assert_eq!(route.get_total_amount(), amt_msat);
7847 fn we_are_intro_node_candidate_hops() {
7848 // This previously led to a panic in the router because we'd generate a Path with only a
7849 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7850 // where the origin node is the intro node. We now fully disallow considering candidate hops
7851 // where the origin node is the intro node.
7852 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7853 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7854 let scorer = ln_test_utils::TestScorer::new();
7855 let random_seed_bytes = [42; 32];
7856 let config = UserConfig::default();
7858 // Values are taken from the fuzz input that uncovered this panic.
7859 let amt_msat = 21_7020_5185_1423_0019;
7861 let blinded_path = BlindedPath {
7862 introduction_node: IntroductionNode::NodeId(our_id),
7863 blinding_point: ln_test_utils::pubkey(42),
7865 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7866 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7869 let blinded_payinfo = BlindedPayInfo {
7870 fee_base_msat: 5052_9027,
7871 fee_proportional_millionths: 0,
7872 htlc_minimum_msat: 21_7020_5185_1423_0019,
7873 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7874 cltv_expiry_delta: 0,
7875 features: BlindedHopFeatures::empty(),
7877 let mut blinded_hints = vec![
7878 (blinded_payinfo.clone(), blinded_path.clone()),
7879 (blinded_payinfo.clone(), blinded_path.clone()),
7881 blinded_hints[1].1.introduction_node = IntroductionNode::NodeId(nodes[6]);
7883 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7884 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7885 .with_bolt12_features(bolt12_features.clone()).unwrap();
7887 let netgraph = network_graph.read_only();
7888 let route_params = RouteParameters::from_payment_params_and_value(
7889 payment_params, amt_msat);
7890 if let Err(LightningError { err, .. }) = get_route(
7891 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7893 assert_eq!(err, "Failed to find a path to the given destination");
7898 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7899 // This previously led to a debug panic in the router because we'd find an invalid Path with
7900 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7901 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7902 // the payment, when it was intended to only include the final value of the payment.
7903 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7904 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7905 let scorer = ln_test_utils::TestScorer::new();
7906 let random_seed_bytes = [42; 32];
7907 let config = UserConfig::default();
7909 // Values are taken from the fuzz input that uncovered this panic.
7910 let amt_msat = 21_7020_5185_1423_0019;
7912 let blinded_path = BlindedPath {
7913 introduction_node: IntroductionNode::NodeId(our_id),
7914 blinding_point: ln_test_utils::pubkey(42),
7916 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7917 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7920 let blinded_payinfo = BlindedPayInfo {
7921 fee_base_msat: 10_4425_1395,
7922 fee_proportional_millionths: 0,
7923 htlc_minimum_msat: 21_7301_9934_9094_0931,
7924 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7925 cltv_expiry_delta: 0,
7926 features: BlindedHopFeatures::empty(),
7928 let mut blinded_hints = vec![
7929 (blinded_payinfo.clone(), blinded_path.clone()),
7930 (blinded_payinfo.clone(), blinded_path.clone()),
7931 (blinded_payinfo.clone(), blinded_path.clone()),
7933 blinded_hints[1].0.fee_base_msat = 5052_9027;
7934 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7935 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7937 blinded_hints[2].1.introduction_node = IntroductionNode::NodeId(nodes[6]);
7939 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7940 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7941 .with_bolt12_features(bolt12_features.clone()).unwrap();
7943 let netgraph = network_graph.read_only();
7944 let route_params = RouteParameters::from_payment_params_and_value(
7945 payment_params, amt_msat);
7946 if let Err(LightningError { err, .. }) = get_route(
7947 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7949 assert_eq!(err, "Failed to find a path to the given destination");
7954 fn min_htlc_overpay_violates_max_htlc() {
7955 do_min_htlc_overpay_violates_max_htlc(true);
7956 do_min_htlc_overpay_violates_max_htlc(false);
7958 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7959 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7960 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7961 // to `targets` and build an invalid path with it, and subsequently hit a debug panic asserting
7962 // that the used liquidity for a hop was less than its available liquidity limit.
7963 let secp_ctx = Secp256k1::new();
7964 let logger = Arc::new(ln_test_utils::TestLogger::new());
7965 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7966 let scorer = ln_test_utils::TestScorer::new();
7967 let random_seed_bytes = [42; 32];
7968 let config = UserConfig::default();
7970 // Values are taken from the fuzz input that uncovered this panic.
7971 let amt_msat = 7_4009_8048;
7972 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7973 let first_hop_outbound_capacity = 2_7345_2000;
7974 let first_hops = vec![get_channel_details(
7975 Some(200), nodes[0], channelmanager::provided_init_features(&config),
7976 first_hop_outbound_capacity
7979 let base_fee = 1_6778_3453;
7980 let htlc_min = 2_5165_8240;
7981 let payment_params = if blinded_payee {
7982 let blinded_path = BlindedPath {
7983 introduction_node: IntroductionNode::NodeId(nodes[0]),
7984 blinding_point: ln_test_utils::pubkey(42),
7986 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7987 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7990 let blinded_payinfo = BlindedPayInfo {
7991 fee_base_msat: base_fee,
7992 fee_proportional_millionths: 0,
7993 htlc_minimum_msat: htlc_min,
7994 htlc_maximum_msat: htlc_min * 1000,
7995 cltv_expiry_delta: 0,
7996 features: BlindedHopFeatures::empty(),
7998 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7999 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
8000 .with_bolt12_features(bolt12_features.clone()).unwrap()
8002 let route_hint = RouteHint(vec![RouteHintHop {
8003 src_node_id: nodes[0],
8004 short_channel_id: 42,
8006 base_msat: base_fee,
8007 proportional_millionths: 0,
8009 cltv_expiry_delta: 10,
8010 htlc_minimum_msat: Some(htlc_min),
8011 htlc_maximum_msat: None,
8014 PaymentParameters::from_node_id(nodes[1], 42)
8015 .with_route_hints(vec![route_hint]).unwrap()
8016 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8019 let netgraph = network_graph.read_only();
8020 let route_params = RouteParameters::from_payment_params_and_value(
8021 payment_params, amt_msat);
8022 if let Err(LightningError { err, .. }) = get_route(
8023 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8024 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8026 assert_eq!(err, "Failed to find a path to the given destination");
8031 fn previously_used_liquidity_violates_max_htlc() {
8032 do_previously_used_liquidity_violates_max_htlc(true);
8033 do_previously_used_liquidity_violates_max_htlc(false);
8036 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
8037 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
8038 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
8039 // candidate. In this case, the candidate does not have enough due to a previous path taking up
8040 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
8041 // asserting that the used liquidity for a hop was less than its available liquidity limit.
8042 let secp_ctx = Secp256k1::new();
8043 let logger = Arc::new(ln_test_utils::TestLogger::new());
8044 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8045 let scorer = ln_test_utils::TestScorer::new();
8046 let random_seed_bytes = [42; 32];
8047 let config = UserConfig::default();
8049 // Values are taken from the fuzz input that uncovered this panic.
8050 let amt_msat = 52_4288;
8051 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8052 let first_hops = vec![get_channel_details(
8053 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
8054 ), get_channel_details(
8055 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
8058 let base_fees = [0, 425_9840, 0, 0];
8059 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
8060 let payment_params = if blinded_payee {
8061 let blinded_path = BlindedPath {
8062 introduction_node: IntroductionNode::NodeId(nodes[0]),
8063 blinding_point: ln_test_utils::pubkey(42),
8065 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8066 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8069 let mut blinded_hints = Vec::new();
8070 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
8071 blinded_hints.push((BlindedPayInfo {
8072 fee_base_msat: *base_fee,
8073 fee_proportional_millionths: 0,
8074 htlc_minimum_msat: *htlc_min,
8075 htlc_maximum_msat: htlc_min * 100,
8076 cltv_expiry_delta: 10,
8077 features: BlindedHopFeatures::empty(),
8078 }, blinded_path.clone()));
8080 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8081 PaymentParameters::blinded(blinded_hints.clone())
8082 .with_bolt12_features(bolt12_features.clone()).unwrap()
8084 let mut route_hints = Vec::new();
8085 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
8086 route_hints.push(RouteHint(vec![RouteHintHop {
8087 src_node_id: nodes[0],
8088 short_channel_id: 42 + idx as u64,
8090 base_msat: *base_fee,
8091 proportional_millionths: 0,
8093 cltv_expiry_delta: 10,
8094 htlc_minimum_msat: Some(*htlc_min),
8095 htlc_maximum_msat: Some(htlc_min * 100),
8098 PaymentParameters::from_node_id(nodes[1], 42)
8099 .with_route_hints(route_hints).unwrap()
8100 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8103 let netgraph = network_graph.read_only();
8104 let route_params = RouteParameters::from_payment_params_and_value(
8105 payment_params, amt_msat);
8107 let route = get_route(
8108 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8109 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8111 assert_eq!(route.paths.len(), 1);
8112 assert_eq!(route.get_total_amount(), amt_msat);
8116 fn candidate_path_min() {
8117 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
8118 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
8119 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
8120 // would add a connecting first_hop node that did not have enough contribution amount, leading
8121 // to a debug panic upon invalid path construction.
8122 let secp_ctx = Secp256k1::new();
8123 let logger = Arc::new(ln_test_utils::TestLogger::new());
8124 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8125 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
8126 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8127 let random_seed_bytes = [42; 32];
8128 let config = UserConfig::default();
8130 // Values are taken from the fuzz input that uncovered this panic.
8131 let amt_msat = 7_4009_8048;
8132 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
8133 let first_hops = vec![get_channel_details(
8134 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
8137 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
8138 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8139 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8140 short_channel_id: 6,
8143 cltv_expiry_delta: (6 << 4) | 0,
8144 htlc_minimum_msat: 0,
8145 htlc_maximum_msat: MAX_VALUE_MSAT,
8147 fee_proportional_millionths: 0,
8148 excess_data: Vec::new()
8150 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
8152 let htlc_min = 2_5165_8240;
8153 let blinded_hints = vec![
8155 fee_base_msat: 1_6778_3453,
8156 fee_proportional_millionths: 0,
8157 htlc_minimum_msat: htlc_min,
8158 htlc_maximum_msat: htlc_min * 100,
8159 cltv_expiry_delta: 10,
8160 features: BlindedHopFeatures::empty(),
8162 introduction_node: IntroductionNode::NodeId(nodes[0]),
8163 blinding_point: ln_test_utils::pubkey(42),
8165 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8166 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8170 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8171 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8172 .with_bolt12_features(bolt12_features.clone()).unwrap();
8173 let route_params = RouteParameters::from_payment_params_and_value(
8174 payment_params, amt_msat);
8175 let netgraph = network_graph.read_only();
8177 if let Err(LightningError { err, .. }) = get_route(
8178 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8179 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8182 assert_eq!(err, "Failed to find a path to the given destination");
8187 fn path_contribution_includes_min_htlc_overpay() {
8188 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
8189 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
8190 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
8191 // selection, both tested here.
8192 let secp_ctx = Secp256k1::new();
8193 let logger = Arc::new(ln_test_utils::TestLogger::new());
8194 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8195 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8196 let random_seed_bytes = [42; 32];
8197 let config = UserConfig::default();
8199 // Values are taken from the fuzz input that uncovered this panic.
8200 let amt_msat = 562_0000;
8201 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8202 let first_hops = vec![
8203 get_channel_details(
8204 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
8208 let htlc_mins = [49_0000, 1125_0000];
8209 let payment_params = {
8210 let blinded_path = BlindedPath {
8211 introduction_node: IntroductionNode::NodeId(nodes[0]),
8212 blinding_point: ln_test_utils::pubkey(42),
8214 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8215 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8218 let mut blinded_hints = Vec::new();
8219 for htlc_min in htlc_mins.iter() {
8220 blinded_hints.push((BlindedPayInfo {
8222 fee_proportional_millionths: 0,
8223 htlc_minimum_msat: *htlc_min,
8224 htlc_maximum_msat: *htlc_min * 100,
8225 cltv_expiry_delta: 10,
8226 features: BlindedHopFeatures::empty(),
8227 }, blinded_path.clone()));
8229 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8230 PaymentParameters::blinded(blinded_hints.clone())
8231 .with_bolt12_features(bolt12_features.clone()).unwrap()
8234 let netgraph = network_graph.read_only();
8235 let route_params = RouteParameters::from_payment_params_and_value(
8236 payment_params, amt_msat);
8237 let route = get_route(
8238 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8239 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8242 assert_eq!(route.paths.len(), 1);
8243 assert_eq!(route.get_total_amount(), amt_msat);
8247 fn first_hop_preferred_over_hint() {
8248 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
8249 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
8250 let secp_ctx = Secp256k1::new();
8251 let logger = Arc::new(ln_test_utils::TestLogger::new());
8252 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8253 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
8254 let scorer = ln_test_utils::TestScorer::new();
8255 let random_seed_bytes = [42; 32];
8256 let config = UserConfig::default();
8258 let amt_msat = 1_000_000;
8259 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
8261 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
8262 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
8263 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8264 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8265 short_channel_id: 1,
8268 cltv_expiry_delta: 42,
8269 htlc_minimum_msat: 1_000,
8270 htlc_maximum_msat: 10_000_000,
8272 fee_proportional_millionths: 0,
8273 excess_data: Vec::new()
8275 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8276 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8277 short_channel_id: 1,
8280 cltv_expiry_delta: 42,
8281 htlc_minimum_msat: 1_000,
8282 htlc_maximum_msat: 10_000_000,
8284 fee_proportional_millionths: 0,
8285 excess_data: Vec::new()
8288 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
8289 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
8290 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8291 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8292 short_channel_id: 2,
8295 cltv_expiry_delta: 42,
8296 htlc_minimum_msat: 1_000,
8297 htlc_maximum_msat: 10_000_000,
8299 fee_proportional_millionths: 0,
8300 excess_data: Vec::new()
8302 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8303 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8304 short_channel_id: 2,
8307 cltv_expiry_delta: 42,
8308 htlc_minimum_msat: 1_000,
8309 htlc_maximum_msat: 10_000_000,
8311 fee_proportional_millionths: 0,
8312 excess_data: Vec::new()
8315 let dest_node_id = nodes[2];
8317 let route_hint = RouteHint(vec![RouteHintHop {
8318 src_node_id: our_node_id,
8319 short_channel_id: 44,
8322 proportional_millionths: 0,
8324 cltv_expiry_delta: 10,
8325 htlc_minimum_msat: None,
8326 htlc_maximum_msat: Some(5_000_000),
8329 src_node_id: nodes[0],
8330 short_channel_id: 45,
8333 proportional_millionths: 0,
8335 cltv_expiry_delta: 10,
8336 htlc_minimum_msat: None,
8337 htlc_maximum_msat: None,
8340 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8341 .with_route_hints(vec![route_hint]).unwrap()
8342 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8343 let route_params = RouteParameters::from_payment_params_and_value(
8344 payment_params, amt_msat);
8346 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8348 let first_hop = get_channel_details(Some(1), nodes[0],
8349 channelmanager::provided_init_features(&config), 999_999);
8350 let first_hops = vec![first_hop];
8352 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8353 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8354 &Default::default(), &random_seed_bytes).unwrap();
8355 assert_eq!(route.paths.len(), 1);
8356 assert_eq!(route.get_total_amount(), amt_msat);
8357 assert_eq!(route.paths[0].hops.len(), 2);
8358 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8359 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8360 assert_eq!(route.get_total_fees(), 123);
8362 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8363 // for a first hop channel.
8364 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8365 first_hop.outbound_scid_alias = Some(44);
8366 let first_hops = vec![first_hop];
8368 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8369 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8370 &Default::default(), &random_seed_bytes);
8371 assert!(route_res.is_err());
8373 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8374 // use the cheaper second hop of the route hint.
8375 let mut first_hop = get_channel_details(Some(1), nodes[0],
8376 channelmanager::provided_init_features(&config), 10_000_000);
8377 first_hop.outbound_scid_alias = Some(44);
8378 let first_hops = vec![first_hop];
8380 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8381 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8382 &Default::default(), &random_seed_bytes).unwrap();
8383 assert_eq!(route.paths.len(), 1);
8384 assert_eq!(route.get_total_amount(), amt_msat);
8385 assert_eq!(route.paths[0].hops.len(), 2);
8386 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8387 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8388 assert_eq!(route.get_total_fees(), 123);
8392 fn allow_us_being_first_hint() {
8393 // Check that we consider a route hint even if we are the src of the first hop.
8394 let secp_ctx = Secp256k1::new();
8395 let logger = Arc::new(ln_test_utils::TestLogger::new());
8396 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8397 let scorer = ln_test_utils::TestScorer::new();
8398 let random_seed_bytes = [42; 32];
8399 let config = UserConfig::default();
8401 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8403 let amt_msat = 1_000_000;
8404 let dest_node_id = nodes[1];
8406 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8407 let first_hops = vec![first_hop];
8409 let route_hint = RouteHint(vec![RouteHintHop {
8410 src_node_id: our_node_id,
8411 short_channel_id: 44,
8414 proportional_millionths: 0,
8416 cltv_expiry_delta: 10,
8417 htlc_minimum_msat: None,
8418 htlc_maximum_msat: None,
8421 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8422 .with_route_hints(vec![route_hint]).unwrap()
8423 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8425 let route_params = RouteParameters::from_payment_params_and_value(
8426 payment_params, amt_msat);
8429 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8430 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8431 &Default::default(), &random_seed_bytes).unwrap();
8433 assert_eq!(route.paths.len(), 1);
8434 assert_eq!(route.get_total_amount(), amt_msat);
8435 assert_eq!(route.get_total_fees(), 0);
8436 assert_eq!(route.paths[0].hops.len(), 1);
8438 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8442 #[cfg(all(any(test, ldk_bench), feature = "std"))]
8443 pub(crate) mod bench_utils {
8447 use bitcoin::hashes::Hash;
8448 use bitcoin::secp256k1::SecretKey;
8450 use crate::chain::transaction::OutPoint;
8451 use crate::routing::scoring::{ProbabilisticScorer, ScoreUpdate};
8452 use crate::ln::channel_state::{ChannelCounterparty, ChannelShutdownState};
8453 use crate::ln::channelmanager;
8454 use crate::ln::types::ChannelId;
8455 use crate::util::config::UserConfig;
8456 use crate::util::test_utils::TestLogger;
8457 use crate::sync::Arc;
8459 /// Tries to open a network graph file, or panics with a URL to fetch it.
8460 pub(crate) fn get_graph_scorer_file() -> Result<(std::fs::File, std::fs::File), &'static str> {
8461 let load_file = |fname, err_str| {
8462 File::open(fname) // By default we're run in RL/lightning
8463 .or_else(|_| File::open(&format!("lightning/{}", fname))) // We may be run manually in RL/
8464 .or_else(|_| { // Fall back to guessing based on the binary location
8465 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8466 let mut path = std::env::current_exe().unwrap();
8467 path.pop(); // lightning-...
8469 path.pop(); // debug
8470 path.pop(); // target
8471 path.push("lightning");
8475 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8476 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8477 let mut path = std::env::current_exe().unwrap();
8478 path.pop(); // bench...
8480 path.pop(); // debug
8481 path.pop(); // target
8482 path.pop(); // bench
8483 path.push("lightning");
8487 .map_err(|_| err_str)
8489 let graph_res = load_file(
8490 "net_graph-2023-12-10.bin",
8491 "Please fetch https://bitcoin.ninja/ldk-net_graph-v0.0.118-2023-12-10.bin and place it at lightning/net_graph-2023-12-10.bin"
8493 let scorer_res = load_file(
8494 "scorer-2023-12-10.bin",
8495 "Please fetch https://bitcoin.ninja/ldk-scorer-v0.0.118-2023-12-10.bin and place it at lightning/scorer-2023-12-10.bin"
8497 #[cfg(require_route_graph_test)]
8498 return Ok((graph_res.unwrap(), scorer_res.unwrap()));
8499 #[cfg(not(require_route_graph_test))]
8500 return Ok((graph_res?, scorer_res?));
8503 pub(crate) fn read_graph_scorer(logger: &TestLogger)
8504 -> Result<(Arc<NetworkGraph<&TestLogger>>, ProbabilisticScorer<Arc<NetworkGraph<&TestLogger>>, &TestLogger>), &'static str> {
8505 let (mut graph_file, mut scorer_file) = get_graph_scorer_file()?;
8506 let graph = Arc::new(NetworkGraph::read(&mut graph_file, logger).unwrap());
8507 let scorer_args = (Default::default(), Arc::clone(&graph), logger);
8508 let scorer = ProbabilisticScorer::read(&mut scorer_file, scorer_args).unwrap();
8512 pub(crate) fn payer_pubkey() -> PublicKey {
8513 let secp_ctx = Secp256k1::new();
8514 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8518 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8520 channel_id: ChannelId::new_zero(),
8521 counterparty: ChannelCounterparty {
8522 features: channelmanager::provided_init_features(&UserConfig::default()),
8524 unspendable_punishment_reserve: 0,
8525 forwarding_info: None,
8526 outbound_htlc_minimum_msat: None,
8527 outbound_htlc_maximum_msat: None,
8529 funding_txo: Some(OutPoint {
8530 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8533 short_channel_id: Some(1),
8534 inbound_scid_alias: None,
8535 outbound_scid_alias: None,
8536 channel_value_satoshis: 10_000_000_000,
8538 balance_msat: 10_000_000_000,
8539 outbound_capacity_msat: 10_000_000_000,
8540 next_outbound_htlc_minimum_msat: 0,
8541 next_outbound_htlc_limit_msat: 10_000_000_000,
8542 inbound_capacity_msat: 0,
8543 unspendable_punishment_reserve: None,
8544 confirmations_required: None,
8545 confirmations: None,
8546 force_close_spend_delay: None,
8548 is_channel_ready: true,
8551 inbound_htlc_minimum_msat: None,
8552 inbound_htlc_maximum_msat: None,
8554 feerate_sat_per_1000_weight: None,
8555 channel_shutdown_state: Some(ChannelShutdownState::NotShuttingDown),
8556 pending_inbound_htlcs: Vec::new(),
8557 pending_outbound_htlcs: Vec::new(),
8561 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8562 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8563 starting_amount: u64, route_count: usize,
8564 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8565 let payer = payer_pubkey();
8566 let random_seed_bytes = [42; 32];
8568 let nodes = graph.read_only().nodes().clone();
8569 let mut route_endpoints = Vec::new();
8570 for _ in 0..route_count {
8572 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8573 let src = PublicKey::from_slice(nodes.unordered_keys()
8574 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8575 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8576 let dst = PublicKey::from_slice(nodes.unordered_keys()
8577 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8578 let params = PaymentParameters::from_node_id(dst, 42)
8579 .with_bolt11_features(features.clone()).unwrap();
8580 let first_hop = first_hop(src);
8581 let amt_msat = starting_amount + seed % 1_000_000;
8582 let route_params = RouteParameters::from_payment_params_and_value(
8583 params.clone(), amt_msat);
8585 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8586 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8588 route_endpoints.push((first_hop, params, amt_msat));
8601 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8602 use crate::ln::channelmanager;
8603 use crate::ln::features::Bolt11InvoiceFeatures;
8604 use crate::routing::gossip::NetworkGraph;
8605 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScoringFeeParameters};
8606 use crate::util::config::UserConfig;
8607 use crate::util::logger::{Logger, Record};
8608 use crate::util::test_utils::TestLogger;
8610 use criterion::Criterion;
8612 struct DummyLogger {}
8613 impl Logger for DummyLogger {
8614 fn log(&self, _record: Record) {}
8617 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8618 let logger = TestLogger::new();
8619 let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap();
8620 let scorer = FixedPenaltyScorer::with_penalty(0);
8621 generate_routes(bench, &network_graph, scorer, &Default::default(),
8622 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8625 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8626 let logger = TestLogger::new();
8627 let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap();
8628 let scorer = FixedPenaltyScorer::with_penalty(0);
8629 generate_routes(bench, &network_graph, scorer, &Default::default(),
8630 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8631 "generate_mpp_routes_with_zero_penalty_scorer");
8634 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8635 let logger = TestLogger::new();
8636 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8637 let params = ProbabilisticScoringFeeParameters::default();
8638 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8639 "generate_routes_with_probabilistic_scorer");
8642 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8643 let logger = TestLogger::new();
8644 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8645 let params = ProbabilisticScoringFeeParameters::default();
8646 generate_routes(bench, &network_graph, scorer, ¶ms,
8647 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8648 "generate_mpp_routes_with_probabilistic_scorer");
8651 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8652 let logger = TestLogger::new();
8653 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8654 let params = ProbabilisticScoringFeeParameters::default();
8655 generate_routes(bench, &network_graph, scorer, ¶ms,
8656 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8657 "generate_large_mpp_routes_with_probabilistic_scorer");
8660 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8661 let logger = TestLogger::new();
8662 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8663 let mut params = ProbabilisticScoringFeeParameters::default();
8664 params.linear_success_probability = false;
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, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8673 let mut params = ProbabilisticScoringFeeParameters::default();
8674 params.linear_success_probability = false;
8675 generate_routes(bench, &network_graph, scorer, ¶ms,
8676 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8677 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8680 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8681 let logger = TestLogger::new();
8682 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8683 let mut params = ProbabilisticScoringFeeParameters::default();
8684 params.linear_success_probability = false;
8685 generate_routes(bench, &network_graph, scorer, ¶ms,
8686 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8687 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8690 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8691 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8692 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8693 bench_name: &'static str,
8695 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8696 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8698 // ...then benchmark finding paths between the nodes we learned.
8699 do_route_bench(bench, graph, scorer, score_params, bench_name, route_endpoints);
8703 fn do_route_bench<S: ScoreLookUp + ScoreUpdate>(
8704 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, scorer: S,
8705 score_params: &S::ScoreParams, bench_name: &'static str,
8706 route_endpoints: Vec<(ChannelDetails, PaymentParameters, u64)>,
8708 let payer = bench_utils::payer_pubkey();
8709 let random_seed_bytes = [42; 32];
8712 bench.bench_function(bench_name, |b| b.iter(|| {
8713 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8714 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8715 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8716 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());