1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The router finds paths within a [`NetworkGraph`] for a payment.
12 use bitcoin::secp256k1::{PublicKey, Secp256k1, self};
14 use crate::blinded_path::{BlindedHop, BlindedPath, Direction, IntroductionNode};
15 use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, PaymentConstraints, PaymentRelay, ReceiveTlvs};
16 use crate::ln::PaymentHash;
17 use crate::ln::channelmanager::{ChannelDetails, PaymentId, MIN_FINAL_CLTV_EXPIRY_DELTA};
18 use crate::ln::features::{BlindedHopFeatures, Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
19 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice};
21 use crate::onion_message::messenger::{DefaultMessageRouter, Destination, MessageRouter, OnionMessagePath};
22 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
23 use crate::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp};
24 use crate::sign::EntropySource;
25 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
26 use crate::util::logger::{Level, Logger};
27 use crate::crypto::chacha20::ChaCha20;
30 use crate::prelude::*;
31 use alloc::collections::BinaryHeap;
35 /// A [`Router`] implemented using [`find_route`].
36 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> where
38 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
39 ES::Target: EntropySource,
46 message_router: DefaultMessageRouter<G, L, ES>,
49 impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref + Clone, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> DefaultRouter<G, L, ES, S, SP, Sc> where
51 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
52 ES::Target: EntropySource,
54 /// Creates a new router.
55 pub fn new(network_graph: G, logger: L, entropy_source: ES, scorer: S, score_params: SP) -> Self {
56 let message_router = DefaultMessageRouter::new(network_graph.clone(), entropy_source.clone());
57 Self { network_graph, logger, entropy_source, scorer, score_params, message_router }
61 impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> Router for DefaultRouter<G, L, ES, S, SP, Sc> where
63 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
64 ES::Target: EntropySource,
69 params: &RouteParameters,
70 first_hops: Option<&[&ChannelDetails]>,
71 inflight_htlcs: InFlightHtlcs
72 ) -> Result<Route, LightningError> {
73 let random_seed_bytes = self.entropy_source.get_secure_random_bytes();
75 payer, params, &self.network_graph, first_hops, &*self.logger,
76 &ScorerAccountingForInFlightHtlcs::new(self.scorer.read_lock(), &inflight_htlcs),
82 fn create_blinded_payment_paths<
83 T: secp256k1::Signing + secp256k1::Verification
85 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
86 amount_msats: u64, secp_ctx: &Secp256k1<T>
87 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
88 // Limit the number of blinded paths that are computed.
89 const MAX_PAYMENT_PATHS: usize = 3;
91 // Ensure peers have at least three channels so that it is more difficult to infer the
92 // recipient's node_id.
93 const MIN_PEER_CHANNELS: usize = 3;
95 let network_graph = self.network_graph.deref().read_only();
96 let paths = first_hops.into_iter()
97 .filter(|details| details.counterparty.features.supports_route_blinding())
98 .filter(|details| amount_msats <= details.inbound_capacity_msat)
99 .filter(|details| amount_msats >= details.inbound_htlc_minimum_msat.unwrap_or(0))
100 .filter(|details| amount_msats <= details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX))
101 .filter(|details| network_graph
102 .node(&NodeId::from_pubkey(&details.counterparty.node_id))
103 .map(|node_info| node_info.channels.len() >= MIN_PEER_CHANNELS)
106 .filter_map(|details| {
107 let short_channel_id = match details.get_inbound_payment_scid() {
108 Some(short_channel_id) => short_channel_id,
111 let payment_relay: PaymentRelay = match details.counterparty.forwarding_info {
112 Some(forwarding_info) => match forwarding_info.try_into() {
113 Ok(payment_relay) => payment_relay,
114 Err(()) => return None,
119 let cltv_expiry_delta = payment_relay.cltv_expiry_delta as u32;
120 let payment_constraints = PaymentConstraints {
121 max_cltv_expiry: tlvs.payment_constraints.max_cltv_expiry + cltv_expiry_delta,
122 htlc_minimum_msat: details.inbound_htlc_minimum_msat.unwrap_or(0),
129 features: BlindedHopFeatures::empty(),
131 node_id: details.counterparty.node_id,
132 htlc_maximum_msat: details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX),
135 .map(|forward_node| {
136 BlindedPath::new_for_payment(
137 &[forward_node], recipient, tlvs.clone(), u64::MAX, MIN_FINAL_CLTV_EXPIRY_DELTA,
138 &*self.entropy_source, secp_ctx
141 .take(MAX_PAYMENT_PATHS)
142 .collect::<Result<Vec<_>, _>>();
145 Ok(paths) if !paths.is_empty() => Ok(paths),
147 if network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient)) {
148 BlindedPath::one_hop_for_payment(
149 recipient, tlvs, MIN_FINAL_CLTV_EXPIRY_DELTA, &*self.entropy_source, secp_ctx
150 ).map(|path| vec![path])
159 impl< G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> MessageRouter for DefaultRouter<G, L, ES, S, SP, Sc> where
161 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
162 ES::Target: EntropySource,
165 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
166 ) -> Result<OnionMessagePath, ()> {
167 self.message_router.find_path(sender, peers, destination)
170 fn create_blinded_paths<
171 T: secp256k1::Signing + secp256k1::Verification
173 &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
174 ) -> Result<Vec<BlindedPath>, ()> {
175 self.message_router.create_blinded_paths(recipient, peers, secp_ctx)
179 /// A trait defining behavior for routing a payment.
180 pub trait Router: MessageRouter {
181 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
183 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
184 /// and [`RouteParameters::final_value_msat`], respectively.
186 &self, payer: &PublicKey, route_params: &RouteParameters,
187 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
188 ) -> Result<Route, LightningError>;
190 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
192 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
193 /// and [`RouteParameters::final_value_msat`], respectively.
195 /// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
197 fn find_route_with_id(
198 &self, payer: &PublicKey, route_params: &RouteParameters,
199 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
200 _payment_hash: PaymentHash, _payment_id: PaymentId
201 ) -> Result<Route, LightningError> {
202 self.find_route(payer, route_params, first_hops, inflight_htlcs)
205 /// Creates [`BlindedPath`]s for payment to the `recipient` node. The channels in `first_hops`
206 /// are assumed to be with the `recipient`'s peers. The payment secret and any constraints are
208 fn create_blinded_payment_paths<
209 T: secp256k1::Signing + secp256k1::Verification
211 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
212 amount_msats: u64, secp_ctx: &Secp256k1<T>
213 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()>;
216 /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
218 /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
221 /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
222 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> where S::Target: ScoreLookUp {
224 // Maps a channel's short channel id and its direction to the liquidity used up.
225 inflight_htlcs: &'a InFlightHtlcs,
227 impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
228 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
229 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
230 ScorerAccountingForInFlightHtlcs {
237 impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
238 type ScoreParams = <S::Target as ScoreLookUp>::ScoreParams;
239 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
240 let target = match candidate.target() {
241 Some(target) => target,
242 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
244 let short_channel_id = match candidate.short_channel_id() {
245 Some(short_channel_id) => short_channel_id,
246 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
248 let source = candidate.source();
249 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
250 &source, &target, short_channel_id
252 let usage = ChannelUsage {
253 inflight_htlc_msat: usage.inflight_htlc_msat.saturating_add(used_liquidity),
257 self.scorer.channel_penalty_msat(candidate, usage, score_params)
259 self.scorer.channel_penalty_msat(candidate, usage, score_params)
264 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
265 /// in-use channel liquidity.
267 pub struct InFlightHtlcs(
268 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
269 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
270 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
272 HashMap<(u64, bool), u64>
276 /// Constructs an empty `InFlightHtlcs`.
277 pub fn new() -> Self { InFlightHtlcs(new_hash_map()) }
279 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
280 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
281 if path.hops.is_empty() { return };
283 let mut cumulative_msat = 0;
284 if let Some(tail) = &path.blinded_tail {
285 cumulative_msat += tail.final_value_msat;
288 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
289 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
290 // the router excludes the payer node. In the following lines, the payer's information is
291 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
292 // in our sliding window of two.
293 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
294 .map(|hop| hop.pubkey)
295 .chain(core::iter::once(payer_node_id));
297 // Taking the reversed vector from above, we zip it with just the reversed hops list to
298 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
299 // the total amount sent.
300 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
301 cumulative_msat += next_hop.fee_msat;
303 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
304 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
305 .or_insert(cumulative_msat);
309 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
311 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
313 .entry((channel_scid, source < target))
314 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
315 .or_insert(used_msat);
318 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
320 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
321 self.0.get(&(channel_scid, source < target)).map(|v| *v)
325 impl Writeable for InFlightHtlcs {
326 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
329 impl Readable for InFlightHtlcs {
330 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
331 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
332 Ok(Self(infight_map))
336 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
337 /// that leads to it.
338 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
339 pub struct RouteHop {
340 /// The node_id of the node at this hop.
341 pub pubkey: PublicKey,
342 /// The node_announcement features of the node at this hop. For the last hop, these may be
343 /// amended to match the features present in the invoice this node generated.
344 pub node_features: NodeFeatures,
345 /// The channel that should be used from the previous hop to reach this node.
346 pub short_channel_id: u64,
347 /// The channel_announcement features of the channel that should be used from the previous hop
348 /// to reach this node.
349 pub channel_features: ChannelFeatures,
350 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
351 /// If this is the last hop in [`Path::hops`]:
352 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
353 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
355 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
357 /// The CLTV delta added for this hop.
358 /// If this is the last hop in [`Path::hops`]:
359 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
360 /// * otherwise, this is the CLTV delta expected at the destination
362 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
363 pub cltv_expiry_delta: u32,
364 /// Indicates whether this hop is possibly announced in the public network graph.
366 /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
367 /// either know for sure it's announced in the public graph, or if any public channels exist
368 /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
369 /// the channel to be unannounced.
371 /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
372 pub maybe_announced_channel: bool,
375 impl_writeable_tlv_based!(RouteHop, {
376 (0, pubkey, required),
377 (1, maybe_announced_channel, (default_value, true)),
378 (2, node_features, required),
379 (4, short_channel_id, required),
380 (6, channel_features, required),
381 (8, fee_msat, required),
382 (10, cltv_expiry_delta, required),
385 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
386 /// their [`Bolt12Invoice`].
388 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
389 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
390 pub struct BlindedTail {
391 /// The hops of the [`BlindedPath`] provided by the recipient.
393 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
394 pub hops: Vec<BlindedHop>,
395 /// The blinding point of the [`BlindedPath`] provided by the recipient.
397 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
398 pub blinding_point: PublicKey,
399 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
400 /// inferring the destination. May be 0.
401 pub excess_final_cltv_expiry_delta: u32,
402 /// The total amount paid on this [`Path`], excluding the fees.
403 pub final_value_msat: u64,
406 impl_writeable_tlv_based!(BlindedTail, {
407 (0, hops, required_vec),
408 (2, blinding_point, required),
409 (4, excess_final_cltv_expiry_delta, required),
410 (6, final_value_msat, required),
413 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
414 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
415 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
417 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
418 pub hops: Vec<RouteHop>,
419 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
420 pub blinded_tail: Option<BlindedTail>,
424 /// Gets the fees for a given path, excluding any excess paid to the recipient.
425 pub fn fee_msat(&self) -> u64 {
426 match &self.blinded_tail {
427 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
429 // Do not count last hop of each path since that's the full value of the payment
430 self.hops.split_last().map_or(0,
431 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
436 /// Gets the total amount paid on this [`Path`], excluding the fees.
437 pub fn final_value_msat(&self) -> u64 {
438 match &self.blinded_tail {
439 Some(blinded_tail) => blinded_tail.final_value_msat,
440 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
444 /// Gets the final hop's CLTV expiry delta.
445 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
446 match &self.blinded_tail {
448 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
453 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
454 /// it can take multiple paths. Each path is composed of one or more hops through the network.
455 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
457 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
458 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
460 pub paths: Vec<Path>,
461 /// The `route_params` parameter passed to [`find_route`].
463 /// This is used by `ChannelManager` to track information which may be required for retries.
465 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
466 pub route_params: Option<RouteParameters>,
470 /// Returns the total amount of fees paid on this [`Route`].
472 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
473 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
474 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
476 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
477 pub fn get_total_fees(&self) -> u64 {
478 let overpaid_value_msat = self.route_params.as_ref()
479 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
480 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
483 /// Returns the total amount paid on this [`Route`], excluding the fees.
485 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
486 /// we had to reach the [`htlc_minimum_msat`] limits.
488 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
489 pub fn get_total_amount(&self) -> u64 {
490 self.paths.iter().map(|path| path.final_value_msat()).sum()
494 impl fmt::Display for Route {
495 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
496 log_route!(self).fmt(f)
500 const SERIALIZATION_VERSION: u8 = 1;
501 const MIN_SERIALIZATION_VERSION: u8 = 1;
503 impl Writeable for Route {
504 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
505 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
506 (self.paths.len() as u64).write(writer)?;
507 let mut blinded_tails = Vec::new();
508 for (idx, path) in self.paths.iter().enumerate() {
509 (path.hops.len() as u8).write(writer)?;
510 for hop in path.hops.iter() {
513 if let Some(blinded_tail) = &path.blinded_tail {
514 if blinded_tails.is_empty() {
515 blinded_tails = Vec::with_capacity(path.hops.len());
517 blinded_tails.push(None);
520 blinded_tails.push(Some(blinded_tail));
521 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
523 write_tlv_fields!(writer, {
524 // For compatibility with LDK versions prior to 0.0.117, we take the individual
525 // RouteParameters' fields and reconstruct them on read.
526 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
527 (2, blinded_tails, optional_vec),
528 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
529 (5, self.route_params.as_ref().and_then(|p| p.max_total_routing_fee_msat), option),
535 impl Readable for Route {
536 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
537 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
538 let path_count: u64 = Readable::read(reader)?;
539 if path_count == 0 { return Err(DecodeError::InvalidValue); }
540 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
541 let mut min_final_cltv_expiry_delta = u32::max_value();
542 for _ in 0..path_count {
543 let hop_count: u8 = Readable::read(reader)?;
544 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
545 for _ in 0..hop_count {
546 hops.push(Readable::read(reader)?);
548 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
549 min_final_cltv_expiry_delta =
550 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
551 paths.push(Path { hops, blinded_tail: None });
553 _init_and_read_len_prefixed_tlv_fields!(reader, {
554 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
555 (2, blinded_tails, optional_vec),
556 (3, final_value_msat, option),
557 (5, max_total_routing_fee_msat, option)
559 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
560 if blinded_tails.len() != 0 {
561 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
562 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
563 path.blinded_tail = blinded_tail_opt;
567 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
568 let route_params = match (payment_params, final_value_msat) {
569 (Some(payment_params), Some(final_value_msat)) => {
570 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
575 Ok(Route { paths, route_params })
579 /// Parameters needed to find a [`Route`].
581 /// Passed to [`find_route`] and [`build_route_from_hops`].
582 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
583 pub struct RouteParameters {
584 /// The parameters of the failed payment path.
585 pub payment_params: PaymentParameters,
587 /// The amount in msats sent on the failed payment path.
588 pub final_value_msat: u64,
590 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
592 /// This limit also applies to the total fees that may arise while retrying failed payment
595 /// Note that values below a few sats may result in some paths being spuriously ignored.
596 pub max_total_routing_fee_msat: Option<u64>,
599 impl RouteParameters {
600 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
602 /// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
603 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
604 Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
608 impl Writeable for RouteParameters {
609 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
610 write_tlv_fields!(writer, {
611 (0, self.payment_params, required),
612 (1, self.max_total_routing_fee_msat, option),
613 (2, self.final_value_msat, required),
614 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
615 // `RouteParameters` directly. For compatibility, we write it here.
616 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
622 impl Readable for RouteParameters {
623 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
624 _init_and_read_len_prefixed_tlv_fields!(reader, {
625 (0, payment_params, (required: ReadableArgs, 0)),
626 (1, max_total_routing_fee_msat, option),
627 (2, final_value_msat, required),
628 (4, final_cltv_delta, option),
630 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
631 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
632 if final_cltv_expiry_delta == &0 {
633 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
638 final_value_msat: final_value_msat.0.unwrap(),
639 max_total_routing_fee_msat,
644 /// Maximum total CTLV difference we allow for a full payment path.
645 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
647 /// Maximum number of paths we allow an (MPP) payment to have.
648 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
649 // limits, but for now more than 10 paths likely carries too much one-path failure.
650 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
652 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
654 // The median hop CLTV expiry delta currently seen in the network.
655 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
657 // During routing, we only consider paths shorter than our maximum length estimate.
658 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
659 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
660 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
662 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
663 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
664 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
665 // (payment_secret and total_msat) = 93 bytes for the final hop.
666 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
667 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
668 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
670 /// Information used to route a payment.
671 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
672 pub struct PaymentParameters {
673 /// Information about the payee, such as their features and route hints for their channels.
676 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
677 pub expiry_time: Option<u64>,
679 /// The maximum total CLTV delta we accept for the route.
680 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
681 pub max_total_cltv_expiry_delta: u32,
683 /// The maximum number of paths that may be used by (MPP) payments.
684 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
685 pub max_path_count: u8,
687 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
688 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
689 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
690 /// increasing failure probability for those paths.
692 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
693 /// restriction have been found. While paths which meet this criteria will be searched for, it
694 /// is ultimately up to the scorer to select them over other paths.
696 /// A value of 0 will allow payments up to and including a channel's total announced usable
697 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
700 pub max_channel_saturation_power_of_half: u8,
702 /// A list of SCIDs which this payment was previously attempted over and which caused the
703 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
705 pub previously_failed_channels: Vec<u64>,
707 /// A list of indices corresponding to blinded paths in [`Payee::Blinded::route_hints`] which this
708 /// payment was previously attempted over and which caused the payment to fail. Future attempts
709 /// for the same payment shouldn't be relayed through any of these blinded paths.
710 pub previously_failed_blinded_path_idxs: Vec<u64>,
713 impl Writeable for PaymentParameters {
714 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
715 let mut clear_hints = &vec![];
716 let mut blinded_hints = &vec![];
718 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
719 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
721 write_tlv_fields!(writer, {
722 (0, self.payee.node_id(), option),
723 (1, self.max_total_cltv_expiry_delta, required),
724 (2, self.payee.features(), option),
725 (3, self.max_path_count, required),
726 (4, *clear_hints, required_vec),
727 (5, self.max_channel_saturation_power_of_half, required),
728 (6, self.expiry_time, option),
729 (7, self.previously_failed_channels, required_vec),
730 (8, *blinded_hints, optional_vec),
731 (9, self.payee.final_cltv_expiry_delta(), option),
732 (11, self.previously_failed_blinded_path_idxs, required_vec),
738 impl ReadableArgs<u32> for PaymentParameters {
739 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
740 _init_and_read_len_prefixed_tlv_fields!(reader, {
741 (0, payee_pubkey, option),
742 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
743 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
744 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
745 (4, clear_route_hints, required_vec),
746 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
747 (6, expiry_time, option),
748 (7, previously_failed_channels, optional_vec),
749 (8, blinded_route_hints, optional_vec),
750 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
751 (11, previously_failed_blinded_path_idxs, optional_vec),
753 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
754 let payee = if blinded_route_hints.len() != 0 {
755 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
757 route_hints: blinded_route_hints,
758 features: features.and_then(|f: Features| f.bolt12()),
762 route_hints: clear_route_hints,
763 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
764 features: features.and_then(|f| f.bolt11()),
765 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
769 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
770 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
772 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
774 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
775 previously_failed_blinded_path_idxs: previously_failed_blinded_path_idxs.unwrap_or(Vec::new()),
781 impl PaymentParameters {
782 /// Creates a payee with the node id of the given `pubkey`.
784 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
786 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
788 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
790 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
791 max_path_count: DEFAULT_MAX_PATH_COUNT,
792 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
793 previously_failed_channels: Vec::new(),
794 previously_failed_blinded_path_idxs: Vec::new(),
798 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
800 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
803 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
804 /// whether your router will be allowed to find a multi-part route for this payment. If you
805 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
806 /// [`RecipientOnionFields::secret_only`].
808 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
809 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
810 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
811 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
812 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
815 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
816 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
817 /// [`PaymentParameters::expiry_time`].
818 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
819 Self::blinded(invoice.payment_paths().to_vec())
820 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
821 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
824 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
825 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
827 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
829 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
830 max_path_count: DEFAULT_MAX_PATH_COUNT,
831 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
832 previously_failed_channels: Vec::new(),
833 previously_failed_blinded_path_idxs: Vec::new(),
837 /// Includes the payee's features. Errors if the parameters were not initialized with
838 /// [`PaymentParameters::from_bolt12_invoice`].
840 /// This is not exported to bindings users since bindings don't support move semantics
841 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
843 Payee::Clear { .. } => Err(()),
844 Payee::Blinded { route_hints, .. } =>
845 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
849 /// Includes the payee's features. Errors if the parameters were initialized with
850 /// [`PaymentParameters::from_bolt12_invoice`].
852 /// This is not exported to bindings users since bindings don't support move semantics
853 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
855 Payee::Blinded { .. } => Err(()),
856 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
858 payee: Payee::Clear {
859 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
865 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
866 /// [`PaymentParameters::from_bolt12_invoice`].
868 /// This is not exported to bindings users since bindings don't support move semantics
869 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
871 Payee::Blinded { .. } => Err(()),
872 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
874 payee: Payee::Clear {
875 route_hints, node_id, features, final_cltv_expiry_delta,
881 /// Includes a payment expiration in seconds relative to the UNIX epoch.
883 /// This is not exported to bindings users since bindings don't support move semantics
884 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
885 Self { expiry_time: Some(expiry_time), ..self }
888 /// Includes a limit for the total CLTV expiry delta which is considered during routing
890 /// This is not exported to bindings users since bindings don't support move semantics
891 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
892 Self { max_total_cltv_expiry_delta, ..self }
895 /// Includes a limit for the maximum number of payment paths that may be used.
897 /// This is not exported to bindings users since bindings don't support move semantics
898 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
899 Self { max_path_count, ..self }
902 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
903 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
905 /// This is not exported to bindings users since bindings don't support move semantics
906 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
907 Self { max_channel_saturation_power_of_half, ..self }
910 pub(crate) fn insert_previously_failed_blinded_path(&mut self, failed_blinded_tail: &BlindedTail) {
911 let mut found_blinded_tail = false;
912 for (idx, (_, path)) in self.payee.blinded_route_hints().iter().enumerate() {
913 if failed_blinded_tail.hops == path.blinded_hops &&
914 failed_blinded_tail.blinding_point == path.blinding_point
916 self.previously_failed_blinded_path_idxs.push(idx as u64);
917 found_blinded_tail = true;
920 debug_assert!(found_blinded_tail);
924 /// The recipient of a payment, differing based on whether they've hidden their identity with route
926 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
928 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
929 /// will be included in the final [`Route`].
931 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
933 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
934 /// Features supported by the payee.
936 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
938 features: Option<Bolt12InvoiceFeatures>,
940 /// The recipient included these route hints in their BOLT11 invoice.
942 /// The node id of the payee.
944 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
945 route_hints: Vec<RouteHint>,
946 /// Features supported by the payee.
948 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
949 /// does not contain any features.
951 /// [`for_keysend`]: PaymentParameters::for_keysend
952 features: Option<Bolt11InvoiceFeatures>,
953 /// The minimum CLTV delta at the end of the route. This value must not be zero.
954 final_cltv_expiry_delta: u32,
959 fn node_id(&self) -> Option<PublicKey> {
961 Self::Clear { node_id, .. } => Some(*node_id),
965 fn node_features(&self) -> Option<NodeFeatures> {
967 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
968 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
971 fn supports_basic_mpp(&self) -> bool {
973 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
974 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
977 fn features(&self) -> Option<FeaturesRef> {
979 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
980 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
983 fn final_cltv_expiry_delta(&self) -> Option<u32> {
985 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
989 pub(crate) fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
991 Self::Blinded { route_hints, .. } => &route_hints[..],
992 Self::Clear { .. } => &[]
996 fn unblinded_route_hints(&self) -> &[RouteHint] {
998 Self::Blinded { .. } => &[],
999 Self::Clear { route_hints, .. } => &route_hints[..]
1004 enum FeaturesRef<'a> {
1005 Bolt11(&'a Bolt11InvoiceFeatures),
1006 Bolt12(&'a Bolt12InvoiceFeatures),
1009 Bolt11(Bolt11InvoiceFeatures),
1010 Bolt12(Bolt12InvoiceFeatures),
1014 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
1016 Self::Bolt12(f) => Some(f),
1020 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
1022 Self::Bolt11(f) => Some(f),
1028 impl<'a> Writeable for FeaturesRef<'a> {
1029 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1031 Self::Bolt11(f) => Ok(f.write(w)?),
1032 Self::Bolt12(f) => Ok(f.write(w)?),
1037 impl ReadableArgs<bool> for Features {
1038 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
1039 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
1040 Ok(Self::Bolt12(Readable::read(reader)?))
1044 /// A list of hops along a payment path terminating with a channel to the recipient.
1045 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1046 pub struct RouteHint(pub Vec<RouteHintHop>);
1048 impl Writeable for RouteHint {
1049 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1050 (self.0.len() as u64).write(writer)?;
1051 for hop in self.0.iter() {
1058 impl Readable for RouteHint {
1059 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1060 let hop_count: u64 = Readable::read(reader)?;
1061 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
1062 for _ in 0..hop_count {
1063 hops.push(Readable::read(reader)?);
1069 /// A channel descriptor for a hop along a payment path.
1071 /// While this generally comes from BOLT 11's `r` field, this struct includes more fields than are
1072 /// available in BOLT 11. Thus, encoding and decoding this via `lightning-invoice` is lossy, as
1073 /// fields not supported in BOLT 11 will be stripped.
1074 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1075 pub struct RouteHintHop {
1076 /// The node_id of the non-target end of the route
1077 pub src_node_id: PublicKey,
1078 /// The short_channel_id of this channel
1079 pub short_channel_id: u64,
1080 /// The fees which must be paid to use this channel
1081 pub fees: RoutingFees,
1082 /// The difference in CLTV values between this node and the next node.
1083 pub cltv_expiry_delta: u16,
1084 /// The minimum value, in msat, which must be relayed to the next hop.
1085 pub htlc_minimum_msat: Option<u64>,
1086 /// The maximum value in msat available for routing with a single HTLC.
1087 pub htlc_maximum_msat: Option<u64>,
1090 impl_writeable_tlv_based!(RouteHintHop, {
1091 (0, src_node_id, required),
1092 (1, htlc_minimum_msat, option),
1093 (2, short_channel_id, required),
1094 (3, htlc_maximum_msat, option),
1095 (4, fees, required),
1096 (6, cltv_expiry_delta, required),
1099 #[derive(Eq, PartialEq)]
1100 #[repr(align(64))] // Force the size to 64 bytes
1101 struct RouteGraphNode {
1104 // The maximum value a yet-to-be-constructed payment path might flow through this node.
1105 // This value is upper-bounded by us by:
1106 // - how much is needed for a path being constructed
1107 // - how much value can channels following this node (up to the destination) can contribute,
1108 // considering their capacity and fees
1109 value_contribution_msat: u64,
1110 total_cltv_delta: u32,
1111 /// The number of hops walked up to this node.
1112 path_length_to_node: u8,
1115 impl cmp::Ord for RouteGraphNode {
1116 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
1117 other.score.cmp(&self.score).then_with(|| other.node_id.cmp(&self.node_id))
1121 impl cmp::PartialOrd for RouteGraphNode {
1122 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
1123 Some(self.cmp(other))
1127 // While RouteGraphNode can be laid out with fewer bytes, performance appears to be improved
1128 // substantially when it is laid out at exactly 64 bytes.
1130 // Thus, we use `#[repr(C)]` on the struct to force a suboptimal layout and check that it stays 64
1132 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1133 const _GRAPH_NODE_SMALL: usize = 64 - core::mem::size_of::<RouteGraphNode>();
1134 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1135 const _GRAPH_NODE_FIXED_SIZE: usize = core::mem::size_of::<RouteGraphNode>() - 64;
1137 /// A [`CandidateRouteHop::FirstHop`] entry.
1138 #[derive(Clone, Debug)]
1139 pub struct FirstHopCandidate<'a> {
1140 /// Channel details of the first hop
1142 /// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1143 /// has been funded and is able to pay), and accessor methods may panic otherwise.
1145 /// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1147 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1148 pub details: &'a ChannelDetails,
1149 /// The node id of the payer, which is also the source side of this candidate route hop.
1151 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1152 pub payer_node_id: &'a NodeId,
1155 /// A [`CandidateRouteHop::PublicHop`] entry.
1156 #[derive(Clone, Debug)]
1157 pub struct PublicHopCandidate<'a> {
1158 /// Information about the channel, including potentially its capacity and
1159 /// direction-specific information.
1161 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1162 pub info: DirectedChannelInfo<'a>,
1163 /// The short channel ID of the channel, i.e. the identifier by which we refer to this
1165 pub short_channel_id: u64,
1168 /// A [`CandidateRouteHop::PrivateHop`] entry.
1169 #[derive(Clone, Debug)]
1170 pub struct PrivateHopCandidate<'a> {
1171 /// Information about the private hop communicated via BOLT 11.
1173 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1174 pub hint: &'a RouteHintHop,
1175 /// Node id of the next hop in BOLT 11 route hint.
1177 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1178 pub target_node_id: &'a NodeId
1181 /// A [`CandidateRouteHop::Blinded`] entry.
1182 #[derive(Clone, Debug)]
1183 pub struct BlindedPathCandidate<'a> {
1184 /// The node id of the introduction node, resolved from either the [`NetworkGraph`] or first
1187 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1188 pub source_node_id: &'a NodeId,
1189 /// Information about the blinded path including the fee, HTLC amount limits, and
1190 /// cryptographic material required to build an HTLC through the given path.
1192 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1193 pub hint: &'a (BlindedPayInfo, BlindedPath),
1194 /// Index of the hint in the original list of blinded hints.
1196 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1197 /// a short channel ID for this hop.
1201 /// A [`CandidateRouteHop::OneHopBlinded`] entry.
1202 #[derive(Clone, Debug)]
1203 pub struct OneHopBlindedPathCandidate<'a> {
1204 /// The node id of the introduction node, resolved from either the [`NetworkGraph`] or first
1207 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1208 pub source_node_id: &'a NodeId,
1209 /// Information about the blinded path including the fee, HTLC amount limits, and
1210 /// cryptographic material required to build an HTLC terminating with the given path.
1212 /// Note that the [`BlindedPayInfo`] is ignored here.
1214 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1215 pub hint: &'a (BlindedPayInfo, BlindedPath),
1216 /// Index of the hint in the original list of blinded hints.
1218 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1219 /// a short channel ID for this hop.
1223 /// A wrapper around the various hop representations.
1225 /// Can be used to examine the properties of a hop,
1226 /// potentially to decide whether to include it in a route.
1227 #[derive(Clone, Debug)]
1228 pub enum CandidateRouteHop<'a> {
1229 /// A hop from the payer, where the outbound liquidity is known.
1230 FirstHop(FirstHopCandidate<'a>),
1231 /// A hop found in the [`ReadOnlyNetworkGraph`].
1232 PublicHop(PublicHopCandidate<'a>),
1233 /// A private hop communicated by the payee, generally via a BOLT 11 invoice.
1235 /// Because BOLT 11 route hints can take multiple hops to get to the destination, this may not
1236 /// terminate at the payee.
1237 PrivateHop(PrivateHopCandidate<'a>),
1238 /// A blinded path which starts with an introduction point and ultimately terminates with the
1241 /// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1242 /// `None` in this state.
1244 /// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1245 /// path, the full path is treated as a single [`CandidateRouteHop`].
1246 Blinded(BlindedPathCandidate<'a>),
1247 /// Similar to [`Self::Blinded`], but the path here only has one hop.
1249 /// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1250 /// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1251 /// payee's identity - it's the introduction point!
1253 /// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1254 /// to the hops *between* the introduction node and the destination.
1256 /// This primarily exists to track that we need to included a blinded path at the end of our
1257 /// [`Route`], even though it doesn't actually add an additional hop in the payment.
1258 OneHopBlinded(OneHopBlindedPathCandidate<'a>),
1261 impl<'a> CandidateRouteHop<'a> {
1262 /// Returns the short channel ID for this hop, if one is known.
1264 /// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1265 /// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1267 /// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1268 /// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1269 /// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1270 /// (which is always true for channels which are funded and ready for use).
1272 /// In other words, this should always return `Some` as long as the candidate hop is not a
1273 /// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1275 /// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1276 /// define a global namespace.
1278 fn short_channel_id(&self) -> Option<u64> {
1280 CandidateRouteHop::FirstHop(hop) => hop.details.get_outbound_payment_scid(),
1281 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1282 CandidateRouteHop::PrivateHop(hop) => Some(hop.hint.short_channel_id),
1283 CandidateRouteHop::Blinded(_) => None,
1284 CandidateRouteHop::OneHopBlinded(_) => None,
1288 /// Returns the globally unique short channel ID for this hop, if one is known.
1290 /// This only returns `Some` if the channel is public (either our own, or one we've learned
1291 /// from the public network graph), and thus the short channel ID we have for this channel is
1292 /// globally unique and identifies this channel in a global namespace.
1294 pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1296 CandidateRouteHop::FirstHop(hop) => if hop.details.is_public { hop.details.short_channel_id } else { None },
1297 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1298 CandidateRouteHop::PrivateHop(_) => None,
1299 CandidateRouteHop::Blinded(_) => None,
1300 CandidateRouteHop::OneHopBlinded(_) => None,
1304 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1305 fn features(&self) -> ChannelFeatures {
1307 CandidateRouteHop::FirstHop(hop) => hop.details.counterparty.features.to_context(),
1308 CandidateRouteHop::PublicHop(hop) => hop.info.channel().features.clone(),
1309 CandidateRouteHop::PrivateHop(_) => ChannelFeatures::empty(),
1310 CandidateRouteHop::Blinded(_) => ChannelFeatures::empty(),
1311 CandidateRouteHop::OneHopBlinded(_) => ChannelFeatures::empty(),
1315 /// Returns the required difference in HTLC CLTV expiry between the [`Self::source`] and the
1316 /// next-hop for an HTLC taking this hop.
1318 /// This is the time that the node(s) in this hop have to claim the HTLC on-chain if the
1319 /// next-hop goes on chain with a payment preimage.
1321 pub fn cltv_expiry_delta(&self) -> u32 {
1323 CandidateRouteHop::FirstHop(_) => 0,
1324 CandidateRouteHop::PublicHop(hop) => hop.info.direction().cltv_expiry_delta as u32,
1325 CandidateRouteHop::PrivateHop(hop) => hop.hint.cltv_expiry_delta as u32,
1326 CandidateRouteHop::Blinded(hop) => hop.hint.0.cltv_expiry_delta as u32,
1327 CandidateRouteHop::OneHopBlinded(_) => 0,
1331 /// Returns the minimum amount that can be sent over this hop, in millisatoshis.
1333 pub fn htlc_minimum_msat(&self) -> u64 {
1335 CandidateRouteHop::FirstHop(hop) => hop.details.next_outbound_htlc_minimum_msat,
1336 CandidateRouteHop::PublicHop(hop) => hop.info.direction().htlc_minimum_msat,
1337 CandidateRouteHop::PrivateHop(hop) => hop.hint.htlc_minimum_msat.unwrap_or(0),
1338 CandidateRouteHop::Blinded(hop) => hop.hint.0.htlc_minimum_msat,
1339 CandidateRouteHop::OneHopBlinded { .. } => 0,
1343 /// Returns the fees that must be paid to route an HTLC over this channel.
1345 pub fn fees(&self) -> RoutingFees {
1347 CandidateRouteHop::FirstHop(_) => RoutingFees {
1348 base_msat: 0, proportional_millionths: 0,
1350 CandidateRouteHop::PublicHop(hop) => hop.info.direction().fees,
1351 CandidateRouteHop::PrivateHop(hop) => hop.hint.fees,
1352 CandidateRouteHop::Blinded(hop) => {
1354 base_msat: hop.hint.0.fee_base_msat,
1355 proportional_millionths: hop.hint.0.fee_proportional_millionths
1358 CandidateRouteHop::OneHopBlinded(_) =>
1359 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1363 /// Fetch the effective capacity of this hop.
1365 /// Note that this may be somewhat expensive, so calls to this should be limited and results
1367 fn effective_capacity(&self) -> EffectiveCapacity {
1369 CandidateRouteHop::FirstHop(hop) => EffectiveCapacity::ExactLiquidity {
1370 liquidity_msat: hop.details.next_outbound_htlc_limit_msat,
1372 CandidateRouteHop::PublicHop(hop) => hop.info.effective_capacity(),
1373 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. }) =>
1374 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1375 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. }) =>
1376 EffectiveCapacity::Infinite,
1377 CandidateRouteHop::Blinded(hop) =>
1378 EffectiveCapacity::HintMaxHTLC { amount_msat: hop.hint.0.htlc_maximum_msat },
1379 CandidateRouteHop::OneHopBlinded(_) => EffectiveCapacity::Infinite,
1383 /// Returns an ID describing the given hop.
1385 /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1387 fn id(&self) -> CandidateHopId {
1389 CandidateRouteHop::Blinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1390 CandidateRouteHop::OneHopBlinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1391 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1394 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1396 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1402 fn blinded_hint_idx(&self) -> Option<usize> {
1404 Self::Blinded(BlindedPathCandidate { hint_idx, .. }) |
1405 Self::OneHopBlinded(OneHopBlindedPathCandidate { hint_idx, .. }) => {
1411 /// Returns the source node id of current hop.
1413 /// Source node id refers to the node forwarding the HTLC through this hop.
1415 /// For [`Self::FirstHop`] we return payer's node id.
1417 pub fn source(&self) -> NodeId {
1419 CandidateRouteHop::FirstHop(hop) => *hop.payer_node_id,
1420 CandidateRouteHop::PublicHop(hop) => *hop.info.source(),
1421 CandidateRouteHop::PrivateHop(hop) => hop.hint.src_node_id.into(),
1422 CandidateRouteHop::Blinded(hop) => *hop.source_node_id,
1423 CandidateRouteHop::OneHopBlinded(hop) => *hop.source_node_id,
1426 /// Returns the target node id of this hop, if known.
1428 /// Target node id refers to the node receiving the HTLC after this hop.
1430 /// For [`Self::Blinded`] we return `None` because the ultimate destination after the blinded
1431 /// path is unknown.
1433 /// For [`Self::OneHopBlinded`] we return `None` because the target is the same as the source,
1434 /// and such a return value would be somewhat nonsensical.
1436 pub fn target(&self) -> Option<NodeId> {
1438 CandidateRouteHop::FirstHop(hop) => Some(hop.details.counterparty.node_id.into()),
1439 CandidateRouteHop::PublicHop(hop) => Some(*hop.info.target()),
1440 CandidateRouteHop::PrivateHop(hop) => Some(*hop.target_node_id),
1441 CandidateRouteHop::Blinded(_) => None,
1442 CandidateRouteHop::OneHopBlinded(_) => None,
1447 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1449 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1451 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1452 /// isn't guaranteed to be unique at all.
1454 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1455 /// difficult-to-use API.
1456 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1457 enum CandidateHopId {
1458 /// Contains (scid, src_node_id < target_node_id)
1460 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1465 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1466 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1468 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1469 EffectiveCapacity::Infinite => u64::max_value(),
1470 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1471 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1472 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1473 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1474 // expected to have been generated from up-to-date capacity information.
1475 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1476 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1477 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1481 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1482 -> bool where I1::Item: PartialEq<I2::Item> {
1484 let a = iter_a.next();
1485 let b = iter_b.next();
1486 if a.is_none() && b.is_none() { return true; }
1487 if a.is_none() || b.is_none() { return false; }
1488 if a.unwrap().ne(&b.unwrap()) { return false; }
1492 /// It's useful to keep track of the hops associated with the fees required to use them,
1493 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1494 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1495 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1497 #[repr(C)] // Force fields to appear in the order we define them.
1498 struct PathBuildingHop<'a> {
1499 candidate: CandidateRouteHop<'a>,
1500 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1501 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1502 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1503 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1504 /// avoid processing them again.
1505 was_processed: bool,
1506 /// Used to compare channels when choosing the for routing.
1507 /// Includes paying for the use of a hop and the following hops, as well as
1508 /// an estimated cost of reaching this hop.
1509 /// Might get stale when fees are recomputed. Primarily for internal use.
1510 total_fee_msat: u64,
1511 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1512 /// walk and may be invalid thereafter.
1513 path_htlc_minimum_msat: u64,
1514 /// All penalties incurred from this channel on the way to the destination, as calculated using
1515 /// channel scoring.
1516 path_penalty_msat: u64,
1518 // The last 16 bytes are on the next cache line by default in glibc's malloc. Thus, we should
1519 // only place fields which are not hot there. Luckily, the next three fields are only read if
1520 // we end up on the selected path, and only in the final path layout phase, so we don't care
1521 // too much if reading them is slow.
1525 /// All the fees paid *after* this channel on the way to the destination
1526 next_hops_fee_msat: u64,
1527 /// Fee paid for the use of the current channel (see candidate.fees()).
1528 /// The value will be actually deducted from the counterparty balance on the previous link.
1529 hop_use_fee_msat: u64,
1531 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1532 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1533 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1534 // value_contribution_msat, which requires tracking it here. See comments below where it is
1535 // used for more info.
1536 value_contribution_msat: u64,
1539 // Checks that the entries in the `find_route` `dist` map fit in (exactly) two standard x86-64
1540 // cache lines. Sadly, they're not guaranteed to actually lie on a cache line (and in fact,
1541 // generally won't, because at least glibc's malloc will align to a nice, big, round
1542 // boundary...plus 16), but at least it will reduce the amount of data we'll need to load.
1544 // Note that these assertions only pass on somewhat recent rustc, and thus are gated on the
1547 const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::<(NodeId, PathBuildingHop)>();
1549 const _NODE_MAP_SIZE_EXACTLY_CACHE_LINES: usize = core::mem::size_of::<(NodeId, PathBuildingHop)>() - 128;
1551 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1552 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1553 let mut debug_struct = f.debug_struct("PathBuildingHop");
1555 .field("node_id", &self.candidate.target())
1556 .field("short_channel_id", &self.candidate.short_channel_id())
1557 .field("total_fee_msat", &self.total_fee_msat)
1558 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1559 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1560 .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)))
1561 .field("path_penalty_msat", &self.path_penalty_msat)
1562 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1563 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1564 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1565 let debug_struct = debug_struct
1566 .field("value_contribution_msat", &self.value_contribution_msat);
1567 debug_struct.finish()
1571 // Instantiated with a list of hops with correct data in them collected during path finding,
1572 // an instance of this struct should be further modified only via given methods.
1574 struct PaymentPath<'a> {
1575 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1578 impl<'a> PaymentPath<'a> {
1579 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1580 fn get_value_msat(&self) -> u64 {
1581 self.hops.last().unwrap().0.fee_msat
1584 fn get_path_penalty_msat(&self) -> u64 {
1585 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1588 fn get_total_fee_paid_msat(&self) -> u64 {
1589 if self.hops.len() < 1 {
1593 // Can't use next_hops_fee_msat because it gets outdated.
1594 for (i, (hop, _)) in self.hops.iter().enumerate() {
1595 if i != self.hops.len() - 1 {
1596 result += hop.fee_msat;
1602 fn get_cost_msat(&self) -> u64 {
1603 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1606 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1607 // to change fees may result in an inconsistency.
1609 // Sometimes we call this function right after constructing a path which is inconsistent in
1610 // that it the value being transferred has decreased while we were doing path finding, leading
1611 // to the fees being paid not lining up with the actual limits.
1613 // Note that this function is not aware of the available_liquidity limit, and thus does not
1614 // support increasing the value being transferred beyond what was selected during the initial
1617 // Returns the amount that this path contributes to the total payment value, which may be greater
1618 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1619 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1620 let mut extra_contribution_msat = 0;
1621 let mut total_fee_paid_msat = 0 as u64;
1622 for i in (0..self.hops.len()).rev() {
1623 let last_hop = i == self.hops.len() - 1;
1625 // For non-last-hop, this value will represent the fees paid on the current hop. It
1626 // will consist of the fees for the use of the next hop, and extra fees to match
1627 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1628 let mut cur_hop_fees_msat = 0;
1630 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1633 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1634 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1635 cur_hop.path_penalty_msat += extra_contribution_msat;
1636 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1637 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1638 // set it too high just to maliciously take more fees by exploiting this
1639 // match htlc_minimum_msat logic.
1640 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1641 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1642 // Note that there is a risk that *previous hops* (those closer to us, as we go
1643 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1645 // This might make us end up with a broken route, although this should be super-rare
1646 // in practice, both because of how healthy channels look like, and how we pick
1647 // channels in add_entry.
1648 // Also, this can't be exploited more heavily than *announce a free path and fail
1650 cur_hop_transferred_amount_msat += extra_fees_msat;
1652 // We remember and return the extra fees on the final hop to allow accounting for
1653 // them in the path's value contribution.
1655 extra_contribution_msat = extra_fees_msat;
1657 total_fee_paid_msat += extra_fees_msat;
1658 cur_hop_fees_msat += extra_fees_msat;
1663 // Final hop is a special case: it usually has just value_msat (by design), but also
1664 // it still could overpay for the htlc_minimum_msat.
1665 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1667 // Propagate updated fees for the use of the channels to one hop back, where they
1668 // will be actually paid (fee_msat). The last hop is handled above separately.
1669 cur_hop.fee_msat = cur_hop_fees_msat;
1672 // Fee for the use of the current hop which will be deducted on the previous hop.
1673 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1674 // this channel is free for us.
1676 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1677 cur_hop.hop_use_fee_msat = new_fee;
1678 total_fee_paid_msat += new_fee;
1680 // It should not be possible because this function is called only to reduce the
1681 // value. In that case, compute_fee was already called with the same fees for
1682 // larger amount and there was no overflow.
1687 value_msat + extra_contribution_msat
1692 /// Calculate the fees required to route the given amount over a channel with the given fees.
1693 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1694 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1695 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1699 /// Calculate the fees required to route the given amount over a channel with the given fees,
1700 /// saturating to [`u64::max_value`].
1701 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1702 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1703 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1704 .saturating_add(channel_fees.base_msat as u64)
1707 /// The default `features` we assume for a node in a route, when no `features` are known about that
1710 /// Default features are:
1711 /// * variable_length_onion_optional
1712 fn default_node_features() -> NodeFeatures {
1713 let mut features = NodeFeatures::empty();
1714 features.set_variable_length_onion_optional();
1718 struct LoggedPayeePubkey(Option<PublicKey>);
1719 impl fmt::Display for LoggedPayeePubkey {
1720 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1723 "payee node id ".fmt(f)?;
1727 "blinded payee".fmt(f)
1733 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1734 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1735 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1737 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1738 "blinded route hint with introduction node ".fmt(f)?;
1739 match &hint.1.introduction_node {
1740 IntroductionNode::NodeId(pubkey) => write!(f, "id {}", pubkey)?,
1741 IntroductionNode::DirectedShortChannelId(direction, scid) => {
1743 Direction::NodeOne => {
1744 write!(f, "one on channel with SCID {}", scid)?;
1746 Direction::NodeTwo => {
1747 write!(f, "two on channel with SCID {}", scid)?;
1752 " and blinding point ".fmt(f)?;
1753 hint.1.blinding_point.fmt(f)
1755 CandidateRouteHop::FirstHop(_) => {
1756 "first hop with SCID ".fmt(f)?;
1757 self.0.short_channel_id().unwrap().fmt(f)
1759 CandidateRouteHop::PrivateHop(_) => {
1760 "route hint with SCID ".fmt(f)?;
1761 self.0.short_channel_id().unwrap().fmt(f)
1765 self.0.short_channel_id().unwrap().fmt(f)
1772 fn sort_first_hop_channels(
1773 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1774 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1776 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1777 // most like to use.
1779 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1780 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1783 // Second, because simply always sorting in descending order would always use our largest
1784 // available outbound capacity, needlessly fragmenting our available channel capacities,
1785 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1786 // which have enough, but not too much, capacity for the payment.
1788 // Available outbound balances factor in liquidity already reserved for previously found paths.
1789 channels.sort_unstable_by(|chan_a, chan_b| {
1790 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1791 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1792 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1793 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1794 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1795 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1796 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1797 // Sort in descending order
1798 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1800 // Sort in ascending order
1801 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1806 /// Finds a route from us (payer) to the given target node (payee).
1808 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1809 /// in the given [`RouteParameters::payment_params`].
1810 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1812 /// Private routing paths between a public node and the target may be included in the `payee` field
1813 /// of [`RouteParameters::payment_params`].
1815 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1816 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1817 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1819 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1820 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1821 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1825 /// Panics if first_hops contains channels without `short_channel_id`s;
1826 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1828 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1829 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1830 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1831 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1832 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1833 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1834 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1835 ) -> Result<Route, LightningError>
1836 where L::Target: Logger, GL::Target: Logger {
1837 let graph_lock = network_graph.read_only();
1838 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1839 scorer, score_params, random_seed_bytes)?;
1840 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1844 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1845 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1846 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1847 _random_seed_bytes: &[u8; 32]
1848 ) -> Result<Route, LightningError>
1849 where L::Target: Logger {
1851 let payment_params = &route_params.payment_params;
1852 let final_value_msat = route_params.final_value_msat;
1853 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1854 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1855 // so use a dummy id for this in the blinded case.
1856 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1857 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1858 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1859 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1860 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1862 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1863 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1865 if our_node_id == maybe_dummy_payee_node_id {
1866 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1869 if final_value_msat > MAX_VALUE_MSAT {
1870 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1873 if final_value_msat == 0 {
1874 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1877 match &payment_params.payee {
1878 Payee::Clear { route_hints, node_id, .. } => {
1879 for route in route_hints.iter() {
1880 for hop in &route.0 {
1881 if hop.src_node_id == *node_id {
1882 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1887 Payee::Blinded { route_hints, .. } => {
1888 if route_hints.iter().all(|(_, path)| path.public_introduction_node_id(network_graph) == Some(&our_node_id)) {
1889 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});
1891 for (_, blinded_path) in route_hints.iter() {
1892 if blinded_path.blinded_hops.len() == 0 {
1893 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1894 } else if blinded_path.public_introduction_node_id(network_graph) == Some(&our_node_id) {
1895 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1896 } else if blinded_path.blinded_hops.len() == 1 &&
1897 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1898 && p.public_introduction_node_id(network_graph) != blinded_path.public_introduction_node_id(network_graph))
1900 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1905 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1906 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1907 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});
1910 // The general routing idea is the following:
1911 // 1. Fill first/last hops communicated by the caller.
1912 // 2. Attempt to construct a path from payer to payee for transferring
1913 // any ~sufficient (described later) value.
1914 // If succeed, remember which channels were used and how much liquidity they have available,
1915 // so that future paths don't rely on the same liquidity.
1916 // 3. Proceed to the next step if:
1917 // - we hit the recommended target value;
1918 // - OR if we could not construct a new path. Any next attempt will fail too.
1919 // Otherwise, repeat step 2.
1920 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1921 // (not recommended value).
1922 // 5. If yes, proceed. If not, fail routing.
1923 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1924 // transferred up to the transfer target value.
1925 // 7. Reduce the value of the last path until we are sending only the target value.
1926 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1927 // them so that we're not sending two HTLCs along the same path.
1929 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1930 // distance from the payee
1932 // We are not a faithful Dijkstra's implementation because we can change values which impact
1933 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1934 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1935 // the value we are currently attempting to send over a path, we simply reduce the value being
1936 // sent along the path for any hops after that channel. This may imply that later fees (which
1937 // we've already tabulated) are lower because a smaller value is passing through the channels
1938 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1939 // channels which were selected earlier (and which may still be used for other paths without a
1940 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1943 // One potentially problematic case for this algorithm would be if there are many
1944 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1945 // graph walking), we may never find a path which is not liquidity-limited and has lower
1946 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1947 // Because we only consider paths with at least 5% of the total value being sent, the damage
1948 // from such a case should be limited, however this could be further reduced in the future by
1949 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1950 // limits for the purposes of fee calculation.
1952 // Alternatively, we could store more detailed path information in the heap (targets, below)
1953 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1954 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1955 // and practically (as we would need to store dynamically-allocated path information in heap
1956 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1957 // results of such an algorithm would likely be biased towards lower-value paths.
1959 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1960 // outside of our current search value, running a path search more times to gather candidate
1961 // paths at different values. While this may be acceptable, further path searches may increase
1962 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1963 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1964 // the same time, remaining generic across different payment values.
1966 let network_channels = network_graph.channels();
1967 let network_nodes = network_graph.nodes();
1969 if payment_params.max_path_count == 0 {
1970 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1973 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1974 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1976 let allow_mpp = if payment_params.max_path_count == 1 {
1978 } else if payment_params.payee.supports_basic_mpp() {
1980 } else if let Some(payee) = payee_node_id_opt {
1981 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1982 |info| info.features.supports_basic_mpp()))
1985 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1987 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph with a fee limit of {} msat",
1988 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
1989 if allow_mpp { "with" } else { "without" },
1990 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " },
1991 max_total_routing_fee_msat);
1994 // Prepare the data we'll use for payee-to-payer search by
1995 // inserting first hops suggested by the caller as targets.
1996 // Our search will then attempt to reach them while traversing from the payee node.
1997 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1998 hash_map_with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1999 if let Some(hops) = first_hops {
2001 if chan.get_outbound_payment_scid().is_none() {
2002 panic!("first_hops should be filled in with usable channels, not pending ones");
2004 if chan.counterparty.node_id == *our_node_pubkey {
2005 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
2008 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
2009 .or_insert(Vec::new())
2012 if first_hop_targets.is_empty() {
2013 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
2017 let mut private_hop_key_cache = hash_map_with_capacity(
2018 payment_params.payee.unblinded_route_hints().iter().map(|path| path.0.len()).sum()
2021 // Because we store references to private hop node_ids in `dist`, below, we need them to exist
2022 // (as `NodeId`, not `PublicKey`) for the lifetime of `dist`. Thus, we calculate all the keys
2023 // we'll need here and simply fetch them when routing.
2024 private_hop_key_cache.insert(maybe_dummy_payee_pk, NodeId::from_pubkey(&maybe_dummy_payee_pk));
2025 for route in payment_params.payee.unblinded_route_hints().iter() {
2026 for hop in route.0.iter() {
2027 private_hop_key_cache.insert(hop.src_node_id, NodeId::from_pubkey(&hop.src_node_id));
2031 // The main heap containing all candidate next-hops sorted by their score (max(fee,
2032 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
2033 // adding duplicate entries when we find a better path to a given node.
2034 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
2036 // Map from node_id to information about the best current path to that node, including feerate
2038 let mut dist: HashMap<NodeId, PathBuildingHop> = hash_map_with_capacity(network_nodes.len());
2040 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
2041 // indicating that we may wish to try again with a higher value, potentially paying to meet an
2042 // htlc_minimum with extra fees while still finding a cheaper path.
2043 let mut hit_minimum_limit;
2045 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
2046 // We start with a path_value of the exact amount we want, and if that generates a route we may
2047 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
2048 // amount we want in total across paths, selecting the best subset at the end.
2049 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
2050 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
2051 let mut path_value_msat = final_value_msat;
2053 // Routing Fragmentation Mitigation heuristic:
2055 // Routing fragmentation across many payment paths increases the overall routing
2056 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
2057 // Taking too many smaller paths also increases the chance of payment failure.
2058 // Thus to avoid this effect, we require from our collected links to provide
2059 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
2060 // This requirement is currently set to be 1/max_path_count of the payment
2061 // value to ensure we only ever return routes that do not violate this limit.
2062 let minimal_value_contribution_msat: u64 = if allow_mpp {
2063 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
2068 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
2069 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
2070 // drop the requirement by setting this to 0.
2071 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
2073 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
2074 // determine if the channel can be used by additional MPP paths or to inform path finding
2075 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
2076 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
2078 let mut used_liquidities: HashMap<CandidateHopId, u64> =
2079 hash_map_with_capacity(network_nodes.len());
2081 // Keeping track of how much value we already collected across other paths. Helps to decide
2082 // when we want to stop looking for new paths.
2083 let mut already_collected_value_msat = 0;
2085 for (_, channels) in first_hop_targets.iter_mut() {
2086 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
2090 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
2091 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
2093 // Remember how many candidates we ignored to allow for some logging afterwards.
2094 let mut num_ignored_value_contribution: u32 = 0;
2095 let mut num_ignored_path_length_limit: u32 = 0;
2096 let mut num_ignored_cltv_delta_limit: u32 = 0;
2097 let mut num_ignored_previously_failed: u32 = 0;
2098 let mut num_ignored_total_fee_limit: u32 = 0;
2099 let mut num_ignored_avoid_overpayment: u32 = 0;
2100 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
2102 macro_rules! add_entry {
2103 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
2104 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
2105 // since that value has to be transferred over this channel.
2106 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
2107 ( $candidate: expr, $next_hops_fee_msat: expr,
2108 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
2109 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
2110 // We "return" whether we updated the path at the end, and how much we can route via
2111 // this channel, via this:
2112 let mut hop_contribution_amt_msat = None;
2113 // Channels to self should not be used. This is more of belt-and-suspenders, because in
2114 // practice these cases should be caught earlier:
2115 // - for regular channels at channel announcement (TODO)
2116 // - for first and last hops early in get_route
2117 let src_node_id = $candidate.source();
2118 if Some(src_node_id) != $candidate.target() {
2119 let scid_opt = $candidate.short_channel_id();
2120 let effective_capacity = $candidate.effective_capacity();
2121 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
2123 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
2124 // It may be misleading because we might later choose to reduce the value transferred
2125 // over these channels, and the channel which was insufficient might become sufficient.
2126 // Worst case: we drop a good channel here because it can't cover the high following
2127 // fees caused by one expensive channel, but then this channel could have been used
2128 // if the amount being transferred over this path is lower.
2129 // We do this for now, but this is a subject for removal.
2130 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
2131 let used_liquidity_msat = used_liquidities
2132 .get(&$candidate.id())
2133 .map_or(0, |used_liquidity_msat| {
2134 available_value_contribution_msat = available_value_contribution_msat
2135 .saturating_sub(*used_liquidity_msat);
2136 *used_liquidity_msat
2139 // Verify the liquidity offered by this channel complies to the minimal contribution.
2140 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
2141 // Do not consider candidate hops that would exceed the maximum path length.
2142 let path_length_to_node = $next_hops_path_length + 1;
2143 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
2145 // Do not consider candidates that exceed the maximum total cltv expiry limit.
2146 // In order to already account for some of the privacy enhancing random CLTV
2147 // expiry delta offset we add on top later, we subtract a rough estimate
2148 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
2149 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
2150 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
2151 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
2152 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
2153 .saturating_add($candidate.cltv_expiry_delta());
2154 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
2156 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
2157 // Includes paying fees for the use of the following channels.
2158 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
2159 Some(result) => result,
2160 // Can't overflow due to how the values were computed right above.
2161 None => unreachable!(),
2163 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2164 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
2165 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
2167 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2168 let may_overpay_to_meet_path_minimum_msat =
2169 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
2170 recommended_value_msat >= $candidate.htlc_minimum_msat()) ||
2171 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
2172 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
2174 let payment_failed_on_this_channel = match scid_opt {
2175 Some(scid) => payment_params.previously_failed_channels.contains(&scid),
2176 None => match $candidate.blinded_hint_idx() {
2178 payment_params.previously_failed_blinded_path_idxs.contains(&(idx as u64))
2184 let (should_log_candidate, first_hop_details) = match $candidate {
2185 CandidateRouteHop::FirstHop(hop) => (true, Some(hop.details)),
2186 CandidateRouteHop::PrivateHop(_) => (true, None),
2187 CandidateRouteHop::Blinded(_) => (true, None),
2188 CandidateRouteHop::OneHopBlinded(_) => (true, None),
2192 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
2193 // bother considering this channel. If retrying with recommended_value_msat may
2194 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
2195 // around again with a higher amount.
2196 if !contributes_sufficient_value {
2197 if should_log_candidate {
2198 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
2200 if let Some(details) = first_hop_details {
2202 "First hop candidate next_outbound_htlc_limit_msat: {}",
2203 details.next_outbound_htlc_limit_msat,
2207 num_ignored_value_contribution += 1;
2208 } else if exceeds_max_path_length {
2209 if should_log_candidate {
2210 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
2212 num_ignored_path_length_limit += 1;
2213 } else if exceeds_cltv_delta_limit {
2214 if should_log_candidate {
2215 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
2217 if let Some(_) = first_hop_details {
2219 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
2220 hop_total_cltv_delta,
2221 max_total_cltv_expiry_delta,
2225 num_ignored_cltv_delta_limit += 1;
2226 } else if payment_failed_on_this_channel {
2227 if should_log_candidate {
2228 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
2230 num_ignored_previously_failed += 1;
2231 } else if may_overpay_to_meet_path_minimum_msat {
2232 if should_log_candidate {
2234 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit.",
2235 LoggedCandidateHop(&$candidate));
2237 if let Some(details) = first_hop_details {
2239 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2240 details.next_outbound_htlc_minimum_msat,
2244 num_ignored_avoid_overpayment += 1;
2245 hit_minimum_limit = true;
2246 } else if over_path_minimum_msat {
2247 // Note that low contribution here (limited by available_liquidity_msat)
2248 // might violate htlc_minimum_msat on the hops which are next along the
2249 // payment path (upstream to the payee). To avoid that, we recompute
2250 // path fees knowing the final path contribution after constructing it.
2251 let curr_min = cmp::max(
2252 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
2254 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
2255 .saturating_add(curr_min);
2256 let hm_entry = dist.entry(src_node_id);
2257 let old_entry = hm_entry.or_insert_with(|| {
2258 // If there was previously no known way to access the source node
2259 // (recall it goes payee-to-payer) of short_channel_id, first add a
2260 // semi-dummy record just to compute the fees to reach the source node.
2261 // This will affect our decision on selecting short_channel_id
2262 // as a way to reach the $candidate.target() node.
2264 candidate: $candidate.clone(),
2266 next_hops_fee_msat: u64::max_value(),
2267 hop_use_fee_msat: u64::max_value(),
2268 total_fee_msat: u64::max_value(),
2269 path_htlc_minimum_msat,
2270 path_penalty_msat: u64::max_value(),
2271 was_processed: false,
2272 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2273 value_contribution_msat,
2277 #[allow(unused_mut)] // We only use the mut in cfg(test)
2278 let mut should_process = !old_entry.was_processed;
2279 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2281 // In test/fuzzing builds, we do extra checks to make sure the skipping
2282 // of already-seen nodes only happens in cases we expect (see below).
2283 if !should_process { should_process = true; }
2287 let mut hop_use_fee_msat = 0;
2288 let mut total_fee_msat: u64 = $next_hops_fee_msat;
2290 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2291 // will have the same effective-fee
2292 if src_node_id != our_node_id {
2293 // Note that `u64::max_value` means we'll always fail the
2294 // `old_entry.total_fee_msat > total_fee_msat` check below
2295 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
2296 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2299 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2300 if total_fee_msat > max_total_routing_fee_msat {
2301 if should_log_candidate {
2302 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2304 if let Some(_) = first_hop_details {
2306 "First hop candidate routing fee: {}. Limit: {}",
2308 max_total_routing_fee_msat,
2312 num_ignored_total_fee_limit += 1;
2314 let channel_usage = ChannelUsage {
2315 amount_msat: amount_to_transfer_over_msat,
2316 inflight_htlc_msat: used_liquidity_msat,
2319 let channel_penalty_msat =
2320 scorer.channel_penalty_msat($candidate,
2323 let path_penalty_msat = $next_hops_path_penalty_msat
2324 .saturating_add(channel_penalty_msat);
2326 // Update the way of reaching $candidate.source()
2327 // with the given short_channel_id (from $candidate.target()),
2328 // if this way is cheaper than the already known
2329 // (considering the cost to "reach" this channel from the route destination,
2330 // the cost of using this channel,
2331 // and the cost of routing to the source node of this channel).
2332 // Also, consider that htlc_minimum_msat_difference, because we might end up
2333 // paying it. Consider the following exploit:
2334 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2335 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2336 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2337 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2339 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2340 // but it may require additional tracking - we don't want to double-count
2341 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2342 // can't use something that may decrease on future hops.
2343 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2344 .saturating_add(old_entry.path_penalty_msat);
2345 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2346 .saturating_add(path_penalty_msat);
2348 if !old_entry.was_processed && new_cost < old_cost {
2349 let new_graph_node = RouteGraphNode {
2350 node_id: src_node_id,
2351 score: cmp::max(total_fee_msat, path_htlc_minimum_msat).saturating_add(path_penalty_msat),
2352 total_cltv_delta: hop_total_cltv_delta,
2353 value_contribution_msat,
2354 path_length_to_node,
2356 targets.push(new_graph_node);
2357 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2358 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2359 old_entry.total_fee_msat = total_fee_msat;
2360 old_entry.candidate = $candidate.clone();
2361 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2362 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2363 old_entry.path_penalty_msat = path_penalty_msat;
2364 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2366 old_entry.value_contribution_msat = value_contribution_msat;
2368 hop_contribution_amt_msat = Some(value_contribution_msat);
2369 } else if old_entry.was_processed && new_cost < old_cost {
2370 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2372 // If we're skipping processing a node which was previously
2373 // processed even though we found another path to it with a
2374 // cheaper fee, check that it was because the second path we
2375 // found (which we are processing now) has a lower value
2376 // contribution due to an HTLC minimum limit.
2378 // e.g. take a graph with two paths from node 1 to node 2, one
2379 // through channel A, and one through channel B. Channel A and
2380 // B are both in the to-process heap, with their scores set by
2381 // a higher htlc_minimum than fee.
2382 // Channel A is processed first, and the channels onwards from
2383 // node 1 are added to the to-process heap. Thereafter, we pop
2384 // Channel B off of the heap, note that it has a much more
2385 // restrictive htlc_maximum_msat, and recalculate the fees for
2386 // all of node 1's channels using the new, reduced, amount.
2388 // This would be bogus - we'd be selecting a higher-fee path
2389 // with a lower htlc_maximum_msat instead of the one we'd
2390 // already decided to use.
2391 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2393 value_contribution_msat + path_penalty_msat <
2394 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2401 if should_log_candidate {
2403 "Ignoring {} due to its htlc_minimum_msat limit.",
2404 LoggedCandidateHop(&$candidate));
2406 if let Some(details) = first_hop_details {
2408 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2409 details.next_outbound_htlc_minimum_msat,
2413 num_ignored_htlc_minimum_msat_limit += 1;
2417 hop_contribution_amt_msat
2421 let default_node_features = default_node_features();
2423 // Find ways (channels with destination) to reach a given node and store them
2424 // in the corresponding data structures (routing graph etc).
2425 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2426 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2427 // This data can later be helpful to optimize routing (pay lower fees).
2428 macro_rules! add_entries_to_cheapest_to_target_node {
2429 ( $node: expr, $node_id: expr, $next_hops_value_contribution: expr,
2430 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2431 let fee_to_target_msat;
2432 let next_hops_path_htlc_minimum_msat;
2433 let next_hops_path_penalty_msat;
2434 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
2435 let was_processed = elem.was_processed;
2436 elem.was_processed = true;
2437 fee_to_target_msat = elem.total_fee_msat;
2438 next_hops_path_htlc_minimum_msat = elem.path_htlc_minimum_msat;
2439 next_hops_path_penalty_msat = elem.path_penalty_msat;
2442 // Entries are added to dist in add_entry!() when there is a channel from a node.
2443 // Because there are no channels from payee, it will not have a dist entry at this point.
2444 // If we're processing any other node, it is always be the result of a channel from it.
2445 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2446 fee_to_target_msat = 0;
2447 next_hops_path_htlc_minimum_msat = 0;
2448 next_hops_path_penalty_msat = 0;
2453 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
2454 for details in first_channels {
2455 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2456 details, payer_node_id: &our_node_id,
2458 add_entry!(&candidate, fee_to_target_msat,
2459 $next_hops_value_contribution,
2460 next_hops_path_htlc_minimum_msat, next_hops_path_penalty_msat,
2461 $next_hops_cltv_delta, $next_hops_path_length);
2465 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2468 &default_node_features
2471 if !features.requires_unknown_bits() {
2472 for chan_id in $node.channels.iter() {
2473 let chan = network_channels.get(chan_id).unwrap();
2474 if !chan.features.requires_unknown_bits() {
2475 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2476 if first_hops.is_none() || *source != our_node_id {
2477 if directed_channel.direction().enabled {
2478 let candidate = CandidateRouteHop::PublicHop(PublicHopCandidate {
2479 info: directed_channel,
2480 short_channel_id: *chan_id,
2482 add_entry!(&candidate,
2484 $next_hops_value_contribution,
2485 next_hops_path_htlc_minimum_msat,
2486 next_hops_path_penalty_msat,
2487 $next_hops_cltv_delta, $next_hops_path_length);
2498 let mut payment_paths = Vec::<PaymentPath>::new();
2500 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2501 'paths_collection: loop {
2502 // For every new path, start from scratch, except for used_liquidities, which
2503 // helps to avoid reusing previously selected paths in future iterations.
2506 hit_minimum_limit = false;
2508 // If first hop is a private channel and the only way to reach the payee, this is the only
2509 // place where it could be added.
2510 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2511 for details in first_channels {
2512 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2513 details, payer_node_id: &our_node_id,
2515 let added = add_entry!(&candidate, 0, path_value_msat,
2516 0, 0u64, 0, 0).is_some();
2517 log_trace!(logger, "{} direct route to payee via {}",
2518 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2522 // Add the payee as a target, so that the payee-to-payer
2523 // search algorithm knows what to start with.
2524 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2525 // The payee is not in our network graph, so nothing to add here.
2526 // There is still a chance of reaching them via last_hops though,
2527 // so don't yet fail the payment here.
2528 // If not, targets.pop() will not even let us enter the loop in step 2.
2531 add_entries_to_cheapest_to_target_node!(node, payee, path_value_msat, 0, 0);
2536 // If a caller provided us with last hops, add them to routing targets. Since this happens
2537 // earlier than general path finding, they will be somewhat prioritized, although currently
2538 // it matters only if the fees are exactly the same.
2539 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2540 // Only add the hops in this route to our candidate set if either
2541 // we have a direct channel to the first hop or the first hop is
2542 // in the regular network graph.
2543 let source_node_id = match hint.1.public_introduction_node_id(network_graph) {
2544 Some(node_id) => node_id,
2545 None => match &hint.1.introduction_node {
2546 IntroductionNode::NodeId(pubkey) => {
2547 let node_id = NodeId::from_pubkey(&pubkey);
2548 match first_hop_targets.get_key_value(&node_id).map(|(key, _)| key) {
2549 Some(node_id) => node_id,
2553 IntroductionNode::DirectedShortChannelId(direction, scid) => {
2554 let first_hop = first_hop_targets.iter().find(|(_, channels)|
2557 .any(|details| Some(*scid) == details.get_outbound_payment_scid())
2560 Some((counterparty_node_id, _)) => {
2561 direction.select_node_id(&our_node_id, counterparty_node_id)
2568 if our_node_id == *source_node_id { continue }
2569 let candidate = if hint.1.blinded_hops.len() == 1 {
2570 CandidateRouteHop::OneHopBlinded(
2571 OneHopBlindedPathCandidate { source_node_id, hint, hint_idx }
2574 CandidateRouteHop::Blinded(BlindedPathCandidate { source_node_id, hint, hint_idx })
2576 let mut path_contribution_msat = path_value_msat;
2577 if let Some(hop_used_msat) = add_entry!(&candidate,
2578 0, path_contribution_msat, 0, 0_u64, 0, 0)
2580 path_contribution_msat = hop_used_msat;
2582 if let Some(first_channels) = first_hop_targets.get(source_node_id) {
2583 let mut first_channels = first_channels.clone();
2584 sort_first_hop_channels(
2585 &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2587 for details in first_channels {
2588 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2589 details, payer_node_id: &our_node_id,
2591 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2595 let path_min = candidate.htlc_minimum_msat().saturating_add(
2596 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2597 add_entry!(&first_hop_candidate, blinded_path_fee,
2598 path_contribution_msat, path_min, 0_u64, candidate.cltv_expiry_delta(),
2599 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2603 for route in payment_params.payee.unblinded_route_hints().iter()
2604 .filter(|route| !route.0.is_empty())
2606 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2607 let first_hop_src_is_reachable =
2608 // Only add the hops in this route to our candidate set if either we are part of
2609 // the first hop, we have a direct channel to the first hop, or the first hop is in
2610 // the regular network graph.
2611 our_node_id == first_hop_src_id ||
2612 first_hop_targets.get(&first_hop_src_id).is_some() ||
2613 network_nodes.get(&first_hop_src_id).is_some();
2614 if first_hop_src_is_reachable {
2615 // We start building the path from reverse, i.e., from payee
2616 // to the first RouteHintHop in the path.
2617 let hop_iter = route.0.iter().rev();
2618 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2619 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2620 let mut hop_used = true;
2621 let mut aggregate_next_hops_fee_msat: u64 = 0;
2622 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2623 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2624 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2625 let mut aggregate_next_hops_path_length: u8 = 0;
2626 let mut aggregate_path_contribution_msat = path_value_msat;
2628 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2629 let target = private_hop_key_cache.get(prev_hop_id).unwrap();
2631 if let Some(first_channels) = first_hop_targets.get(target) {
2632 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2633 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2634 hop.short_channel_id);
2639 let candidate = network_channels
2640 .get(&hop.short_channel_id)
2641 .and_then(|channel| channel.as_directed_to(target))
2642 .map(|(info, _)| CandidateRouteHop::PublicHop(PublicHopCandidate {
2644 short_channel_id: hop.short_channel_id,
2646 .unwrap_or_else(|| CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: hop, target_node_id: target }));
2648 if let Some(hop_used_msat) = add_entry!(&candidate,
2649 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2650 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2651 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2653 aggregate_path_contribution_msat = hop_used_msat;
2655 // If this hop was not used then there is no use checking the preceding
2656 // hops in the RouteHint. We can break by just searching for a direct
2657 // channel between last checked hop and first_hop_targets.
2661 let used_liquidity_msat = used_liquidities
2662 .get(&candidate.id()).copied()
2664 let channel_usage = ChannelUsage {
2665 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2666 inflight_htlc_msat: used_liquidity_msat,
2667 effective_capacity: candidate.effective_capacity(),
2669 let channel_penalty_msat = scorer.channel_penalty_msat(
2670 &candidate, channel_usage, score_params
2672 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2673 .saturating_add(channel_penalty_msat);
2675 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2676 .saturating_add(hop.cltv_expiry_delta as u32);
2678 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2681 // Searching for a direct channel between last checked hop and first_hop_targets
2682 if let Some(first_channels) = first_hop_targets.get(target) {
2683 let mut first_channels = first_channels.clone();
2684 sort_first_hop_channels(
2685 &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2687 for details in first_channels {
2688 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2689 details, payer_node_id: &our_node_id,
2691 add_entry!(&first_hop_candidate,
2692 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2693 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2694 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2702 // In the next values of the iterator, the aggregate fees already reflects
2703 // the sum of value sent from payer (final_value_msat) and routing fees
2704 // for the last node in the RouteHint. We need to just add the fees to
2705 // route through the current node so that the preceding node (next iteration)
2707 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2708 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2709 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2711 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2712 // this route hint's source node to forward said min over this channel.
2713 aggregate_next_hops_path_htlc_minimum_msat = {
2714 let curr_htlc_min = cmp::max(
2715 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2717 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2718 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2721 if idx == route.0.len() - 1 {
2722 // The last hop in this iterator is the first hop in
2723 // overall RouteHint.
2724 // If this hop connects to a node with which we have a direct channel,
2725 // ignore the network graph and, if the last hop was added, add our
2726 // direct channel to the candidate set.
2728 // Note that we *must* check if the last hop was added as `add_entry`
2729 // always assumes that the third argument is a node to which we have a
2731 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
2732 let mut first_channels = first_channels.clone();
2733 sort_first_hop_channels(
2734 &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2736 for details in first_channels {
2737 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2738 details, payer_node_id: &our_node_id,
2740 add_entry!(&first_hop_candidate,
2741 aggregate_next_hops_fee_msat,
2742 aggregate_path_contribution_msat,
2743 aggregate_next_hops_path_htlc_minimum_msat,
2744 aggregate_next_hops_path_penalty_msat,
2745 aggregate_next_hops_cltv_delta,
2746 aggregate_next_hops_path_length);
2754 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2756 // At this point, targets are filled with the data from first and
2757 // last hops communicated by the caller, and the payment receiver.
2758 let mut found_new_path = false;
2761 // If this loop terminates due the exhaustion of targets, two situations are possible:
2762 // - not enough outgoing liquidity:
2763 // 0 < already_collected_value_msat < final_value_msat
2764 // - enough outgoing liquidity:
2765 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2766 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2767 // paths_collection will be stopped because found_new_path==false.
2768 // This is not necessarily a routing failure.
2769 'path_construction: while let Some(RouteGraphNode { node_id, total_cltv_delta, mut value_contribution_msat, path_length_to_node, .. }) = targets.pop() {
2771 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2772 // traversing the graph and arrange the path out of what we found.
2773 if node_id == our_node_id {
2774 let mut new_entry = dist.remove(&our_node_id).unwrap();
2775 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2778 let mut features_set = false;
2779 let target = ordered_hops.last().unwrap().0.candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2780 if let Some(first_channels) = first_hop_targets.get(&target) {
2781 for details in first_channels {
2782 if let CandidateRouteHop::FirstHop(FirstHopCandidate { details: last_hop_details, .. })
2783 = ordered_hops.last().unwrap().0.candidate
2785 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2786 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2787 features_set = true;
2794 if let Some(node) = network_nodes.get(&target) {
2795 if let Some(node_info) = node.announcement_info.as_ref() {
2796 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2798 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2801 // We can fill in features for everything except hops which were
2802 // provided via the invoice we're paying. We could guess based on the
2803 // recipient's features but for now we simply avoid guessing at all.
2807 // Means we successfully traversed from the payer to the payee, now
2808 // save this path for the payment route. Also, update the liquidity
2809 // remaining on the used hops, so that we take them into account
2810 // while looking for more paths.
2811 if target == maybe_dummy_payee_node_id {
2815 new_entry = match dist.remove(&target) {
2816 Some(payment_hop) => payment_hop,
2817 // We can't arrive at None because, if we ever add an entry to targets,
2818 // we also fill in the entry in dist (see add_entry!).
2819 None => unreachable!(),
2821 // We "propagate" the fees one hop backward (topologically) here,
2822 // so that fees paid for a HTLC forwarding on the current channel are
2823 // associated with the previous channel (where they will be subtracted).
2824 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2825 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2827 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2828 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2830 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2831 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2833 let mut payment_path = PaymentPath {hops: ordered_hops};
2835 // We could have possibly constructed a slightly inconsistent path: since we reduce
2836 // value being transferred along the way, we could have violated htlc_minimum_msat
2837 // on some channels we already passed (assuming dest->source direction). Here, we
2838 // recompute the fees again, so that if that's the case, we match the currently
2839 // underpaid htlc_minimum_msat with fees.
2840 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2841 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2842 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2844 // Since a path allows to transfer as much value as
2845 // the smallest channel it has ("bottleneck"), we should recompute
2846 // the fees so sender HTLC don't overpay fees when traversing
2847 // larger channels than the bottleneck. This may happen because
2848 // when we were selecting those channels we were not aware how much value
2849 // this path will transfer, and the relative fee for them
2850 // might have been computed considering a larger value.
2851 // Remember that we used these channels so that we don't rely
2852 // on the same liquidity in future paths.
2853 let mut prevented_redundant_path_selection = false;
2854 for (hop, _) in payment_path.hops.iter() {
2855 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2856 let used_liquidity_msat = used_liquidities
2857 .entry(hop.candidate.id())
2858 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2859 .or_insert(spent_on_hop_msat);
2860 let hop_capacity = hop.candidate.effective_capacity();
2861 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2862 if *used_liquidity_msat == hop_max_msat {
2863 // If this path used all of this channel's available liquidity, we know
2864 // this path will not be selected again in the next loop iteration.
2865 prevented_redundant_path_selection = true;
2867 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2869 if !prevented_redundant_path_selection {
2870 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2871 // we'll probably end up picking the same path again on the next iteration.
2872 // Decrease the available liquidity of a hop in the middle of the path.
2873 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2874 let exhausted = u64::max_value();
2876 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2877 LoggedCandidateHop(victim_candidate));
2878 if let Some(scid) = victim_candidate.short_channel_id() {
2879 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2880 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2884 // Track the total amount all our collected paths allow to send so that we know
2885 // when to stop looking for more paths
2886 already_collected_value_msat += value_contribution_msat;
2888 payment_paths.push(payment_path);
2889 found_new_path = true;
2890 break 'path_construction;
2893 // If we found a path back to the payee, we shouldn't try to process it again. This is
2894 // the equivalent of the `elem.was_processed` check in
2895 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2896 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2898 // Otherwise, since the current target node is not us,
2899 // keep "unrolling" the payment graph from payee to payer by
2900 // finding a way to reach the current target from the payer side.
2901 match network_nodes.get(&node_id) {
2904 add_entries_to_cheapest_to_target_node!(node, node_id,
2905 value_contribution_msat,
2906 total_cltv_delta, path_length_to_node);
2912 if !found_new_path && channel_saturation_pow_half != 0 {
2913 channel_saturation_pow_half = 0;
2914 continue 'paths_collection;
2916 // If we don't support MPP, no use trying to gather more value ever.
2917 break 'paths_collection;
2921 // Stop either when the recommended value is reached or if no new path was found in this
2923 // In the latter case, making another path finding attempt won't help,
2924 // because we deterministically terminated the search due to low liquidity.
2925 if !found_new_path && channel_saturation_pow_half != 0 {
2926 channel_saturation_pow_half = 0;
2927 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2928 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
2929 path_value_msat = recommended_value_msat;
2930 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2931 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2932 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2933 break 'paths_collection;
2934 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2935 // Further, if this was our first walk of the graph, and we weren't limited by an
2936 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2937 // limited by an htlc_minimum_msat value, find another path with a higher value,
2938 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2939 // still keeping a lower total fee than this path.
2940 if !hit_minimum_limit {
2941 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2942 break 'paths_collection;
2944 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.");
2945 path_value_msat = recommended_value_msat;
2949 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2950 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
2951 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
2952 num_ignored_total_fee_limit;
2953 if num_ignored_total > 0 {
2955 "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.",
2956 num_ignored_value_contribution, num_ignored_path_length_limit,
2957 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
2958 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
2959 num_ignored_total_fee_limit, num_ignored_total);
2963 if payment_paths.len() == 0 {
2964 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2967 if already_collected_value_msat < final_value_msat {
2968 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2972 let mut selected_route = payment_paths;
2974 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2975 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2977 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2978 // the value they contribute towards the payment amount.
2979 // We sort in descending order as we will remove from the front in `retain`, next.
2980 selected_route.sort_unstable_by(|a, b|
2981 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2982 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2985 // We should make sure that at least 1 path left.
2986 let mut paths_left = selected_route.len();
2987 selected_route.retain(|path| {
2988 if paths_left == 1 {
2991 let path_value_msat = path.get_value_msat();
2992 if path_value_msat <= overpaid_value_msat {
2993 overpaid_value_msat -= path_value_msat;
2999 debug_assert!(selected_route.len() > 0);
3001 if overpaid_value_msat != 0 {
3003 // Now, subtract the remaining overpaid value from the most-expensive path.
3004 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
3005 // so that the sender pays less fees overall. And also htlc_minimum_msat.
3006 selected_route.sort_unstable_by(|a, b| {
3007 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3008 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3009 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
3011 let expensive_payment_path = selected_route.first_mut().unwrap();
3013 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
3014 // can't go negative.
3015 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
3016 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
3020 // Sort by the path itself and combine redundant paths.
3021 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
3022 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
3024 selected_route.sort_unstable_by_key(|path| {
3025 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
3026 debug_assert!(path.hops.len() <= key.len());
3027 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
3032 for idx in 0..(selected_route.len() - 1) {
3033 if idx + 1 >= selected_route.len() { break; }
3034 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
3035 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
3036 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
3037 selected_route[idx].update_value_and_recompute_fees(new_value);
3038 selected_route.remove(idx + 1);
3042 let mut paths = Vec::new();
3043 for payment_path in selected_route {
3044 let mut hops = Vec::with_capacity(payment_path.hops.len());
3045 for (hop, node_features) in payment_path.hops.iter()
3046 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
3048 let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
3049 let maybe_announced_channel = if let CandidateRouteHop::PublicHop(_) = hop.candidate {
3050 // If we sourced the hop from the graph we're sure the target node is announced.
3052 } else if let CandidateRouteHop::FirstHop(first_hop) = &hop.candidate {
3053 // If this is a first hop we also know if it's announced.
3054 first_hop.details.is_public
3056 // If we sourced it any other way, we double-check the network graph to see if
3057 // there are announced channels between the endpoints. If so, the hop might be
3058 // referring to any of the announced channels, as its `short_channel_id` might be
3059 // an alias, in which case we don't take any chances here.
3060 network_graph.node(&target).map_or(false, |hop_node|
3061 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
3062 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
3066 hops.push(RouteHop {
3067 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
3068 node_features: node_features.clone(),
3069 short_channel_id: hop.candidate.short_channel_id().unwrap(),
3070 channel_features: hop.candidate.features(),
3071 fee_msat: hop.fee_msat,
3072 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
3073 maybe_announced_channel,
3076 let mut final_cltv_delta = final_cltv_expiry_delta;
3077 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
3078 if let Some(blinded_path) = h.candidate.blinded_path() {
3079 final_cltv_delta = h.candidate.cltv_expiry_delta();
3081 hops: blinded_path.blinded_hops.clone(),
3082 blinding_point: blinded_path.blinding_point,
3083 excess_final_cltv_expiry_delta: 0,
3084 final_value_msat: h.fee_msat,
3088 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
3089 // applicable for the previous hop.
3090 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
3091 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
3094 paths.push(Path { hops, blinded_tail });
3096 // Make sure we would never create a route with more paths than we allow.
3097 debug_assert!(paths.len() <= payment_params.max_path_count.into());
3099 if let Some(node_features) = payment_params.payee.node_features() {
3100 for path in paths.iter_mut() {
3101 path.hops.last_mut().unwrap().node_features = node_features.clone();
3105 let route = Route { paths, route_params: Some(route_params.clone()) };
3107 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
3108 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
3109 if route.get_total_fees() > max_total_routing_fee_msat {
3110 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
3111 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
3115 log_info!(logger, "Got route: {}", log_route!(route));
3119 // When an adversarial intermediary node observes a payment, it may be able to infer its
3120 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
3121 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
3122 // payment path by adding a randomized 'shadow route' offset to the final hop.
3123 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
3124 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
3126 let network_channels = network_graph.channels();
3127 let network_nodes = network_graph.nodes();
3129 for path in route.paths.iter_mut() {
3130 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
3132 // Remember the last three nodes of the random walk and avoid looping back on them.
3133 // Init with the last three nodes from the actual path, if possible.
3134 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
3135 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
3136 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
3138 // Choose the last publicly known node as the starting point for the random walk.
3139 let mut cur_hop: Option<NodeId> = None;
3140 let mut path_nonce = [0u8; 12];
3141 if let Some(starting_hop) = path.hops.iter().rev()
3142 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
3143 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
3144 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
3147 // Init PRNG with the path-dependant nonce, which is static for private paths.
3148 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
3149 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
3151 // Pick a random path length in [1 .. 3]
3152 prng.process_in_place(&mut random_path_bytes);
3153 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
3155 for random_hop in 0..random_walk_length {
3156 // If we don't find a suitable offset in the public network graph, we default to
3157 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3158 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
3160 if let Some(cur_node_id) = cur_hop {
3161 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
3162 // Randomly choose the next unvisited hop.
3163 prng.process_in_place(&mut random_path_bytes);
3164 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
3165 .checked_rem(cur_node.channels.len())
3166 .and_then(|index| cur_node.channels.get(index))
3167 .and_then(|id| network_channels.get(id)) {
3168 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
3169 if !nodes_to_avoid.iter().any(|x| x == next_id) {
3170 nodes_to_avoid[random_hop] = *next_id;
3171 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
3172 cur_hop = Some(*next_id);
3179 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
3180 .checked_add(random_hop_offset)
3181 .unwrap_or(shadow_ctlv_expiry_delta_offset);
3184 // Limit the total offset to reduce the worst-case locked liquidity timevalue
3185 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
3186 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
3188 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
3189 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3190 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
3191 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
3192 max_path_offset = cmp::max(
3193 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
3194 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
3195 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
3197 // Add 'shadow' CLTV offset to the final hop
3198 if let Some(tail) = path.blinded_tail.as_mut() {
3199 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
3200 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
3202 if let Some(last_hop) = path.hops.last_mut() {
3203 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
3204 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
3209 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
3210 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
3212 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
3213 pub fn build_route_from_hops<L: Deref, GL: Deref>(
3214 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3215 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
3216 ) -> Result<Route, LightningError>
3217 where L::Target: Logger, GL::Target: Logger {
3218 let graph_lock = network_graph.read_only();
3219 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
3220 &graph_lock, logger, random_seed_bytes)?;
3221 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
3225 fn build_route_from_hops_internal<L: Deref>(
3226 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3227 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
3228 ) -> Result<Route, LightningError> where L::Target: Logger {
3231 our_node_id: NodeId,
3232 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
3235 impl ScoreLookUp for HopScorer {
3236 type ScoreParams = ();
3237 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
3238 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
3240 let mut cur_id = self.our_node_id;
3241 for i in 0..self.hop_ids.len() {
3242 if let Some(next_id) = self.hop_ids[i] {
3243 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
3255 impl<'a> Writeable for HopScorer {
3257 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
3262 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
3263 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
3266 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
3267 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
3268 for i in 0..hops.len() {
3269 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
3272 let scorer = HopScorer { our_node_id, hop_ids };
3274 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
3279 use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode};
3280 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
3281 use crate::routing::utxo::UtxoResult;
3282 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
3283 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
3284 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop, PublicHopCandidate};
3285 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
3286 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
3287 use crate::chain::transaction::OutPoint;
3288 use crate::sign::EntropySource;
3289 use crate::ln::ChannelId;
3290 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
3291 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
3292 use crate::ln::channelmanager;
3293 use crate::offers::invoice::BlindedPayInfo;
3294 use crate::util::config::UserConfig;
3295 use crate::util::test_utils as ln_test_utils;
3296 use crate::crypto::chacha20::ChaCha20;
3297 use crate::util::ser::{Readable, Writeable};
3299 use crate::util::ser::Writer;
3301 use bitcoin::hashes::Hash;
3302 use bitcoin::network::constants::Network;
3303 use bitcoin::blockdata::constants::ChainHash;
3304 use bitcoin::blockdata::script::Builder;
3305 use bitcoin::blockdata::opcodes;
3306 use bitcoin::blockdata::transaction::TxOut;
3307 use bitcoin::hashes::hex::FromHex;
3308 use bitcoin::secp256k1::{PublicKey,SecretKey};
3309 use bitcoin::secp256k1::Secp256k1;
3311 use crate::io::Cursor;
3312 use crate::prelude::*;
3313 use crate::sync::Arc;
3315 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3316 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
3317 channelmanager::ChannelDetails {
3318 channel_id: ChannelId::new_zero(),
3319 counterparty: channelmanager::ChannelCounterparty {
3322 unspendable_punishment_reserve: 0,
3323 forwarding_info: None,
3324 outbound_htlc_minimum_msat: None,
3325 outbound_htlc_maximum_msat: None,
3327 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3330 outbound_scid_alias: None,
3331 inbound_scid_alias: None,
3332 channel_value_satoshis: 0,
3335 outbound_capacity_msat,
3336 next_outbound_htlc_limit_msat: outbound_capacity_msat,
3337 next_outbound_htlc_minimum_msat: 0,
3338 inbound_capacity_msat: 42,
3339 unspendable_punishment_reserve: None,
3340 confirmations_required: None,
3341 confirmations: None,
3342 force_close_spend_delay: None,
3343 is_outbound: true, is_channel_ready: true,
3344 is_usable: true, is_public: true,
3345 inbound_htlc_minimum_msat: None,
3346 inbound_htlc_maximum_msat: None,
3348 feerate_sat_per_1000_weight: None,
3349 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
3350 pending_inbound_htlcs: Vec::new(),
3351 pending_outbound_htlcs: Vec::new(),
3356 fn simple_route_test() {
3357 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3358 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3359 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3360 let scorer = ln_test_utils::TestScorer::new();
3361 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3362 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3364 // Simple route to 2 via 1
3366 let route_params = RouteParameters::from_payment_params_and_value(
3367 payment_params.clone(), 0);
3368 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3369 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3370 &Default::default(), &random_seed_bytes) {
3371 assert_eq!(err, "Cannot send a payment of 0 msat");
3372 } else { panic!(); }
3374 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3375 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3376 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3377 assert_eq!(route.paths[0].hops.len(), 2);
3379 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3380 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3381 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3382 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3383 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3384 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3386 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3387 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3388 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3389 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3390 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3391 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3395 fn invalid_first_hop_test() {
3396 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3397 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3398 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3399 let scorer = ln_test_utils::TestScorer::new();
3400 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3401 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3403 // Simple route to 2 via 1
3405 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3407 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3408 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3409 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3410 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3411 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3412 } else { panic!(); }
3414 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3415 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3416 assert_eq!(route.paths[0].hops.len(), 2);
3420 fn htlc_minimum_test() {
3421 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3422 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3423 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3424 let scorer = ln_test_utils::TestScorer::new();
3425 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3426 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3428 // Simple route to 2 via 1
3430 // Disable other paths
3431 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3432 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3433 short_channel_id: 12,
3435 flags: 2, // to disable
3436 cltv_expiry_delta: 0,
3437 htlc_minimum_msat: 0,
3438 htlc_maximum_msat: MAX_VALUE_MSAT,
3440 fee_proportional_millionths: 0,
3441 excess_data: Vec::new()
3443 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3444 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3445 short_channel_id: 3,
3447 flags: 2, // to disable
3448 cltv_expiry_delta: 0,
3449 htlc_minimum_msat: 0,
3450 htlc_maximum_msat: MAX_VALUE_MSAT,
3452 fee_proportional_millionths: 0,
3453 excess_data: Vec::new()
3455 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3456 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3457 short_channel_id: 13,
3459 flags: 2, // to disable
3460 cltv_expiry_delta: 0,
3461 htlc_minimum_msat: 0,
3462 htlc_maximum_msat: MAX_VALUE_MSAT,
3464 fee_proportional_millionths: 0,
3465 excess_data: Vec::new()
3467 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3468 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3469 short_channel_id: 6,
3471 flags: 2, // to disable
3472 cltv_expiry_delta: 0,
3473 htlc_minimum_msat: 0,
3474 htlc_maximum_msat: MAX_VALUE_MSAT,
3476 fee_proportional_millionths: 0,
3477 excess_data: Vec::new()
3479 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3480 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3481 short_channel_id: 7,
3483 flags: 2, // to disable
3484 cltv_expiry_delta: 0,
3485 htlc_minimum_msat: 0,
3486 htlc_maximum_msat: MAX_VALUE_MSAT,
3488 fee_proportional_millionths: 0,
3489 excess_data: Vec::new()
3492 // Check against amount_to_transfer_over_msat.
3493 // Set minimal HTLC of 200_000_000 msat.
3494 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3495 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3496 short_channel_id: 2,
3499 cltv_expiry_delta: 0,
3500 htlc_minimum_msat: 200_000_000,
3501 htlc_maximum_msat: MAX_VALUE_MSAT,
3503 fee_proportional_millionths: 0,
3504 excess_data: Vec::new()
3507 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3509 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3510 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3511 short_channel_id: 4,
3514 cltv_expiry_delta: 0,
3515 htlc_minimum_msat: 0,
3516 htlc_maximum_msat: 199_999_999,
3518 fee_proportional_millionths: 0,
3519 excess_data: Vec::new()
3522 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3523 let route_params = RouteParameters::from_payment_params_and_value(
3524 payment_params, 199_999_999);
3525 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3526 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3527 &Default::default(), &random_seed_bytes) {
3528 assert_eq!(err, "Failed to find a path to the given destination");
3529 } else { panic!(); }
3531 // Lift the restriction on the first hop.
3532 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3533 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3534 short_channel_id: 2,
3537 cltv_expiry_delta: 0,
3538 htlc_minimum_msat: 0,
3539 htlc_maximum_msat: MAX_VALUE_MSAT,
3541 fee_proportional_millionths: 0,
3542 excess_data: Vec::new()
3545 // A payment above the minimum should pass
3546 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3547 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3548 assert_eq!(route.paths[0].hops.len(), 2);
3552 fn htlc_minimum_overpay_test() {
3553 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3554 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3555 let config = UserConfig::default();
3556 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3557 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3559 let scorer = ln_test_utils::TestScorer::new();
3560 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3561 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3563 // A route to node#2 via two paths.
3564 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3565 // Thus, they can't send 60 without overpaying.
3566 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3567 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3568 short_channel_id: 2,
3571 cltv_expiry_delta: 0,
3572 htlc_minimum_msat: 35_000,
3573 htlc_maximum_msat: 40_000,
3575 fee_proportional_millionths: 0,
3576 excess_data: Vec::new()
3578 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3579 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3580 short_channel_id: 12,
3583 cltv_expiry_delta: 0,
3584 htlc_minimum_msat: 35_000,
3585 htlc_maximum_msat: 40_000,
3587 fee_proportional_millionths: 0,
3588 excess_data: Vec::new()
3592 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3593 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3594 short_channel_id: 13,
3597 cltv_expiry_delta: 0,
3598 htlc_minimum_msat: 0,
3599 htlc_maximum_msat: MAX_VALUE_MSAT,
3601 fee_proportional_millionths: 0,
3602 excess_data: Vec::new()
3604 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3605 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3606 short_channel_id: 4,
3609 cltv_expiry_delta: 0,
3610 htlc_minimum_msat: 0,
3611 htlc_maximum_msat: MAX_VALUE_MSAT,
3613 fee_proportional_millionths: 0,
3614 excess_data: Vec::new()
3617 // Disable other paths
3618 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3619 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3620 short_channel_id: 1,
3622 flags: 2, // to disable
3623 cltv_expiry_delta: 0,
3624 htlc_minimum_msat: 0,
3625 htlc_maximum_msat: MAX_VALUE_MSAT,
3627 fee_proportional_millionths: 0,
3628 excess_data: Vec::new()
3631 let mut route_params = RouteParameters::from_payment_params_and_value(
3632 payment_params.clone(), 60_000);
3633 route_params.max_total_routing_fee_msat = Some(15_000);
3634 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3635 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3636 // Overpay fees to hit htlc_minimum_msat.
3637 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3638 // TODO: this could be better balanced to overpay 10k and not 15k.
3639 assert_eq!(overpaid_fees, 15_000);
3641 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3642 // while taking even more fee to match htlc_minimum_msat.
3643 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3644 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3645 short_channel_id: 12,
3648 cltv_expiry_delta: 0,
3649 htlc_minimum_msat: 65_000,
3650 htlc_maximum_msat: 80_000,
3652 fee_proportional_millionths: 0,
3653 excess_data: Vec::new()
3655 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3656 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3657 short_channel_id: 2,
3660 cltv_expiry_delta: 0,
3661 htlc_minimum_msat: 0,
3662 htlc_maximum_msat: MAX_VALUE_MSAT,
3664 fee_proportional_millionths: 0,
3665 excess_data: Vec::new()
3667 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3668 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3669 short_channel_id: 4,
3672 cltv_expiry_delta: 0,
3673 htlc_minimum_msat: 0,
3674 htlc_maximum_msat: MAX_VALUE_MSAT,
3676 fee_proportional_millionths: 100_000,
3677 excess_data: Vec::new()
3680 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3681 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3682 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3683 assert_eq!(route.paths.len(), 1);
3684 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3685 let fees = route.paths[0].hops[0].fee_msat;
3686 assert_eq!(fees, 5_000);
3688 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3689 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3690 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3691 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3692 // the other channel.
3693 assert_eq!(route.paths.len(), 1);
3694 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3695 let fees = route.paths[0].hops[0].fee_msat;
3696 assert_eq!(fees, 5_000);
3700 fn htlc_minimum_recipient_overpay_test() {
3701 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3702 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3703 let config = UserConfig::default();
3704 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3705 let scorer = ln_test_utils::TestScorer::new();
3706 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3707 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3709 // Route to node2 over a single path which requires overpaying the recipient themselves.
3711 // First disable all paths except the us -> node1 -> node2 path
3712 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3713 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3714 short_channel_id: 13,
3717 cltv_expiry_delta: 0,
3718 htlc_minimum_msat: 0,
3719 htlc_maximum_msat: 0,
3721 fee_proportional_millionths: 0,
3722 excess_data: Vec::new()
3725 // Set channel 4 to free but with a high htlc_minimum_msat
3726 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3727 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3728 short_channel_id: 4,
3731 cltv_expiry_delta: 0,
3732 htlc_minimum_msat: 15_000,
3733 htlc_maximum_msat: MAX_VALUE_MSAT,
3735 fee_proportional_millionths: 0,
3736 excess_data: Vec::new()
3739 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3740 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3741 // what we try to find a route for, so this test only just happens to work out to exactly
3743 let mut route_params = RouteParameters::from_payment_params_and_value(
3744 payment_params.clone(), 5_000);
3745 route_params.max_total_routing_fee_msat = Some(9_999);
3746 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3747 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3748 &Default::default(), &random_seed_bytes) {
3749 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3750 } else { panic!(); }
3752 let mut route_params = RouteParameters::from_payment_params_and_value(
3753 payment_params.clone(), 5_000);
3754 route_params.max_total_routing_fee_msat = Some(10_000);
3755 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3756 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3757 assert_eq!(route.get_total_fees(), 10_000);
3761 fn disable_channels_test() {
3762 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3763 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3764 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3765 let scorer = ln_test_utils::TestScorer::new();
3766 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3767 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3769 // // Disable channels 4 and 12 by flags=2
3770 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3771 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3772 short_channel_id: 4,
3774 flags: 2, // to disable
3775 cltv_expiry_delta: 0,
3776 htlc_minimum_msat: 0,
3777 htlc_maximum_msat: MAX_VALUE_MSAT,
3779 fee_proportional_millionths: 0,
3780 excess_data: Vec::new()
3782 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3783 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3784 short_channel_id: 12,
3786 flags: 2, // to disable
3787 cltv_expiry_delta: 0,
3788 htlc_minimum_msat: 0,
3789 htlc_maximum_msat: MAX_VALUE_MSAT,
3791 fee_proportional_millionths: 0,
3792 excess_data: Vec::new()
3795 // If all the channels require some features we don't understand, route should fail
3796 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3797 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3798 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3799 &Default::default(), &random_seed_bytes) {
3800 assert_eq!(err, "Failed to find a path to the given destination");
3801 } else { panic!(); }
3803 // If we specify a channel to node7, that overrides our local channel view and that gets used
3804 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3805 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3806 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3807 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3808 &Default::default(), &random_seed_bytes).unwrap();
3809 assert_eq!(route.paths[0].hops.len(), 2);
3811 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3812 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3813 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3814 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3815 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3816 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3818 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3819 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3820 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3821 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3822 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3823 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3827 fn disable_node_test() {
3828 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3829 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3830 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3831 let scorer = ln_test_utils::TestScorer::new();
3832 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3833 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3835 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3836 let mut unknown_features = NodeFeatures::empty();
3837 unknown_features.set_unknown_feature_required();
3838 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3839 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3840 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3842 // If all nodes require some features we don't understand, route should fail
3843 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3844 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3845 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3846 &Default::default(), &random_seed_bytes) {
3847 assert_eq!(err, "Failed to find a path to the given destination");
3848 } else { panic!(); }
3850 // If we specify a channel to node7, that overrides our local channel view and that gets used
3851 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3852 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3853 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3854 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3855 &Default::default(), &random_seed_bytes).unwrap();
3856 assert_eq!(route.paths[0].hops.len(), 2);
3858 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3859 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3860 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3861 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3862 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3863 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3865 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3866 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3867 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3868 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3869 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3870 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3872 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3873 // naively) assume that the user checked the feature bits on the invoice, which override
3874 // the node_announcement.
3878 fn our_chans_test() {
3879 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3880 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3881 let scorer = ln_test_utils::TestScorer::new();
3882 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3883 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3885 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3886 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3887 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3888 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3889 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3890 assert_eq!(route.paths[0].hops.len(), 3);
3892 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3893 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3894 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3895 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3896 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3897 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3899 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3900 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3901 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3902 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3903 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3904 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3906 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3907 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3908 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3909 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3910 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3911 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3913 // If we specify a channel to node7, that overrides our local channel view and that gets used
3914 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3915 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3916 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3917 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3918 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3919 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3920 &Default::default(), &random_seed_bytes).unwrap();
3921 assert_eq!(route.paths[0].hops.len(), 2);
3923 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3924 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3925 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3926 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3927 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3928 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3930 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3931 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3932 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3933 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3934 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3935 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3938 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3939 let zero_fees = RoutingFees {
3941 proportional_millionths: 0,
3943 vec![RouteHint(vec![RouteHintHop {
3944 src_node_id: nodes[3],
3945 short_channel_id: 8,
3947 cltv_expiry_delta: (8 << 4) | 1,
3948 htlc_minimum_msat: None,
3949 htlc_maximum_msat: None,
3951 ]), RouteHint(vec![RouteHintHop {
3952 src_node_id: nodes[4],
3953 short_channel_id: 9,
3956 proportional_millionths: 0,
3958 cltv_expiry_delta: (9 << 4) | 1,
3959 htlc_minimum_msat: None,
3960 htlc_maximum_msat: None,
3961 }]), RouteHint(vec![RouteHintHop {
3962 src_node_id: nodes[5],
3963 short_channel_id: 10,
3965 cltv_expiry_delta: (10 << 4) | 1,
3966 htlc_minimum_msat: None,
3967 htlc_maximum_msat: None,
3971 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3972 let zero_fees = RoutingFees {
3974 proportional_millionths: 0,
3976 vec![RouteHint(vec![RouteHintHop {
3977 src_node_id: nodes[2],
3978 short_channel_id: 5,
3981 proportional_millionths: 0,
3983 cltv_expiry_delta: (5 << 4) | 1,
3984 htlc_minimum_msat: None,
3985 htlc_maximum_msat: None,
3987 src_node_id: nodes[3],
3988 short_channel_id: 8,
3990 cltv_expiry_delta: (8 << 4) | 1,
3991 htlc_minimum_msat: None,
3992 htlc_maximum_msat: None,
3994 ]), RouteHint(vec![RouteHintHop {
3995 src_node_id: nodes[4],
3996 short_channel_id: 9,
3999 proportional_millionths: 0,
4001 cltv_expiry_delta: (9 << 4) | 1,
4002 htlc_minimum_msat: None,
4003 htlc_maximum_msat: None,
4004 }]), RouteHint(vec![RouteHintHop {
4005 src_node_id: nodes[5],
4006 short_channel_id: 10,
4008 cltv_expiry_delta: (10 << 4) | 1,
4009 htlc_minimum_msat: None,
4010 htlc_maximum_msat: None,
4015 fn partial_route_hint_test() {
4016 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4017 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4018 let scorer = ln_test_utils::TestScorer::new();
4019 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4020 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4022 // Simple test across 2, 3, 5, and 4 via a last_hop channel
4023 // Tests the behaviour when the RouteHint contains a suboptimal hop.
4024 // RouteHint may be partially used by the algo to build the best path.
4026 // First check that last hop can't have its source as the payee.
4027 let invalid_last_hop = RouteHint(vec![RouteHintHop {
4028 src_node_id: nodes[6],
4029 short_channel_id: 8,
4032 proportional_millionths: 0,
4034 cltv_expiry_delta: (8 << 4) | 1,
4035 htlc_minimum_msat: None,
4036 htlc_maximum_msat: None,
4039 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
4040 invalid_last_hops.push(invalid_last_hop);
4042 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4043 .with_route_hints(invalid_last_hops).unwrap();
4044 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4045 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
4046 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
4047 &Default::default(), &random_seed_bytes) {
4048 assert_eq!(err, "Route hint cannot have the payee as the source.");
4049 } else { panic!(); }
4052 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4053 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
4054 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4055 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4056 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4057 assert_eq!(route.paths[0].hops.len(), 5);
4059 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4060 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4061 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4062 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4063 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4064 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4066 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4067 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4068 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4069 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4070 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4071 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4073 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4074 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4075 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4076 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4077 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4078 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4080 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4081 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4082 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4083 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4084 // If we have a peer in the node map, we'll use their features here since we don't have
4085 // a way of figuring out their features from the invoice:
4086 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4087 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4089 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4090 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4091 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4092 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4093 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4094 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4097 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4098 let zero_fees = RoutingFees {
4100 proportional_millionths: 0,
4102 vec![RouteHint(vec![RouteHintHop {
4103 src_node_id: nodes[3],
4104 short_channel_id: 8,
4106 cltv_expiry_delta: (8 << 4) | 1,
4107 htlc_minimum_msat: None,
4108 htlc_maximum_msat: None,
4109 }]), RouteHint(vec![
4111 ]), RouteHint(vec![RouteHintHop {
4112 src_node_id: nodes[5],
4113 short_channel_id: 10,
4115 cltv_expiry_delta: (10 << 4) | 1,
4116 htlc_minimum_msat: None,
4117 htlc_maximum_msat: None,
4122 fn ignores_empty_last_hops_test() {
4123 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4124 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4125 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
4126 let scorer = ln_test_utils::TestScorer::new();
4127 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4128 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4130 // Test handling of an empty RouteHint passed in Invoice.
4131 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4132 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4133 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4134 assert_eq!(route.paths[0].hops.len(), 5);
4136 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4137 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4138 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4139 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4140 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4141 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4143 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4144 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4145 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4146 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4147 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4148 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4150 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4151 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4152 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4153 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4154 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4155 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4157 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4158 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4159 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4160 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4161 // If we have a peer in the node map, we'll use their features here since we don't have
4162 // a way of figuring out their features from the invoice:
4163 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4164 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4166 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4167 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4168 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4169 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4170 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4171 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4174 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
4176 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
4177 let zero_fees = RoutingFees {
4179 proportional_millionths: 0,
4181 vec![RouteHint(vec![RouteHintHop {
4182 src_node_id: hint_hops[0],
4183 short_channel_id: 0xff00,
4186 proportional_millionths: 0,
4188 cltv_expiry_delta: (5 << 4) | 1,
4189 htlc_minimum_msat: None,
4190 htlc_maximum_msat: None,
4192 src_node_id: hint_hops[1],
4193 short_channel_id: 0xff01,
4195 cltv_expiry_delta: (8 << 4) | 1,
4196 htlc_minimum_msat: None,
4197 htlc_maximum_msat: None,
4202 fn multi_hint_last_hops_test() {
4203 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4204 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4205 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
4206 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4207 let scorer = ln_test_utils::TestScorer::new();
4208 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4209 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4210 // Test through channels 2, 3, 0xff00, 0xff01.
4211 // Test shows that multiple hop hints are considered.
4213 // Disabling channels 6 & 7 by flags=2
4214 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4215 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4216 short_channel_id: 6,
4218 flags: 2, // to disable
4219 cltv_expiry_delta: 0,
4220 htlc_minimum_msat: 0,
4221 htlc_maximum_msat: MAX_VALUE_MSAT,
4223 fee_proportional_millionths: 0,
4224 excess_data: Vec::new()
4226 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4227 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4228 short_channel_id: 7,
4230 flags: 2, // to disable
4231 cltv_expiry_delta: 0,
4232 htlc_minimum_msat: 0,
4233 htlc_maximum_msat: MAX_VALUE_MSAT,
4235 fee_proportional_millionths: 0,
4236 excess_data: Vec::new()
4239 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4240 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4241 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4242 assert_eq!(route.paths[0].hops.len(), 4);
4244 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4245 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4246 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4247 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4248 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4249 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4251 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4252 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4253 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4254 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4255 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4256 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4258 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4259 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4260 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4261 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4262 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4263 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4265 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4266 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4267 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4268 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4269 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4270 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4274 fn private_multi_hint_last_hops_test() {
4275 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4276 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4278 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4279 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4281 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4282 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4283 let scorer = ln_test_utils::TestScorer::new();
4284 // Test through channels 2, 3, 0xff00, 0xff01.
4285 // Test shows that multiple hop hints are considered.
4287 // Disabling channels 6 & 7 by flags=2
4288 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4289 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4290 short_channel_id: 6,
4292 flags: 2, // to disable
4293 cltv_expiry_delta: 0,
4294 htlc_minimum_msat: 0,
4295 htlc_maximum_msat: MAX_VALUE_MSAT,
4297 fee_proportional_millionths: 0,
4298 excess_data: Vec::new()
4300 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4301 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4302 short_channel_id: 7,
4304 flags: 2, // to disable
4305 cltv_expiry_delta: 0,
4306 htlc_minimum_msat: 0,
4307 htlc_maximum_msat: MAX_VALUE_MSAT,
4309 fee_proportional_millionths: 0,
4310 excess_data: Vec::new()
4313 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4314 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4315 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4316 assert_eq!(route.paths[0].hops.len(), 4);
4318 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4319 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4320 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4321 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4322 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4323 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4325 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4326 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4327 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4328 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4329 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4330 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4332 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4333 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4334 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4335 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4336 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4337 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4339 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4340 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4341 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4342 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4343 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4344 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4347 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4348 let zero_fees = RoutingFees {
4350 proportional_millionths: 0,
4352 vec![RouteHint(vec![RouteHintHop {
4353 src_node_id: nodes[4],
4354 short_channel_id: 11,
4356 cltv_expiry_delta: (11 << 4) | 1,
4357 htlc_minimum_msat: None,
4358 htlc_maximum_msat: None,
4360 src_node_id: nodes[3],
4361 short_channel_id: 8,
4363 cltv_expiry_delta: (8 << 4) | 1,
4364 htlc_minimum_msat: None,
4365 htlc_maximum_msat: None,
4366 }]), RouteHint(vec![RouteHintHop {
4367 src_node_id: nodes[4],
4368 short_channel_id: 9,
4371 proportional_millionths: 0,
4373 cltv_expiry_delta: (9 << 4) | 1,
4374 htlc_minimum_msat: None,
4375 htlc_maximum_msat: None,
4376 }]), RouteHint(vec![RouteHintHop {
4377 src_node_id: nodes[5],
4378 short_channel_id: 10,
4380 cltv_expiry_delta: (10 << 4) | 1,
4381 htlc_minimum_msat: None,
4382 htlc_maximum_msat: None,
4387 fn last_hops_with_public_channel_test() {
4388 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4389 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4390 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4391 let scorer = ln_test_utils::TestScorer::new();
4392 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4393 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4394 // This test shows that public routes can be present in the invoice
4395 // which would be handled in the same manner.
4397 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4398 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4399 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4400 assert_eq!(route.paths[0].hops.len(), 5);
4402 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4403 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4404 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4405 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4406 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4407 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4409 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4410 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4411 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4412 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4413 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4414 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4416 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4417 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4418 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4419 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4420 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4421 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4423 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4424 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4425 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4426 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4427 // If we have a peer in the node map, we'll use their features here since we don't have
4428 // a way of figuring out their features from the invoice:
4429 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4430 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4432 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4433 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4434 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4435 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4436 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4437 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4441 fn our_chans_last_hop_connect_test() {
4442 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4443 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4444 let scorer = ln_test_utils::TestScorer::new();
4445 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4446 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4448 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4449 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4450 let mut last_hops = last_hops(&nodes);
4451 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4452 .with_route_hints(last_hops.clone()).unwrap();
4453 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4454 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4455 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4456 &Default::default(), &random_seed_bytes).unwrap();
4457 assert_eq!(route.paths[0].hops.len(), 2);
4459 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4460 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4461 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4462 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4463 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4464 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4466 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4467 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4468 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4469 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4470 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4471 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4473 last_hops[0].0[0].fees.base_msat = 1000;
4475 // Revert to via 6 as the fee on 8 goes up
4476 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4477 .with_route_hints(last_hops).unwrap();
4478 let route_params = RouteParameters::from_payment_params_and_value(
4479 payment_params.clone(), 100);
4480 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4481 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4482 assert_eq!(route.paths[0].hops.len(), 4);
4484 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4485 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4486 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4487 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4488 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4489 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4491 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4492 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4493 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4494 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4495 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4496 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4498 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4499 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4500 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4501 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4502 // If we have a peer in the node map, we'll use their features here since we don't have
4503 // a way of figuring out their features from the invoice:
4504 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4505 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4507 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4508 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4509 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4510 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4511 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4512 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4514 // ...but still use 8 for larger payments as 6 has a variable feerate
4515 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4516 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4517 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4518 assert_eq!(route.paths[0].hops.len(), 5);
4520 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4521 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4522 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4523 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4524 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4525 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4527 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4528 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4529 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4530 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4531 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4532 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4534 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4535 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4536 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4537 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4538 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4539 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4541 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4542 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4543 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4544 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4545 // If we have a peer in the node map, we'll use their features here since we don't have
4546 // a way of figuring out their features from the invoice:
4547 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4548 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4550 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4551 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4552 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4553 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4554 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4555 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4558 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> {
4559 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4560 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4561 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4563 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4564 let last_hops = RouteHint(vec![RouteHintHop {
4565 src_node_id: middle_node_id,
4566 short_channel_id: 8,
4569 proportional_millionths: last_hop_fee_prop,
4571 cltv_expiry_delta: (8 << 4) | 1,
4572 htlc_minimum_msat: None,
4573 htlc_maximum_msat: last_hop_htlc_max,
4575 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4576 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4577 let scorer = ln_test_utils::TestScorer::new();
4578 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4579 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4580 let logger = ln_test_utils::TestLogger::new();
4581 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4582 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4583 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4584 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4585 &random_seed_bytes);
4590 fn unannounced_path_test() {
4591 // We should be able to send a payment to a destination without any help of a routing graph
4592 // if we have a channel with a common counterparty that appears in the first and last hop
4594 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4596 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4597 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4598 assert_eq!(route.paths[0].hops.len(), 2);
4600 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4601 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4602 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4603 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4604 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4605 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4607 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4608 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4609 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4610 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4611 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4612 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4616 fn overflow_unannounced_path_test_liquidity_underflow() {
4617 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4618 // the last-hop had a fee which overflowed a u64, we'd panic.
4619 // This was due to us adding the first-hop from us unconditionally, causing us to think
4620 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4621 // In this test, we previously hit a subtraction underflow due to having less available
4622 // liquidity at the last hop than 0.
4623 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());
4627 fn overflow_unannounced_path_test_feerate_overflow() {
4628 // This tests for the same case as above, except instead of hitting a subtraction
4629 // underflow, we hit a case where the fee charged at a hop overflowed.
4630 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());
4634 fn available_amount_while_routing_test() {
4635 // Tests whether we choose the correct available channel amount while routing.
4637 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4638 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4639 let scorer = ln_test_utils::TestScorer::new();
4640 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4641 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4642 let config = UserConfig::default();
4643 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4644 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4647 // We will use a simple single-path route from
4648 // our node to node2 via node0: channels {1, 3}.
4650 // First disable all other paths.
4651 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4652 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4653 short_channel_id: 2,
4656 cltv_expiry_delta: 0,
4657 htlc_minimum_msat: 0,
4658 htlc_maximum_msat: 100_000,
4660 fee_proportional_millionths: 0,
4661 excess_data: Vec::new()
4663 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4664 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4665 short_channel_id: 12,
4668 cltv_expiry_delta: 0,
4669 htlc_minimum_msat: 0,
4670 htlc_maximum_msat: 100_000,
4672 fee_proportional_millionths: 0,
4673 excess_data: Vec::new()
4676 // Make the first channel (#1) very permissive,
4677 // and we will be testing all limits on the second channel.
4678 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4679 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4680 short_channel_id: 1,
4683 cltv_expiry_delta: 0,
4684 htlc_minimum_msat: 0,
4685 htlc_maximum_msat: 1_000_000_000,
4687 fee_proportional_millionths: 0,
4688 excess_data: Vec::new()
4691 // First, let's see if routing works if we have absolutely no idea about the available amount.
4692 // In this case, it should be set to 250_000 sats.
4693 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4694 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4695 short_channel_id: 3,
4698 cltv_expiry_delta: 0,
4699 htlc_minimum_msat: 0,
4700 htlc_maximum_msat: 250_000_000,
4702 fee_proportional_millionths: 0,
4703 excess_data: Vec::new()
4707 // Attempt to route more than available results in a failure.
4708 let route_params = RouteParameters::from_payment_params_and_value(
4709 payment_params.clone(), 250_000_001);
4710 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4711 &our_id, &route_params, &network_graph.read_only(), None,
4712 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4713 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4714 } else { panic!(); }
4718 // Now, attempt to route an exact amount we have should be fine.
4719 let route_params = RouteParameters::from_payment_params_and_value(
4720 payment_params.clone(), 250_000_000);
4721 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4722 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4723 assert_eq!(route.paths.len(), 1);
4724 let path = route.paths.last().unwrap();
4725 assert_eq!(path.hops.len(), 2);
4726 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4727 assert_eq!(path.final_value_msat(), 250_000_000);
4730 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4731 // Disable channel #1 and use another first hop.
4732 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4733 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4734 short_channel_id: 1,
4737 cltv_expiry_delta: 0,
4738 htlc_minimum_msat: 0,
4739 htlc_maximum_msat: 1_000_000_000,
4741 fee_proportional_millionths: 0,
4742 excess_data: Vec::new()
4745 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4746 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4749 // Attempt to route more than available results in a failure.
4750 let route_params = RouteParameters::from_payment_params_and_value(
4751 payment_params.clone(), 200_000_001);
4752 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4753 &our_id, &route_params, &network_graph.read_only(),
4754 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4755 &Default::default(), &random_seed_bytes) {
4756 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4757 } else { panic!(); }
4761 // Now, attempt to route an exact amount we have should be fine.
4762 let route_params = RouteParameters::from_payment_params_and_value(
4763 payment_params.clone(), 200_000_000);
4764 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4765 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4766 &Default::default(), &random_seed_bytes).unwrap();
4767 assert_eq!(route.paths.len(), 1);
4768 let path = route.paths.last().unwrap();
4769 assert_eq!(path.hops.len(), 2);
4770 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4771 assert_eq!(path.final_value_msat(), 200_000_000);
4774 // Enable channel #1 back.
4775 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4776 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4777 short_channel_id: 1,
4780 cltv_expiry_delta: 0,
4781 htlc_minimum_msat: 0,
4782 htlc_maximum_msat: 1_000_000_000,
4784 fee_proportional_millionths: 0,
4785 excess_data: Vec::new()
4789 // Now let's see if routing works if we know only htlc_maximum_msat.
4790 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4791 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4792 short_channel_id: 3,
4795 cltv_expiry_delta: 0,
4796 htlc_minimum_msat: 0,
4797 htlc_maximum_msat: 15_000,
4799 fee_proportional_millionths: 0,
4800 excess_data: Vec::new()
4804 // Attempt to route more than available results in a failure.
4805 let route_params = RouteParameters::from_payment_params_and_value(
4806 payment_params.clone(), 15_001);
4807 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4808 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4809 &scorer, &Default::default(), &random_seed_bytes) {
4810 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4811 } else { panic!(); }
4815 // Now, attempt to route an exact amount we have should be fine.
4816 let route_params = RouteParameters::from_payment_params_and_value(
4817 payment_params.clone(), 15_000);
4818 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4819 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4820 assert_eq!(route.paths.len(), 1);
4821 let path = route.paths.last().unwrap();
4822 assert_eq!(path.hops.len(), 2);
4823 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4824 assert_eq!(path.final_value_msat(), 15_000);
4827 // Now let's see if routing works if we know only capacity from the UTXO.
4829 // We can't change UTXO capacity on the fly, so we'll disable
4830 // the existing channel and add another one with the capacity we need.
4831 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4832 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4833 short_channel_id: 3,
4836 cltv_expiry_delta: 0,
4837 htlc_minimum_msat: 0,
4838 htlc_maximum_msat: MAX_VALUE_MSAT,
4840 fee_proportional_millionths: 0,
4841 excess_data: Vec::new()
4844 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4845 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4846 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4847 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4848 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4850 *chain_monitor.utxo_ret.lock().unwrap() =
4851 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4852 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4854 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4855 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4856 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4857 short_channel_id: 333,
4860 cltv_expiry_delta: (3 << 4) | 1,
4861 htlc_minimum_msat: 0,
4862 htlc_maximum_msat: 15_000,
4864 fee_proportional_millionths: 0,
4865 excess_data: Vec::new()
4867 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4868 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4869 short_channel_id: 333,
4872 cltv_expiry_delta: (3 << 4) | 2,
4873 htlc_minimum_msat: 0,
4874 htlc_maximum_msat: 15_000,
4876 fee_proportional_millionths: 0,
4877 excess_data: Vec::new()
4881 // Attempt to route more than available results in a failure.
4882 let route_params = RouteParameters::from_payment_params_and_value(
4883 payment_params.clone(), 15_001);
4884 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4885 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4886 &scorer, &Default::default(), &random_seed_bytes) {
4887 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4888 } else { panic!(); }
4892 // Now, attempt to route an exact amount we have should be fine.
4893 let route_params = RouteParameters::from_payment_params_and_value(
4894 payment_params.clone(), 15_000);
4895 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4896 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4897 assert_eq!(route.paths.len(), 1);
4898 let path = route.paths.last().unwrap();
4899 assert_eq!(path.hops.len(), 2);
4900 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4901 assert_eq!(path.final_value_msat(), 15_000);
4904 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4905 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4906 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4907 short_channel_id: 333,
4910 cltv_expiry_delta: 0,
4911 htlc_minimum_msat: 0,
4912 htlc_maximum_msat: 10_000,
4914 fee_proportional_millionths: 0,
4915 excess_data: Vec::new()
4919 // Attempt to route more than available results in a failure.
4920 let route_params = RouteParameters::from_payment_params_and_value(
4921 payment_params.clone(), 10_001);
4922 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4923 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4924 &scorer, &Default::default(), &random_seed_bytes) {
4925 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4926 } else { panic!(); }
4930 // Now, attempt to route an exact amount we have should be fine.
4931 let route_params = RouteParameters::from_payment_params_and_value(
4932 payment_params.clone(), 10_000);
4933 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4934 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4935 assert_eq!(route.paths.len(), 1);
4936 let path = route.paths.last().unwrap();
4937 assert_eq!(path.hops.len(), 2);
4938 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4939 assert_eq!(path.final_value_msat(), 10_000);
4944 fn available_liquidity_last_hop_test() {
4945 // Check that available liquidity properly limits the path even when only
4946 // one of the latter hops is limited.
4947 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4948 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4949 let scorer = ln_test_utils::TestScorer::new();
4950 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4951 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4952 let config = UserConfig::default();
4953 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4954 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4957 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4958 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4959 // Total capacity: 50 sats.
4961 // Disable other potential paths.
4962 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4963 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4964 short_channel_id: 2,
4967 cltv_expiry_delta: 0,
4968 htlc_minimum_msat: 0,
4969 htlc_maximum_msat: 100_000,
4971 fee_proportional_millionths: 0,
4972 excess_data: Vec::new()
4974 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4975 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4976 short_channel_id: 7,
4979 cltv_expiry_delta: 0,
4980 htlc_minimum_msat: 0,
4981 htlc_maximum_msat: 100_000,
4983 fee_proportional_millionths: 0,
4984 excess_data: Vec::new()
4989 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4990 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4991 short_channel_id: 12,
4994 cltv_expiry_delta: 0,
4995 htlc_minimum_msat: 0,
4996 htlc_maximum_msat: 100_000,
4998 fee_proportional_millionths: 0,
4999 excess_data: Vec::new()
5001 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5002 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5003 short_channel_id: 13,
5006 cltv_expiry_delta: 0,
5007 htlc_minimum_msat: 0,
5008 htlc_maximum_msat: 100_000,
5010 fee_proportional_millionths: 0,
5011 excess_data: Vec::new()
5014 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5015 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5016 short_channel_id: 6,
5019 cltv_expiry_delta: 0,
5020 htlc_minimum_msat: 0,
5021 htlc_maximum_msat: 50_000,
5023 fee_proportional_millionths: 0,
5024 excess_data: Vec::new()
5026 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5027 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5028 short_channel_id: 11,
5031 cltv_expiry_delta: 0,
5032 htlc_minimum_msat: 0,
5033 htlc_maximum_msat: 100_000,
5035 fee_proportional_millionths: 0,
5036 excess_data: Vec::new()
5039 // Attempt to route more than available results in a failure.
5040 let route_params = RouteParameters::from_payment_params_and_value(
5041 payment_params.clone(), 60_000);
5042 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5043 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5044 &scorer, &Default::default(), &random_seed_bytes) {
5045 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5046 } else { panic!(); }
5050 // Now, attempt to route 49 sats (just a bit below the capacity).
5051 let route_params = RouteParameters::from_payment_params_and_value(
5052 payment_params.clone(), 49_000);
5053 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5054 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5055 assert_eq!(route.paths.len(), 1);
5056 let mut total_amount_paid_msat = 0;
5057 for path in &route.paths {
5058 assert_eq!(path.hops.len(), 4);
5059 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5060 total_amount_paid_msat += path.final_value_msat();
5062 assert_eq!(total_amount_paid_msat, 49_000);
5066 // Attempt to route an exact amount is also fine
5067 let route_params = RouteParameters::from_payment_params_and_value(
5068 payment_params, 50_000);
5069 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5070 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5071 assert_eq!(route.paths.len(), 1);
5072 let mut total_amount_paid_msat = 0;
5073 for path in &route.paths {
5074 assert_eq!(path.hops.len(), 4);
5075 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5076 total_amount_paid_msat += path.final_value_msat();
5078 assert_eq!(total_amount_paid_msat, 50_000);
5083 fn ignore_fee_first_hop_test() {
5084 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5085 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5086 let scorer = ln_test_utils::TestScorer::new();
5087 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5088 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5089 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5091 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5092 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5093 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5094 short_channel_id: 1,
5097 cltv_expiry_delta: 0,
5098 htlc_minimum_msat: 0,
5099 htlc_maximum_msat: 100_000,
5100 fee_base_msat: 1_000_000,
5101 fee_proportional_millionths: 0,
5102 excess_data: Vec::new()
5104 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5105 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5106 short_channel_id: 3,
5109 cltv_expiry_delta: 0,
5110 htlc_minimum_msat: 0,
5111 htlc_maximum_msat: 50_000,
5113 fee_proportional_millionths: 0,
5114 excess_data: Vec::new()
5118 let route_params = RouteParameters::from_payment_params_and_value(
5119 payment_params, 50_000);
5120 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5121 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5122 assert_eq!(route.paths.len(), 1);
5123 let mut total_amount_paid_msat = 0;
5124 for path in &route.paths {
5125 assert_eq!(path.hops.len(), 2);
5126 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5127 total_amount_paid_msat += path.final_value_msat();
5129 assert_eq!(total_amount_paid_msat, 50_000);
5134 fn simple_mpp_route_test() {
5135 let (secp_ctx, _, _, _, _) = build_graph();
5136 let (_, _, _, nodes) = get_nodes(&secp_ctx);
5137 let config = UserConfig::default();
5138 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5139 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5141 do_simple_mpp_route_test(clear_payment_params);
5143 // MPP to a 1-hop blinded path for nodes[2]
5144 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
5145 let blinded_path = BlindedPath {
5146 introduction_node: IntroductionNode::NodeId(nodes[2]),
5147 blinding_point: ln_test_utils::pubkey(42),
5148 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
5150 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
5152 fee_proportional_millionths: 0,
5153 htlc_minimum_msat: 0,
5154 htlc_maximum_msat: 0,
5155 cltv_expiry_delta: 0,
5156 features: BlindedHopFeatures::empty(),
5158 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
5159 .with_bolt12_features(bolt12_features.clone()).unwrap();
5160 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
5162 // MPP to 3 2-hop blinded paths
5163 let mut blinded_path_node_0 = blinded_path.clone();
5164 blinded_path_node_0.introduction_node = IntroductionNode::NodeId(nodes[0]);
5165 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
5166 let mut node_0_payinfo = blinded_payinfo.clone();
5167 node_0_payinfo.htlc_maximum_msat = 50_000;
5169 let mut blinded_path_node_7 = blinded_path_node_0.clone();
5170 blinded_path_node_7.introduction_node = IntroductionNode::NodeId(nodes[7]);
5171 let mut node_7_payinfo = blinded_payinfo.clone();
5172 node_7_payinfo.htlc_maximum_msat = 60_000;
5174 let mut blinded_path_node_1 = blinded_path_node_0.clone();
5175 blinded_path_node_1.introduction_node = IntroductionNode::NodeId(nodes[1]);
5176 let mut node_1_payinfo = blinded_payinfo.clone();
5177 node_1_payinfo.htlc_maximum_msat = 180_000;
5179 let two_hop_blinded_payment_params = PaymentParameters::blinded(
5181 (node_0_payinfo, blinded_path_node_0),
5182 (node_7_payinfo, blinded_path_node_7),
5183 (node_1_payinfo, blinded_path_node_1)
5185 .with_bolt12_features(bolt12_features).unwrap();
5186 do_simple_mpp_route_test(two_hop_blinded_payment_params);
5190 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
5191 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5192 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5193 let scorer = ln_test_utils::TestScorer::new();
5194 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5195 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5197 // We need a route consisting of 3 paths:
5198 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5199 // To achieve this, the amount being transferred should be around
5200 // the total capacity of these 3 paths.
5202 // First, we set limits on these (previously unlimited) channels.
5203 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
5205 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5206 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5207 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5208 short_channel_id: 1,
5211 cltv_expiry_delta: 0,
5212 htlc_minimum_msat: 0,
5213 htlc_maximum_msat: 100_000,
5215 fee_proportional_millionths: 0,
5216 excess_data: Vec::new()
5218 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5219 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5220 short_channel_id: 3,
5223 cltv_expiry_delta: 0,
5224 htlc_minimum_msat: 0,
5225 htlc_maximum_msat: 50_000,
5227 fee_proportional_millionths: 0,
5228 excess_data: Vec::new()
5231 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
5232 // (total limit 60).
5233 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5234 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5235 short_channel_id: 12,
5238 cltv_expiry_delta: 0,
5239 htlc_minimum_msat: 0,
5240 htlc_maximum_msat: 60_000,
5242 fee_proportional_millionths: 0,
5243 excess_data: Vec::new()
5245 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5246 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5247 short_channel_id: 13,
5250 cltv_expiry_delta: 0,
5251 htlc_minimum_msat: 0,
5252 htlc_maximum_msat: 60_000,
5254 fee_proportional_millionths: 0,
5255 excess_data: Vec::new()
5258 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5259 // (total capacity 180 sats).
5260 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5261 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5262 short_channel_id: 2,
5265 cltv_expiry_delta: 0,
5266 htlc_minimum_msat: 0,
5267 htlc_maximum_msat: 200_000,
5269 fee_proportional_millionths: 0,
5270 excess_data: Vec::new()
5272 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5273 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5274 short_channel_id: 4,
5277 cltv_expiry_delta: 0,
5278 htlc_minimum_msat: 0,
5279 htlc_maximum_msat: 180_000,
5281 fee_proportional_millionths: 0,
5282 excess_data: Vec::new()
5286 // Attempt to route more than available results in a failure.
5287 let route_params = RouteParameters::from_payment_params_and_value(
5288 payment_params.clone(), 300_000);
5289 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5290 &our_id, &route_params, &network_graph.read_only(), None,
5291 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5292 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5293 } else { panic!(); }
5297 // Attempt to route while setting max_path_count to 0 results in a failure.
5298 let zero_payment_params = payment_params.clone().with_max_path_count(0);
5299 let route_params = RouteParameters::from_payment_params_and_value(
5300 zero_payment_params, 100);
5301 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5302 &our_id, &route_params, &network_graph.read_only(), None,
5303 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5304 assert_eq!(err, "Can't find a route with no paths allowed.");
5305 } else { panic!(); }
5309 // Attempt to route while setting max_path_count to 3 results in a failure.
5310 // This is the case because the minimal_value_contribution_msat would require each path
5311 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5312 let fail_payment_params = payment_params.clone().with_max_path_count(3);
5313 let route_params = RouteParameters::from_payment_params_and_value(
5314 fail_payment_params, 250_000);
5315 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5316 &our_id, &route_params, &network_graph.read_only(), None,
5317 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5318 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5319 } else { panic!(); }
5323 // Now, attempt to route 250 sats (just a bit below the capacity).
5324 // Our algorithm should provide us with these 3 paths.
5325 let route_params = RouteParameters::from_payment_params_and_value(
5326 payment_params.clone(), 250_000);
5327 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5328 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5329 assert_eq!(route.paths.len(), 3);
5330 let mut total_amount_paid_msat = 0;
5331 for path in &route.paths {
5332 if let Some(bt) = &path.blinded_tail {
5333 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5335 assert_eq!(path.hops.len(), 2);
5336 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5338 total_amount_paid_msat += path.final_value_msat();
5340 assert_eq!(total_amount_paid_msat, 250_000);
5344 // Attempt to route an exact amount is also fine
5345 let route_params = RouteParameters::from_payment_params_and_value(
5346 payment_params.clone(), 290_000);
5347 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5348 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5349 assert_eq!(route.paths.len(), 3);
5350 let mut total_amount_paid_msat = 0;
5351 for path in &route.paths {
5352 if payment_params.payee.blinded_route_hints().len() != 0 {
5353 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5354 if let Some(bt) = &path.blinded_tail {
5355 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5356 if bt.hops.len() > 1 {
5357 let network_graph = network_graph.read_only();
5359 NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
5360 payment_params.payee.blinded_route_hints().iter()
5361 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5362 .and_then(|(_, p)| p.public_introduction_node_id(&network_graph))
5367 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5370 assert_eq!(path.hops.len(), 2);
5371 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5373 total_amount_paid_msat += path.final_value_msat();
5375 assert_eq!(total_amount_paid_msat, 290_000);
5380 fn long_mpp_route_test() {
5381 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5382 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5383 let scorer = ln_test_utils::TestScorer::new();
5384 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5385 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5386 let config = UserConfig::default();
5387 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5388 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5391 // We need a route consisting of 3 paths:
5392 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5393 // Note that these paths overlap (channels 5, 12, 13).
5394 // We will route 300 sats.
5395 // Each path will have 100 sats capacity, those channels which
5396 // are used twice will have 200 sats capacity.
5398 // Disable other potential paths.
5399 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5400 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5401 short_channel_id: 2,
5404 cltv_expiry_delta: 0,
5405 htlc_minimum_msat: 0,
5406 htlc_maximum_msat: 100_000,
5408 fee_proportional_millionths: 0,
5409 excess_data: Vec::new()
5411 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5412 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5413 short_channel_id: 7,
5416 cltv_expiry_delta: 0,
5417 htlc_minimum_msat: 0,
5418 htlc_maximum_msat: 100_000,
5420 fee_proportional_millionths: 0,
5421 excess_data: Vec::new()
5424 // Path via {node0, node2} is channels {1, 3, 5}.
5425 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5426 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5427 short_channel_id: 1,
5430 cltv_expiry_delta: 0,
5431 htlc_minimum_msat: 0,
5432 htlc_maximum_msat: 100_000,
5434 fee_proportional_millionths: 0,
5435 excess_data: Vec::new()
5437 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5438 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5439 short_channel_id: 3,
5442 cltv_expiry_delta: 0,
5443 htlc_minimum_msat: 0,
5444 htlc_maximum_msat: 100_000,
5446 fee_proportional_millionths: 0,
5447 excess_data: Vec::new()
5450 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5451 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5452 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5453 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5454 short_channel_id: 5,
5457 cltv_expiry_delta: 0,
5458 htlc_minimum_msat: 0,
5459 htlc_maximum_msat: 200_000,
5461 fee_proportional_millionths: 0,
5462 excess_data: Vec::new()
5465 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5466 // Add 100 sats to the capacities of {12, 13}, because these channels
5467 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5468 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5469 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5470 short_channel_id: 12,
5473 cltv_expiry_delta: 0,
5474 htlc_minimum_msat: 0,
5475 htlc_maximum_msat: 200_000,
5477 fee_proportional_millionths: 0,
5478 excess_data: Vec::new()
5480 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5481 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5482 short_channel_id: 13,
5485 cltv_expiry_delta: 0,
5486 htlc_minimum_msat: 0,
5487 htlc_maximum_msat: 200_000,
5489 fee_proportional_millionths: 0,
5490 excess_data: Vec::new()
5493 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5494 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5495 short_channel_id: 6,
5498 cltv_expiry_delta: 0,
5499 htlc_minimum_msat: 0,
5500 htlc_maximum_msat: 100_000,
5502 fee_proportional_millionths: 0,
5503 excess_data: Vec::new()
5505 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5506 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5507 short_channel_id: 11,
5510 cltv_expiry_delta: 0,
5511 htlc_minimum_msat: 0,
5512 htlc_maximum_msat: 100_000,
5514 fee_proportional_millionths: 0,
5515 excess_data: Vec::new()
5518 // Path via {node7, node2} is channels {12, 13, 5}.
5519 // We already limited them to 200 sats (they are used twice for 100 sats).
5520 // Nothing to do here.
5523 // Attempt to route more than available results in a failure.
5524 let route_params = RouteParameters::from_payment_params_and_value(
5525 payment_params.clone(), 350_000);
5526 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5527 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5528 &scorer, &Default::default(), &random_seed_bytes) {
5529 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5530 } else { panic!(); }
5534 // Now, attempt to route 300 sats (exact amount we can route).
5535 // Our algorithm should provide us with these 3 paths, 100 sats each.
5536 let route_params = RouteParameters::from_payment_params_and_value(
5537 payment_params, 300_000);
5538 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5539 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5540 assert_eq!(route.paths.len(), 3);
5542 let mut total_amount_paid_msat = 0;
5543 for path in &route.paths {
5544 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5545 total_amount_paid_msat += path.final_value_msat();
5547 assert_eq!(total_amount_paid_msat, 300_000);
5553 fn mpp_cheaper_route_test() {
5554 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5555 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5556 let scorer = ln_test_utils::TestScorer::new();
5557 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5558 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5559 let config = UserConfig::default();
5560 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5561 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5564 // This test checks that if we have two cheaper paths and one more expensive path,
5565 // so that liquidity-wise any 2 of 3 combination is sufficient,
5566 // two cheaper paths will be taken.
5567 // These paths have equal available liquidity.
5569 // We need a combination of 3 paths:
5570 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5571 // Note that these paths overlap (channels 5, 12, 13).
5572 // Each path will have 100 sats capacity, those channels which
5573 // are used twice will have 200 sats capacity.
5575 // Disable other potential paths.
5576 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5577 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5578 short_channel_id: 2,
5581 cltv_expiry_delta: 0,
5582 htlc_minimum_msat: 0,
5583 htlc_maximum_msat: 100_000,
5585 fee_proportional_millionths: 0,
5586 excess_data: Vec::new()
5588 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5589 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5590 short_channel_id: 7,
5593 cltv_expiry_delta: 0,
5594 htlc_minimum_msat: 0,
5595 htlc_maximum_msat: 100_000,
5597 fee_proportional_millionths: 0,
5598 excess_data: Vec::new()
5601 // Path via {node0, node2} is channels {1, 3, 5}.
5602 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5603 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5604 short_channel_id: 1,
5607 cltv_expiry_delta: 0,
5608 htlc_minimum_msat: 0,
5609 htlc_maximum_msat: 100_000,
5611 fee_proportional_millionths: 0,
5612 excess_data: Vec::new()
5614 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5615 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5616 short_channel_id: 3,
5619 cltv_expiry_delta: 0,
5620 htlc_minimum_msat: 0,
5621 htlc_maximum_msat: 100_000,
5623 fee_proportional_millionths: 0,
5624 excess_data: Vec::new()
5627 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5628 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5629 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5630 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5631 short_channel_id: 5,
5634 cltv_expiry_delta: 0,
5635 htlc_minimum_msat: 0,
5636 htlc_maximum_msat: 200_000,
5638 fee_proportional_millionths: 0,
5639 excess_data: Vec::new()
5642 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5643 // Add 100 sats to the capacities of {12, 13}, because these channels
5644 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5645 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5646 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5647 short_channel_id: 12,
5650 cltv_expiry_delta: 0,
5651 htlc_minimum_msat: 0,
5652 htlc_maximum_msat: 200_000,
5654 fee_proportional_millionths: 0,
5655 excess_data: Vec::new()
5657 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5658 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5659 short_channel_id: 13,
5662 cltv_expiry_delta: 0,
5663 htlc_minimum_msat: 0,
5664 htlc_maximum_msat: 200_000,
5666 fee_proportional_millionths: 0,
5667 excess_data: Vec::new()
5670 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5671 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5672 short_channel_id: 6,
5675 cltv_expiry_delta: 0,
5676 htlc_minimum_msat: 0,
5677 htlc_maximum_msat: 100_000,
5678 fee_base_msat: 1_000,
5679 fee_proportional_millionths: 0,
5680 excess_data: Vec::new()
5682 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5683 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5684 short_channel_id: 11,
5687 cltv_expiry_delta: 0,
5688 htlc_minimum_msat: 0,
5689 htlc_maximum_msat: 100_000,
5691 fee_proportional_millionths: 0,
5692 excess_data: Vec::new()
5695 // Path via {node7, node2} is channels {12, 13, 5}.
5696 // We already limited them to 200 sats (they are used twice for 100 sats).
5697 // Nothing to do here.
5700 // Now, attempt to route 180 sats.
5701 // Our algorithm should provide us with these 2 paths.
5702 let route_params = RouteParameters::from_payment_params_and_value(
5703 payment_params, 180_000);
5704 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5705 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5706 assert_eq!(route.paths.len(), 2);
5708 let mut total_value_transferred_msat = 0;
5709 let mut total_paid_msat = 0;
5710 for path in &route.paths {
5711 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5712 total_value_transferred_msat += path.final_value_msat();
5713 for hop in &path.hops {
5714 total_paid_msat += hop.fee_msat;
5717 // If we paid fee, this would be higher.
5718 assert_eq!(total_value_transferred_msat, 180_000);
5719 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5720 assert_eq!(total_fees_paid, 0);
5725 fn fees_on_mpp_route_test() {
5726 // This test makes sure that MPP algorithm properly takes into account
5727 // fees charged on the channels, by making the fees impactful:
5728 // if the fee is not properly accounted for, the behavior is different.
5729 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5730 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5731 let scorer = ln_test_utils::TestScorer::new();
5732 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5733 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5734 let config = UserConfig::default();
5735 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5736 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5739 // We need a route consisting of 2 paths:
5740 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5741 // We will route 200 sats, Each path will have 100 sats capacity.
5743 // This test is not particularly stable: e.g.,
5744 // there's a way to route via {node0, node2, node4}.
5745 // It works while pathfinding is deterministic, but can be broken otherwise.
5746 // It's fine to ignore this concern for now.
5748 // Disable other potential paths.
5749 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5750 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5751 short_channel_id: 2,
5754 cltv_expiry_delta: 0,
5755 htlc_minimum_msat: 0,
5756 htlc_maximum_msat: 100_000,
5758 fee_proportional_millionths: 0,
5759 excess_data: Vec::new()
5762 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5763 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5764 short_channel_id: 7,
5767 cltv_expiry_delta: 0,
5768 htlc_minimum_msat: 0,
5769 htlc_maximum_msat: 100_000,
5771 fee_proportional_millionths: 0,
5772 excess_data: Vec::new()
5775 // Path via {node0, node2} is channels {1, 3, 5}.
5776 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5777 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5778 short_channel_id: 1,
5781 cltv_expiry_delta: 0,
5782 htlc_minimum_msat: 0,
5783 htlc_maximum_msat: 100_000,
5785 fee_proportional_millionths: 0,
5786 excess_data: Vec::new()
5788 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5789 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5790 short_channel_id: 3,
5793 cltv_expiry_delta: 0,
5794 htlc_minimum_msat: 0,
5795 htlc_maximum_msat: 100_000,
5797 fee_proportional_millionths: 0,
5798 excess_data: Vec::new()
5801 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5802 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5803 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5804 short_channel_id: 5,
5807 cltv_expiry_delta: 0,
5808 htlc_minimum_msat: 0,
5809 htlc_maximum_msat: 100_000,
5811 fee_proportional_millionths: 0,
5812 excess_data: Vec::new()
5815 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5816 // All channels should be 100 sats capacity. But for the fee experiment,
5817 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5818 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5819 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5820 // so no matter how large are other channels,
5821 // the whole path will be limited by 100 sats with just these 2 conditions:
5822 // - channel 12 capacity is 250 sats
5823 // - fee for channel 6 is 150 sats
5824 // Let's test this by enforcing these 2 conditions and removing other limits.
5825 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5826 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5827 short_channel_id: 12,
5830 cltv_expiry_delta: 0,
5831 htlc_minimum_msat: 0,
5832 htlc_maximum_msat: 250_000,
5834 fee_proportional_millionths: 0,
5835 excess_data: Vec::new()
5837 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5838 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5839 short_channel_id: 13,
5842 cltv_expiry_delta: 0,
5843 htlc_minimum_msat: 0,
5844 htlc_maximum_msat: MAX_VALUE_MSAT,
5846 fee_proportional_millionths: 0,
5847 excess_data: Vec::new()
5850 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5851 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5852 short_channel_id: 6,
5855 cltv_expiry_delta: 0,
5856 htlc_minimum_msat: 0,
5857 htlc_maximum_msat: MAX_VALUE_MSAT,
5858 fee_base_msat: 150_000,
5859 fee_proportional_millionths: 0,
5860 excess_data: Vec::new()
5862 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5863 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5864 short_channel_id: 11,
5867 cltv_expiry_delta: 0,
5868 htlc_minimum_msat: 0,
5869 htlc_maximum_msat: MAX_VALUE_MSAT,
5871 fee_proportional_millionths: 0,
5872 excess_data: Vec::new()
5876 // Attempt to route more than available results in a failure.
5877 let route_params = RouteParameters::from_payment_params_and_value(
5878 payment_params.clone(), 210_000);
5879 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5880 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5881 &scorer, &Default::default(), &random_seed_bytes) {
5882 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5883 } else { panic!(); }
5887 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5888 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5889 max_total_routing_fee_msat: Some(149_999) };
5890 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5891 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5892 &scorer, &Default::default(), &random_seed_bytes) {
5893 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5894 } else { panic!(); }
5898 // Now, attempt to route 200 sats (exact amount we can route).
5899 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5900 max_total_routing_fee_msat: Some(150_000) };
5901 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5902 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5903 assert_eq!(route.paths.len(), 2);
5905 let mut total_amount_paid_msat = 0;
5906 for path in &route.paths {
5907 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5908 total_amount_paid_msat += path.final_value_msat();
5910 assert_eq!(total_amount_paid_msat, 200_000);
5911 assert_eq!(route.get_total_fees(), 150_000);
5916 fn mpp_with_last_hops() {
5917 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5918 // via a single last-hop route hint, we'd fail to route if we first collected routes
5919 // totaling close but not quite enough to fund the full payment.
5921 // This was because we considered last-hop hints to have exactly the sought payment amount
5922 // instead of the amount we were trying to collect, needlessly limiting our path searching
5923 // at the very first hop.
5925 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5926 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5927 // to only have the remaining to-collect amount in available liquidity.
5929 // This bug appeared in production in some specific channel configurations.
5930 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5931 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5932 let scorer = ln_test_utils::TestScorer::new();
5933 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5934 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5935 let config = UserConfig::default();
5936 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
5937 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
5938 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5939 src_node_id: nodes[2],
5940 short_channel_id: 42,
5941 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5942 cltv_expiry_delta: 42,
5943 htlc_minimum_msat: None,
5944 htlc_maximum_msat: None,
5945 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5947 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5948 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5949 // would first use the no-fee route and then fail to find a path along the second route as
5950 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5951 // under 5% of our payment amount.
5952 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5953 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5954 short_channel_id: 1,
5957 cltv_expiry_delta: (5 << 4) | 5,
5958 htlc_minimum_msat: 0,
5959 htlc_maximum_msat: 99_000,
5960 fee_base_msat: u32::max_value(),
5961 fee_proportional_millionths: u32::max_value(),
5962 excess_data: Vec::new()
5964 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5965 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5966 short_channel_id: 2,
5969 cltv_expiry_delta: (5 << 4) | 3,
5970 htlc_minimum_msat: 0,
5971 htlc_maximum_msat: 99_000,
5972 fee_base_msat: u32::max_value(),
5973 fee_proportional_millionths: u32::max_value(),
5974 excess_data: Vec::new()
5976 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5977 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5978 short_channel_id: 4,
5981 cltv_expiry_delta: (4 << 4) | 1,
5982 htlc_minimum_msat: 0,
5983 htlc_maximum_msat: MAX_VALUE_MSAT,
5985 fee_proportional_millionths: 0,
5986 excess_data: Vec::new()
5988 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5989 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5990 short_channel_id: 13,
5992 flags: 0|2, // Channel disabled
5993 cltv_expiry_delta: (13 << 4) | 1,
5994 htlc_minimum_msat: 0,
5995 htlc_maximum_msat: MAX_VALUE_MSAT,
5997 fee_proportional_millionths: 2000000,
5998 excess_data: Vec::new()
6001 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
6003 let route_params = RouteParameters::from_payment_params_and_value(
6004 payment_params, 100_000);
6005 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6006 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6007 assert_eq!(route.paths.len(), 2);
6008 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
6009 // Paths are manually ordered ordered by SCID, so:
6010 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
6011 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
6012 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
6013 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
6014 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
6015 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
6016 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
6017 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
6018 assert_eq!(route.get_total_fees(), 1);
6019 assert_eq!(route.get_total_amount(), 100_000);
6023 fn drop_lowest_channel_mpp_route_test() {
6024 // This test checks that low-capacity channel is dropped when after
6025 // path finding we realize that we found more capacity than we need.
6026 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6027 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6028 let scorer = ln_test_utils::TestScorer::new();
6029 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6030 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6031 let config = UserConfig::default();
6032 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6033 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6035 .with_max_channel_saturation_power_of_half(0);
6037 // We need a route consisting of 3 paths:
6038 // From our node to node2 via node0, node7, node1 (three paths one hop each).
6040 // The first and the second paths should be sufficient, but the third should be
6041 // cheaper, so that we select it but drop later.
6043 // First, we set limits on these (previously unlimited) channels.
6044 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
6046 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
6047 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6048 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6049 short_channel_id: 1,
6052 cltv_expiry_delta: 0,
6053 htlc_minimum_msat: 0,
6054 htlc_maximum_msat: 100_000,
6056 fee_proportional_millionths: 0,
6057 excess_data: Vec::new()
6059 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6060 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6061 short_channel_id: 3,
6064 cltv_expiry_delta: 0,
6065 htlc_minimum_msat: 0,
6066 htlc_maximum_msat: 50_000,
6068 fee_proportional_millionths: 0,
6069 excess_data: Vec::new()
6072 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
6073 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6074 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6075 short_channel_id: 12,
6078 cltv_expiry_delta: 0,
6079 htlc_minimum_msat: 0,
6080 htlc_maximum_msat: 60_000,
6082 fee_proportional_millionths: 0,
6083 excess_data: Vec::new()
6085 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6086 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6087 short_channel_id: 13,
6090 cltv_expiry_delta: 0,
6091 htlc_minimum_msat: 0,
6092 htlc_maximum_msat: 60_000,
6094 fee_proportional_millionths: 0,
6095 excess_data: Vec::new()
6098 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
6099 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6100 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6101 short_channel_id: 2,
6104 cltv_expiry_delta: 0,
6105 htlc_minimum_msat: 0,
6106 htlc_maximum_msat: 20_000,
6108 fee_proportional_millionths: 0,
6109 excess_data: Vec::new()
6111 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6112 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6113 short_channel_id: 4,
6116 cltv_expiry_delta: 0,
6117 htlc_minimum_msat: 0,
6118 htlc_maximum_msat: 20_000,
6120 fee_proportional_millionths: 0,
6121 excess_data: Vec::new()
6125 // Attempt to route more than available results in a failure.
6126 let route_params = RouteParameters::from_payment_params_and_value(
6127 payment_params.clone(), 150_000);
6128 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6129 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6130 &scorer, &Default::default(), &random_seed_bytes) {
6131 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6132 } else { panic!(); }
6136 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
6137 // Our algorithm should provide us with these 3 paths.
6138 let route_params = RouteParameters::from_payment_params_and_value(
6139 payment_params.clone(), 125_000);
6140 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6141 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6142 assert_eq!(route.paths.len(), 3);
6143 let mut total_amount_paid_msat = 0;
6144 for path in &route.paths {
6145 assert_eq!(path.hops.len(), 2);
6146 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6147 total_amount_paid_msat += path.final_value_msat();
6149 assert_eq!(total_amount_paid_msat, 125_000);
6153 // Attempt to route without the last small cheap channel
6154 let route_params = RouteParameters::from_payment_params_and_value(
6155 payment_params, 90_000);
6156 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6157 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6158 assert_eq!(route.paths.len(), 2);
6159 let mut total_amount_paid_msat = 0;
6160 for path in &route.paths {
6161 assert_eq!(path.hops.len(), 2);
6162 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6163 total_amount_paid_msat += path.final_value_msat();
6165 assert_eq!(total_amount_paid_msat, 90_000);
6170 fn min_criteria_consistency() {
6171 // Test that we don't use an inconsistent metric between updating and walking nodes during
6172 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
6173 // was updated with a different criterion from the heap sorting, resulting in loops in
6174 // calculated paths. We test for that specific case here.
6176 // We construct a network that looks like this:
6178 // node2 -1(3)2- node3
6182 // node1 -1(5)2- node4 -1(1)2- node6
6188 // We create a loop on the side of our real path - our destination is node 6, with a
6189 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
6190 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
6191 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
6192 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
6193 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
6194 // "previous hop" being set to node 3, creating a loop in the path.
6195 let secp_ctx = Secp256k1::new();
6196 let logger = Arc::new(ln_test_utils::TestLogger::new());
6197 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6198 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
6199 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6200 let scorer = ln_test_utils::TestScorer::new();
6201 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6202 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6203 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
6205 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
6206 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6207 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6208 short_channel_id: 6,
6211 cltv_expiry_delta: (6 << 4) | 0,
6212 htlc_minimum_msat: 0,
6213 htlc_maximum_msat: MAX_VALUE_MSAT,
6215 fee_proportional_millionths: 0,
6216 excess_data: Vec::new()
6218 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
6220 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6221 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6222 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6223 short_channel_id: 5,
6226 cltv_expiry_delta: (5 << 4) | 0,
6227 htlc_minimum_msat: 0,
6228 htlc_maximum_msat: MAX_VALUE_MSAT,
6230 fee_proportional_millionths: 0,
6231 excess_data: Vec::new()
6233 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
6235 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
6236 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6237 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6238 short_channel_id: 4,
6241 cltv_expiry_delta: (4 << 4) | 0,
6242 htlc_minimum_msat: 0,
6243 htlc_maximum_msat: MAX_VALUE_MSAT,
6245 fee_proportional_millionths: 0,
6246 excess_data: Vec::new()
6248 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6250 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6251 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
6252 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6253 short_channel_id: 3,
6256 cltv_expiry_delta: (3 << 4) | 0,
6257 htlc_minimum_msat: 0,
6258 htlc_maximum_msat: MAX_VALUE_MSAT,
6260 fee_proportional_millionths: 0,
6261 excess_data: Vec::new()
6263 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6265 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6266 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
6267 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6268 short_channel_id: 2,
6271 cltv_expiry_delta: (2 << 4) | 0,
6272 htlc_minimum_msat: 0,
6273 htlc_maximum_msat: MAX_VALUE_MSAT,
6275 fee_proportional_millionths: 0,
6276 excess_data: Vec::new()
6279 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6280 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6281 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6282 short_channel_id: 1,
6285 cltv_expiry_delta: (1 << 4) | 0,
6286 htlc_minimum_msat: 100,
6287 htlc_maximum_msat: MAX_VALUE_MSAT,
6289 fee_proportional_millionths: 0,
6290 excess_data: Vec::new()
6292 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6295 // Now ensure the route flows simply over nodes 1 and 4 to 6.
6296 let route_params = RouteParameters::from_payment_params_and_value(
6297 payment_params, 10_000);
6298 let route = get_route(&our_id, &route_params, &network.read_only(), None,
6299 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6300 assert_eq!(route.paths.len(), 1);
6301 assert_eq!(route.paths[0].hops.len(), 3);
6303 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6304 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6305 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6306 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6307 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6308 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6310 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6311 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6312 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6313 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6314 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6315 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6317 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6318 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6319 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6320 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6321 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6322 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6328 fn exact_fee_liquidity_limit() {
6329 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6330 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6331 // we calculated fees on a higher value, resulting in us ignoring such paths.
6332 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6333 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6334 let scorer = ln_test_utils::TestScorer::new();
6335 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6336 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6337 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6339 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6341 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6342 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6343 short_channel_id: 2,
6346 cltv_expiry_delta: 0,
6347 htlc_minimum_msat: 0,
6348 htlc_maximum_msat: 85_000,
6350 fee_proportional_millionths: 0,
6351 excess_data: Vec::new()
6354 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6355 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6356 short_channel_id: 12,
6359 cltv_expiry_delta: (4 << 4) | 1,
6360 htlc_minimum_msat: 0,
6361 htlc_maximum_msat: 270_000,
6363 fee_proportional_millionths: 1000000,
6364 excess_data: Vec::new()
6368 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6369 // 200% fee charged channel 13 in the 1-to-2 direction.
6370 let mut route_params = RouteParameters::from_payment_params_and_value(
6371 payment_params, 90_000);
6372 route_params.max_total_routing_fee_msat = Some(90_000*2);
6373 let route = get_route(&our_id, &route_params, &network_graph.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(), 2);
6378 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6379 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6380 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6381 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6382 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6383 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6385 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6386 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6387 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6388 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6389 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6390 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6395 fn htlc_max_reduction_below_min() {
6396 // Test that if, while walking the graph, we reduce the value being sent to meet an
6397 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6398 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6399 // resulting in us thinking there is no possible path, even if other paths exist.
6400 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6401 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6402 let scorer = ln_test_utils::TestScorer::new();
6403 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6404 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6405 let config = UserConfig::default();
6406 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6407 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6410 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6411 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6412 // then try to send 90_000.
6413 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6414 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6415 short_channel_id: 2,
6418 cltv_expiry_delta: 0,
6419 htlc_minimum_msat: 0,
6420 htlc_maximum_msat: 80_000,
6422 fee_proportional_millionths: 0,
6423 excess_data: Vec::new()
6425 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6426 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6427 short_channel_id: 4,
6430 cltv_expiry_delta: (4 << 4) | 1,
6431 htlc_minimum_msat: 90_000,
6432 htlc_maximum_msat: MAX_VALUE_MSAT,
6434 fee_proportional_millionths: 0,
6435 excess_data: Vec::new()
6439 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6440 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6441 // expensive) channels 12-13 path.
6442 let mut route_params = RouteParameters::from_payment_params_and_value(
6443 payment_params, 90_000);
6444 route_params.max_total_routing_fee_msat = Some(90_000*2);
6445 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6446 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6447 assert_eq!(route.paths.len(), 1);
6448 assert_eq!(route.paths[0].hops.len(), 2);
6450 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6451 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6452 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6453 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6454 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6455 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6457 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6458 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6459 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6460 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6461 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6462 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6467 fn multiple_direct_first_hops() {
6468 // Previously we'd only ever considered one first hop path per counterparty.
6469 // However, as we don't restrict users to one channel per peer, we really need to support
6470 // looking at all first hop paths.
6471 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6472 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6473 // route over multiple channels with the same first hop.
6474 let secp_ctx = Secp256k1::new();
6475 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6476 let logger = Arc::new(ln_test_utils::TestLogger::new());
6477 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6478 let scorer = ln_test_utils::TestScorer::new();
6479 let config = UserConfig::default();
6480 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6481 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6483 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6484 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6487 let route_params = RouteParameters::from_payment_params_and_value(
6488 payment_params.clone(), 100_000);
6489 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6490 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6491 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6492 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6493 assert_eq!(route.paths.len(), 1);
6494 assert_eq!(route.paths[0].hops.len(), 1);
6496 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6497 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6498 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6501 let route_params = RouteParameters::from_payment_params_and_value(
6502 payment_params.clone(), 100_000);
6503 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6504 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6505 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6506 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6507 assert_eq!(route.paths.len(), 2);
6508 assert_eq!(route.paths[0].hops.len(), 1);
6509 assert_eq!(route.paths[1].hops.len(), 1);
6511 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6512 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6514 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6515 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6517 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6518 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6522 // If we have a bunch of outbound channels to the same node, where most are not
6523 // sufficient to pay the full payment, but one is, we should default to just using the
6524 // one single channel that has sufficient balance, avoiding MPP.
6526 // If we have several options above the 3xpayment value threshold, we should pick the
6527 // smallest of them, avoiding further fragmenting our available outbound balance to
6529 let route_params = RouteParameters::from_payment_params_and_value(
6530 payment_params, 100_000);
6531 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6532 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6533 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6534 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6535 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6536 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6537 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6538 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6539 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6540 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6541 assert_eq!(route.paths.len(), 1);
6542 assert_eq!(route.paths[0].hops.len(), 1);
6544 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6545 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6546 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6551 fn prefers_shorter_route_with_higher_fees() {
6552 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6553 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6554 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6556 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6557 let scorer = ln_test_utils::TestScorer::new();
6558 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6559 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6560 let route_params = RouteParameters::from_payment_params_and_value(
6561 payment_params.clone(), 100);
6562 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6563 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6564 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6566 assert_eq!(route.get_total_fees(), 100);
6567 assert_eq!(route.get_total_amount(), 100);
6568 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6570 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6571 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6572 let scorer = FixedPenaltyScorer::with_penalty(100);
6573 let route_params = RouteParameters::from_payment_params_and_value(
6574 payment_params, 100);
6575 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6576 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6577 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6579 assert_eq!(route.get_total_fees(), 300);
6580 assert_eq!(route.get_total_amount(), 100);
6581 assert_eq!(path, vec![2, 4, 7, 10]);
6584 struct BadChannelScorer {
6585 short_channel_id: u64,
6589 impl Writeable for BadChannelScorer {
6590 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6592 impl ScoreLookUp for BadChannelScorer {
6593 type ScoreParams = ();
6594 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6595 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6599 struct BadNodeScorer {
6604 impl Writeable for BadNodeScorer {
6605 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6608 impl ScoreLookUp for BadNodeScorer {
6609 type ScoreParams = ();
6610 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6611 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6616 fn avoids_routing_through_bad_channels_and_nodes() {
6617 let (secp_ctx, network, _, _, logger) = build_graph();
6618 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6619 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6620 let network_graph = network.read_only();
6622 // A path to nodes[6] exists when no penalties are applied to any channel.
6623 let scorer = ln_test_utils::TestScorer::new();
6624 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6625 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6626 let route_params = RouteParameters::from_payment_params_and_value(
6627 payment_params, 100);
6628 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6629 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6630 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6632 assert_eq!(route.get_total_fees(), 100);
6633 assert_eq!(route.get_total_amount(), 100);
6634 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6636 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6637 let scorer = BadChannelScorer { short_channel_id: 6 };
6638 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6639 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6640 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6642 assert_eq!(route.get_total_fees(), 300);
6643 assert_eq!(route.get_total_amount(), 100);
6644 assert_eq!(path, vec![2, 4, 7, 10]);
6646 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6647 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6648 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6649 &scorer, &Default::default(), &random_seed_bytes) {
6650 Err(LightningError { err, .. } ) => {
6651 assert_eq!(err, "Failed to find a path to the given destination");
6653 Ok(_) => panic!("Expected error"),
6658 fn total_fees_single_path() {
6660 paths: vec![Path { hops: vec![
6662 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6663 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6664 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6667 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6668 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6669 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6672 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6673 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6674 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6676 ], blinded_tail: None }],
6680 assert_eq!(route.get_total_fees(), 250);
6681 assert_eq!(route.get_total_amount(), 225);
6685 fn total_fees_multi_path() {
6687 paths: vec![Path { hops: vec![
6689 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6690 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6691 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6694 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6695 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6696 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6698 ], blinded_tail: None }, Path { hops: vec![
6700 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6701 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6702 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6705 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6706 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6707 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6709 ], blinded_tail: None }],
6713 assert_eq!(route.get_total_fees(), 200);
6714 assert_eq!(route.get_total_amount(), 300);
6718 fn total_empty_route_no_panic() {
6719 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6720 // would both panic if the route was completely empty. We test to ensure they return 0
6721 // here, even though its somewhat nonsensical as a route.
6722 let route = Route { paths: Vec::new(), route_params: None };
6724 assert_eq!(route.get_total_fees(), 0);
6725 assert_eq!(route.get_total_amount(), 0);
6729 fn limits_total_cltv_delta() {
6730 let (secp_ctx, network, _, _, logger) = build_graph();
6731 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6732 let network_graph = network.read_only();
6734 let scorer = ln_test_utils::TestScorer::new();
6736 // Make sure that generally there is at least one route available
6737 let feasible_max_total_cltv_delta = 1008;
6738 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6739 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6740 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6741 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6742 let route_params = RouteParameters::from_payment_params_and_value(
6743 feasible_payment_params, 100);
6744 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6745 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6746 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6747 assert_ne!(path.len(), 0);
6749 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6750 let fail_max_total_cltv_delta = 23;
6751 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6752 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6753 let route_params = RouteParameters::from_payment_params_and_value(
6754 fail_payment_params, 100);
6755 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6756 &Default::default(), &random_seed_bytes)
6758 Err(LightningError { err, .. } ) => {
6759 assert_eq!(err, "Failed to find a path to the given destination");
6761 Ok(_) => panic!("Expected error"),
6766 fn avoids_recently_failed_paths() {
6767 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6768 // randomly inserting channels into it until we can't find a route anymore.
6769 let (secp_ctx, network, _, _, logger) = build_graph();
6770 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6771 let network_graph = network.read_only();
6773 let scorer = ln_test_utils::TestScorer::new();
6774 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6775 .with_max_path_count(1);
6776 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6777 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6779 // We should be able to find a route initially, and then after we fail a few random
6780 // channels eventually we won't be able to any longer.
6781 let route_params = RouteParameters::from_payment_params_and_value(
6782 payment_params.clone(), 100);
6783 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6784 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6786 let route_params = RouteParameters::from_payment_params_and_value(
6787 payment_params.clone(), 100);
6788 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6789 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6791 for chan in route.paths[0].hops.iter() {
6792 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6794 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6795 % route.paths[0].hops.len();
6796 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6802 fn limits_path_length() {
6803 let (secp_ctx, network, _, _, logger) = build_line_graph();
6804 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6805 let network_graph = network.read_only();
6807 let scorer = ln_test_utils::TestScorer::new();
6808 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6809 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6811 // First check we can actually create a long route on this graph.
6812 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6813 let route_params = RouteParameters::from_payment_params_and_value(
6814 feasible_payment_params, 100);
6815 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6816 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6817 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6818 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6820 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6821 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
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 adds_and_limits_cltv_offset() {
6836 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6837 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6839 let scorer = ln_test_utils::TestScorer::new();
6841 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6842 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6843 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6844 let route_params = RouteParameters::from_payment_params_and_value(
6845 payment_params.clone(), 100);
6846 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6847 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6848 assert_eq!(route.paths.len(), 1);
6850 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6852 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6853 let mut route_default = route.clone();
6854 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6855 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6856 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6857 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6858 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6860 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6861 let mut route_limited = route.clone();
6862 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6863 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6864 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6865 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6866 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6870 fn adds_plausible_cltv_offset() {
6871 let (secp_ctx, network, _, _, logger) = build_graph();
6872 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6873 let network_graph = network.read_only();
6874 let network_nodes = network_graph.nodes();
6875 let network_channels = network_graph.channels();
6876 let scorer = ln_test_utils::TestScorer::new();
6877 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6878 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6879 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6881 let route_params = RouteParameters::from_payment_params_and_value(
6882 payment_params.clone(), 100);
6883 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6884 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6885 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6887 let mut path_plausibility = vec![];
6889 for p in route.paths {
6890 // 1. Select random observation point
6891 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6892 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6894 prng.process_in_place(&mut random_bytes);
6895 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6896 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6898 // 2. Calculate what CLTV expiry delta we would observe there
6899 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6901 // 3. Starting from the observation point, find candidate paths
6902 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6903 candidates.push_back((observation_point, vec![]));
6905 let mut found_plausible_candidate = false;
6907 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6908 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6909 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6910 found_plausible_candidate = true;
6911 break 'candidate_loop;
6915 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6916 for channel_id in &cur_node.channels {
6917 if let Some(channel_info) = network_channels.get(&channel_id) {
6918 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6919 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6920 if cur_path_cltv_deltas.iter().sum::<u32>()
6921 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6922 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6923 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6924 candidates.push_back((*next_id, new_path_cltv_deltas));
6932 path_plausibility.push(found_plausible_candidate);
6934 assert!(path_plausibility.iter().all(|x| *x));
6938 fn builds_correct_path_from_hops() {
6939 let (secp_ctx, network, _, _, logger) = build_graph();
6940 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6941 let network_graph = network.read_only();
6943 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6944 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6946 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6947 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6948 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6949 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6950 Arc::clone(&logger), &random_seed_bytes).unwrap();
6951 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6952 assert_eq!(hops.len(), route.paths[0].hops.len());
6953 for (idx, hop_pubkey) in hops.iter().enumerate() {
6954 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6959 fn avoids_saturating_channels() {
6960 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6961 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6962 let decay_params = ProbabilisticScoringDecayParameters::default();
6963 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6965 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6966 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6967 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6968 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6969 short_channel_id: 4,
6972 cltv_expiry_delta: (4 << 4) | 1,
6973 htlc_minimum_msat: 0,
6974 htlc_maximum_msat: 250_000_000,
6976 fee_proportional_millionths: 0,
6977 excess_data: Vec::new()
6979 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6980 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6981 short_channel_id: 13,
6984 cltv_expiry_delta: (13 << 4) | 1,
6985 htlc_minimum_msat: 0,
6986 htlc_maximum_msat: 250_000_000,
6988 fee_proportional_millionths: 0,
6989 excess_data: Vec::new()
6992 let config = UserConfig::default();
6993 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6994 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6996 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6997 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6998 // 100,000 sats is less than the available liquidity on each channel, set above.
6999 let route_params = RouteParameters::from_payment_params_and_value(
7000 payment_params, 100_000_000);
7001 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
7002 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
7003 assert_eq!(route.paths.len(), 2);
7004 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
7005 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
7008 #[cfg(feature = "std")]
7009 pub(super) fn random_init_seed() -> u64 {
7010 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
7011 use core::hash::{BuildHasher, Hasher};
7012 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
7013 println!("Using seed of {}", seed);
7018 #[cfg(feature = "std")]
7019 fn generate_routes() {
7020 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
7022 let logger = ln_test_utils::TestLogger::new();
7023 let graph = match super::bench_utils::read_network_graph(&logger) {
7031 let params = ProbabilisticScoringFeeParameters::default();
7032 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
7033 let features = super::Bolt11InvoiceFeatures::empty();
7035 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7039 #[cfg(feature = "std")]
7040 fn generate_routes_mpp() {
7041 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
7043 let logger = ln_test_utils::TestLogger::new();
7044 let graph = match super::bench_utils::read_network_graph(&logger) {
7052 let params = ProbabilisticScoringFeeParameters::default();
7053 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
7054 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7056 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7060 #[cfg(feature = "std")]
7061 fn generate_large_mpp_routes() {
7062 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
7064 let logger = ln_test_utils::TestLogger::new();
7065 let graph = match super::bench_utils::read_network_graph(&logger) {
7073 let params = ProbabilisticScoringFeeParameters::default();
7074 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
7075 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7077 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
7081 fn honors_manual_penalties() {
7082 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
7083 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7085 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7086 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7088 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
7089 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
7091 // First check set manual penalties are returned by the scorer.
7092 let usage = ChannelUsage {
7094 inflight_htlc_msat: 0,
7095 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
7097 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
7098 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
7099 let network_graph = network_graph.read_only();
7100 let channels = network_graph.channels();
7101 let channel = channels.get(&5).unwrap();
7102 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
7103 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop(PublicHopCandidate {
7105 short_channel_id: 5,
7107 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
7109 // Then check we can get a normal route
7110 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
7111 let route_params = RouteParameters::from_payment_params_and_value(
7112 payment_params, 100);
7113 let route = get_route(&our_id, &route_params, &network_graph, None,
7114 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
7115 assert!(route.is_ok());
7117 // Then check that we can't get a route if we ban an intermediate node.
7118 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
7119 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7120 assert!(route.is_err());
7122 // Finally make sure we can route again, when we remove the ban.
7123 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
7124 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7125 assert!(route.is_ok());
7129 fn abide_by_route_hint_max_htlc() {
7130 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
7131 // params in the final route.
7132 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7133 let netgraph = network_graph.read_only();
7134 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7135 let scorer = ln_test_utils::TestScorer::new();
7136 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7137 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7138 let config = UserConfig::default();
7140 let max_htlc_msat = 50_000;
7141 let route_hint_1 = RouteHint(vec![RouteHintHop {
7142 src_node_id: nodes[2],
7143 short_channel_id: 42,
7146 proportional_millionths: 0,
7148 cltv_expiry_delta: 10,
7149 htlc_minimum_msat: None,
7150 htlc_maximum_msat: Some(max_htlc_msat),
7152 let dest_node_id = ln_test_utils::pubkey(42);
7153 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7154 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
7155 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7158 // Make sure we'll error if our route hints don't have enough liquidity according to their
7159 // htlc_maximum_msat.
7160 let mut route_params = RouteParameters::from_payment_params_and_value(
7161 payment_params, max_htlc_msat + 1);
7162 route_params.max_total_routing_fee_msat = None;
7163 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
7164 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
7167 assert_eq!(err, "Failed to find a sufficient route to the given destination");
7168 } else { panic!(); }
7170 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
7171 let mut route_hint_2 = route_hint_1.clone();
7172 route_hint_2.0[0].short_channel_id = 43;
7173 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7174 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7175 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7177 let mut route_params = RouteParameters::from_payment_params_and_value(
7178 payment_params, max_htlc_msat + 1);
7179 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
7180 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
7181 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7182 assert_eq!(route.paths.len(), 2);
7183 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7184 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7188 fn direct_channel_to_hints_with_max_htlc() {
7189 // Check that if we have a first hop channel peer that's connected to multiple provided route
7190 // hints, that we properly split the payment between the route hints if needed.
7191 let logger = Arc::new(ln_test_utils::TestLogger::new());
7192 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7193 let scorer = ln_test_utils::TestScorer::new();
7194 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7195 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7196 let config = UserConfig::default();
7198 let our_node_id = ln_test_utils::pubkey(42);
7199 let intermed_node_id = ln_test_utils::pubkey(43);
7200 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7202 let amt_msat = 900_000;
7203 let max_htlc_msat = 500_000;
7204 let route_hint_1 = RouteHint(vec![RouteHintHop {
7205 src_node_id: intermed_node_id,
7206 short_channel_id: 44,
7209 proportional_millionths: 0,
7211 cltv_expiry_delta: 10,
7212 htlc_minimum_msat: None,
7213 htlc_maximum_msat: Some(max_htlc_msat),
7215 src_node_id: intermed_node_id,
7216 short_channel_id: 45,
7219 proportional_millionths: 0,
7221 cltv_expiry_delta: 10,
7222 htlc_minimum_msat: None,
7223 // Check that later route hint max htlcs don't override earlier ones
7224 htlc_maximum_msat: Some(max_htlc_msat - 50),
7226 let mut route_hint_2 = route_hint_1.clone();
7227 route_hint_2.0[0].short_channel_id = 46;
7228 route_hint_2.0[1].short_channel_id = 47;
7229 let dest_node_id = ln_test_utils::pubkey(44);
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))
7235 let route_params = RouteParameters::from_payment_params_and_value(
7236 payment_params, amt_msat);
7237 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7238 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7239 &Default::default(), &random_seed_bytes).unwrap();
7240 assert_eq!(route.paths.len(), 2);
7241 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7242 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7243 assert_eq!(route.get_total_amount(), amt_msat);
7245 // Re-run but with two first hop channels connected to the same route hint peers that must be
7247 let first_hops = vec![
7248 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7249 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7251 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7252 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7253 &Default::default(), &random_seed_bytes).unwrap();
7254 assert_eq!(route.paths.len(), 2);
7255 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7256 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7257 assert_eq!(route.get_total_amount(), amt_msat);
7259 // Make sure this works for blinded route hints.
7260 let blinded_path = BlindedPath {
7261 introduction_node: IntroductionNode::NodeId(intermed_node_id),
7262 blinding_point: ln_test_utils::pubkey(42),
7264 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
7265 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
7268 let blinded_payinfo = BlindedPayInfo {
7270 fee_proportional_millionths: 0,
7271 htlc_minimum_msat: 1,
7272 htlc_maximum_msat: max_htlc_msat,
7273 cltv_expiry_delta: 10,
7274 features: BlindedHopFeatures::empty(),
7276 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7277 let payment_params = PaymentParameters::blinded(vec![
7278 (blinded_payinfo.clone(), blinded_path.clone()),
7279 (blinded_payinfo.clone(), blinded_path.clone())])
7280 .with_bolt12_features(bolt12_features).unwrap();
7281 let route_params = RouteParameters::from_payment_params_and_value(
7282 payment_params, amt_msat);
7283 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7284 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7285 &Default::default(), &random_seed_bytes).unwrap();
7286 assert_eq!(route.paths.len(), 2);
7287 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7288 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7289 assert_eq!(route.get_total_amount(), amt_msat);
7293 fn blinded_route_ser() {
7294 let blinded_path_1 = BlindedPath {
7295 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(42)),
7296 blinding_point: ln_test_utils::pubkey(43),
7298 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7299 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7302 let blinded_path_2 = BlindedPath {
7303 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(46)),
7304 blinding_point: ln_test_utils::pubkey(47),
7306 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7307 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7310 // (De)serialize a Route with 1 blinded path out of two total paths.
7311 let mut route = Route { paths: vec![Path {
7312 hops: vec![RouteHop {
7313 pubkey: ln_test_utils::pubkey(50),
7314 node_features: NodeFeatures::empty(),
7315 short_channel_id: 42,
7316 channel_features: ChannelFeatures::empty(),
7318 cltv_expiry_delta: 0,
7319 maybe_announced_channel: true,
7321 blinded_tail: Some(BlindedTail {
7322 hops: blinded_path_1.blinded_hops,
7323 blinding_point: blinded_path_1.blinding_point,
7324 excess_final_cltv_expiry_delta: 40,
7325 final_value_msat: 100,
7327 hops: vec![RouteHop {
7328 pubkey: ln_test_utils::pubkey(51),
7329 node_features: NodeFeatures::empty(),
7330 short_channel_id: 43,
7331 channel_features: ChannelFeatures::empty(),
7333 cltv_expiry_delta: 0,
7334 maybe_announced_channel: true,
7335 }], blinded_tail: None }],
7338 let encoded_route = route.encode();
7339 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7340 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7341 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7343 // (De)serialize a Route with two paths, each containing a blinded tail.
7344 route.paths[1].blinded_tail = Some(BlindedTail {
7345 hops: blinded_path_2.blinded_hops,
7346 blinding_point: blinded_path_2.blinding_point,
7347 excess_final_cltv_expiry_delta: 41,
7348 final_value_msat: 101,
7350 let encoded_route = route.encode();
7351 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7352 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7353 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7357 fn blinded_path_inflight_processing() {
7358 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7359 // account for the blinded tail's final amount_msat.
7360 let mut inflight_htlcs = InFlightHtlcs::new();
7361 let blinded_path = BlindedPath {
7362 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(43)),
7363 blinding_point: ln_test_utils::pubkey(48),
7364 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7367 hops: vec![RouteHop {
7368 pubkey: ln_test_utils::pubkey(42),
7369 node_features: NodeFeatures::empty(),
7370 short_channel_id: 42,
7371 channel_features: ChannelFeatures::empty(),
7373 cltv_expiry_delta: 0,
7374 maybe_announced_channel: false,
7377 pubkey: ln_test_utils::pubkey(43),
7378 node_features: NodeFeatures::empty(),
7379 short_channel_id: 43,
7380 channel_features: ChannelFeatures::empty(),
7382 cltv_expiry_delta: 0,
7383 maybe_announced_channel: false,
7385 blinded_tail: Some(BlindedTail {
7386 hops: blinded_path.blinded_hops,
7387 blinding_point: blinded_path.blinding_point,
7388 excess_final_cltv_expiry_delta: 0,
7389 final_value_msat: 200,
7392 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7393 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7394 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7398 fn blinded_path_cltv_shadow_offset() {
7399 // Make sure we add a shadow offset when sending to blinded paths.
7400 let blinded_path = BlindedPath {
7401 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(43)),
7402 blinding_point: ln_test_utils::pubkey(44),
7404 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7405 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7408 let mut route = Route { paths: vec![Path {
7409 hops: vec![RouteHop {
7410 pubkey: ln_test_utils::pubkey(42),
7411 node_features: NodeFeatures::empty(),
7412 short_channel_id: 42,
7413 channel_features: ChannelFeatures::empty(),
7415 cltv_expiry_delta: 0,
7416 maybe_announced_channel: false,
7419 pubkey: ln_test_utils::pubkey(43),
7420 node_features: NodeFeatures::empty(),
7421 short_channel_id: 43,
7422 channel_features: ChannelFeatures::empty(),
7424 cltv_expiry_delta: 0,
7425 maybe_announced_channel: false,
7428 blinded_tail: Some(BlindedTail {
7429 hops: blinded_path.blinded_hops,
7430 blinding_point: blinded_path.blinding_point,
7431 excess_final_cltv_expiry_delta: 0,
7432 final_value_msat: 200,
7434 }], route_params: None};
7436 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7437 let (_, network_graph, _, _, _) = build_line_graph();
7438 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7439 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7440 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7444 fn simple_blinded_route_hints() {
7445 do_simple_blinded_route_hints(1);
7446 do_simple_blinded_route_hints(2);
7447 do_simple_blinded_route_hints(3);
7450 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7451 // Check that we can generate a route to a blinded path with the expected hops.
7452 let (secp_ctx, network, _, _, logger) = build_graph();
7453 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7454 let network_graph = network.read_only();
7456 let scorer = ln_test_utils::TestScorer::new();
7457 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7458 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7460 let mut blinded_path = BlindedPath {
7461 introduction_node: IntroductionNode::NodeId(nodes[2]),
7462 blinding_point: ln_test_utils::pubkey(42),
7463 blinded_hops: Vec::with_capacity(num_blinded_hops),
7465 for i in 0..num_blinded_hops {
7466 blinded_path.blinded_hops.push(
7467 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7470 let blinded_payinfo = BlindedPayInfo {
7472 fee_proportional_millionths: 500,
7473 htlc_minimum_msat: 1000,
7474 htlc_maximum_msat: 100_000_000,
7475 cltv_expiry_delta: 15,
7476 features: BlindedHopFeatures::empty(),
7479 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7480 let route_params = RouteParameters::from_payment_params_and_value(
7481 payment_params, 1001);
7482 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7483 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7484 assert_eq!(route.paths.len(), 1);
7485 assert_eq!(route.paths[0].hops.len(), 2);
7487 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7488 assert_eq!(tail.hops, blinded_path.blinded_hops);
7489 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7490 assert_eq!(tail.final_value_msat, 1001);
7492 let final_hop = route.paths[0].hops.last().unwrap();
7494 NodeId::from_pubkey(&final_hop.pubkey),
7495 *blinded_path.public_introduction_node_id(&network_graph).unwrap()
7497 if tail.hops.len() > 1 {
7498 assert_eq!(final_hop.fee_msat,
7499 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7500 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7502 assert_eq!(final_hop.fee_msat, 0);
7503 assert_eq!(final_hop.cltv_expiry_delta, 0);
7508 fn blinded_path_routing_errors() {
7509 // Check that we can generate a route to a blinded path with the expected hops.
7510 let (secp_ctx, network, _, _, logger) = build_graph();
7511 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7512 let network_graph = network.read_only();
7514 let scorer = ln_test_utils::TestScorer::new();
7515 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7516 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7518 let mut invalid_blinded_path = BlindedPath {
7519 introduction_node: IntroductionNode::NodeId(nodes[2]),
7520 blinding_point: ln_test_utils::pubkey(42),
7522 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
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 mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7535 invalid_blinded_path_2.introduction_node = IntroductionNode::NodeId(ln_test_utils::pubkey(45));
7536 let payment_params = PaymentParameters::blinded(vec![
7537 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7538 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7539 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7540 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7541 &scorer, &Default::default(), &random_seed_bytes)
7543 Err(LightningError { err, .. }) => {
7544 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7546 _ => panic!("Expected error")
7549 invalid_blinded_path.introduction_node = IntroductionNode::NodeId(our_id);
7550 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7551 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7552 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7553 &Default::default(), &random_seed_bytes)
7555 Err(LightningError { err, .. }) => {
7556 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7558 _ => panic!("Expected error")
7561 invalid_blinded_path.introduction_node = IntroductionNode::NodeId(ln_test_utils::pubkey(46));
7562 invalid_blinded_path.blinded_hops.clear();
7563 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7564 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7565 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7566 &Default::default(), &random_seed_bytes)
7568 Err(LightningError { err, .. }) => {
7569 assert_eq!(err, "0-hop blinded path provided");
7571 _ => panic!("Expected error")
7576 fn matching_intro_node_paths_provided() {
7577 // Check that if multiple blinded paths with the same intro node are provided in payment
7578 // parameters, we'll return the correct paths in the resulting MPP route.
7579 let (secp_ctx, network, _, _, logger) = build_graph();
7580 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7581 let network_graph = network.read_only();
7583 let scorer = ln_test_utils::TestScorer::new();
7584 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7585 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7586 let config = UserConfig::default();
7588 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7589 let blinded_path_1 = BlindedPath {
7590 introduction_node: IntroductionNode::NodeId(nodes[2]),
7591 blinding_point: ln_test_utils::pubkey(42),
7593 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7594 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7597 let blinded_payinfo_1 = BlindedPayInfo {
7599 fee_proportional_millionths: 0,
7600 htlc_minimum_msat: 0,
7601 htlc_maximum_msat: 30_000,
7602 cltv_expiry_delta: 0,
7603 features: BlindedHopFeatures::empty(),
7606 let mut blinded_path_2 = blinded_path_1.clone();
7607 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7608 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7609 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7611 let blinded_hints = vec![
7612 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7613 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7615 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7616 .with_bolt12_features(bolt12_features).unwrap();
7618 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7619 route_params.max_total_routing_fee_msat = Some(100_000);
7620 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7621 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7622 assert_eq!(route.paths.len(), 2);
7623 let mut total_amount_paid_msat = 0;
7624 for path in route.paths.into_iter() {
7625 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7626 if let Some(bt) = &path.blinded_tail {
7627 assert_eq!(bt.blinding_point,
7628 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7629 .map(|(_, bp)| bp.blinding_point).unwrap());
7630 } else { panic!(); }
7631 total_amount_paid_msat += path.final_value_msat();
7633 assert_eq!(total_amount_paid_msat, 100_000);
7637 fn direct_to_intro_node() {
7638 // This previously caused a debug panic in the router when asserting
7639 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7640 // direct channels we failed to account for the fee charged for use of the blinded path.
7643 // node0 -1(1)2 - node1
7644 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7645 // doesn't account for the blinded path fee.
7647 let secp_ctx = Secp256k1::new();
7648 let logger = Arc::new(ln_test_utils::TestLogger::new());
7649 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7650 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7651 let scorer = ln_test_utils::TestScorer::new();
7652 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7653 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7655 let amt_msat = 10_000_000;
7656 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7657 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7658 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7659 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7660 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7661 short_channel_id: 1,
7664 cltv_expiry_delta: 42,
7665 htlc_minimum_msat: 1_000,
7666 htlc_maximum_msat: 10_000_000,
7668 fee_proportional_millionths: 0,
7669 excess_data: Vec::new()
7671 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7672 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7673 short_channel_id: 1,
7676 cltv_expiry_delta: 42,
7677 htlc_minimum_msat: 1_000,
7678 htlc_maximum_msat: 10_000_000,
7680 fee_proportional_millionths: 0,
7681 excess_data: Vec::new()
7683 let first_hops = vec![
7684 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7686 let blinded_path = BlindedPath {
7687 introduction_node: IntroductionNode::NodeId(nodes[1]),
7688 blinding_point: ln_test_utils::pubkey(42),
7690 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7691 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7694 let blinded_payinfo = BlindedPayInfo {
7695 fee_base_msat: 1000,
7696 fee_proportional_millionths: 0,
7697 htlc_minimum_msat: 1000,
7698 htlc_maximum_msat: MAX_VALUE_MSAT,
7699 cltv_expiry_delta: 0,
7700 features: BlindedHopFeatures::empty(),
7702 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7704 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7706 let netgraph = network_graph.read_only();
7707 let route_params = RouteParameters::from_payment_params_and_value(
7708 payment_params.clone(), amt_msat);
7709 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7710 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7711 &Default::default(), &random_seed_bytes) {
7712 assert_eq!(err, "Failed to find a path to the given destination");
7713 } else { panic!("Expected error") }
7715 // Sending an exact amount accounting for the blinded path fee works.
7716 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7717 let route_params = RouteParameters::from_payment_params_and_value(
7718 payment_params, amt_minus_blinded_path_fee);
7719 let route = get_route(&nodes[0], &route_params, &netgraph,
7720 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7721 &Default::default(), &random_seed_bytes).unwrap();
7722 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7723 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7727 fn direct_to_matching_intro_nodes() {
7728 // This previously caused us to enter `unreachable` code in the following situation:
7729 // 1. We add a route candidate for intro_node contributing a high amount
7730 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7731 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7732 // amount, and update our route candidate for intro_node for the lower amount
7733 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7734 // lower contribution amount, but fail (this was previously caused by failure to account for
7735 // blinded path fees when adding first_hop<>intro_node candidates)
7736 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7737 // candidate still thinks its path is contributing the original higher amount. This caused us
7738 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7740 let secp_ctx = Secp256k1::new();
7741 let logger = Arc::new(ln_test_utils::TestLogger::new());
7742 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7743 let scorer = ln_test_utils::TestScorer::new();
7744 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7745 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7746 let config = UserConfig::default();
7748 // Values are taken from the fuzz input that uncovered this panic.
7749 let amt_msat = 21_7020_5185_1403_2640;
7750 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7751 let first_hops = vec![
7752 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7753 18446744073709551615)];
7755 let blinded_path = BlindedPath {
7756 introduction_node: IntroductionNode::NodeId(nodes[1]),
7757 blinding_point: ln_test_utils::pubkey(42),
7759 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7760 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7763 let blinded_payinfo = BlindedPayInfo {
7764 fee_base_msat: 5046_2720,
7765 fee_proportional_millionths: 0,
7766 htlc_minimum_msat: 4503_5996_2737_0496,
7767 htlc_maximum_msat: 45_0359_9627_3704_9600,
7768 cltv_expiry_delta: 0,
7769 features: BlindedHopFeatures::empty(),
7771 let mut blinded_hints = vec![
7772 (blinded_payinfo.clone(), blinded_path.clone()),
7773 (blinded_payinfo.clone(), blinded_path.clone()),
7775 blinded_hints[1].0.fee_base_msat = 419_4304;
7776 blinded_hints[1].0.fee_proportional_millionths = 257;
7777 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7778 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7779 blinded_hints[1].0.cltv_expiry_delta = 0;
7781 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7782 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7783 .with_bolt12_features(bolt12_features).unwrap();
7785 let netgraph = network_graph.read_only();
7786 let route_params = RouteParameters::from_payment_params_and_value(
7787 payment_params, amt_msat);
7788 let route = get_route(&nodes[0], &route_params, &netgraph,
7789 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7790 &Default::default(), &random_seed_bytes).unwrap();
7791 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7792 assert_eq!(route.get_total_amount(), amt_msat);
7796 fn we_are_intro_node_candidate_hops() {
7797 // This previously led to a panic in the router because we'd generate a Path with only a
7798 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7799 // where the origin node is the intro node. We now fully disallow considering candidate hops
7800 // where the origin node is the intro node.
7801 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7802 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7803 let scorer = ln_test_utils::TestScorer::new();
7804 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7805 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7806 let config = UserConfig::default();
7808 // Values are taken from the fuzz input that uncovered this panic.
7809 let amt_msat = 21_7020_5185_1423_0019;
7811 let blinded_path = BlindedPath {
7812 introduction_node: IntroductionNode::NodeId(our_id),
7813 blinding_point: ln_test_utils::pubkey(42),
7815 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7816 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7819 let blinded_payinfo = BlindedPayInfo {
7820 fee_base_msat: 5052_9027,
7821 fee_proportional_millionths: 0,
7822 htlc_minimum_msat: 21_7020_5185_1423_0019,
7823 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7824 cltv_expiry_delta: 0,
7825 features: BlindedHopFeatures::empty(),
7827 let mut blinded_hints = vec![
7828 (blinded_payinfo.clone(), blinded_path.clone()),
7829 (blinded_payinfo.clone(), blinded_path.clone()),
7831 blinded_hints[1].1.introduction_node = IntroductionNode::NodeId(nodes[6]);
7833 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7834 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7835 .with_bolt12_features(bolt12_features.clone()).unwrap();
7837 let netgraph = network_graph.read_only();
7838 let route_params = RouteParameters::from_payment_params_and_value(
7839 payment_params, amt_msat);
7840 if let Err(LightningError { err, .. }) = get_route(
7841 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7843 assert_eq!(err, "Failed to find a path to the given destination");
7848 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7849 // This previously led to a debug panic in the router because we'd find an invalid Path with
7850 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7851 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7852 // the payment, when it was intended to only include the final value of the payment.
7853 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7854 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7855 let scorer = ln_test_utils::TestScorer::new();
7856 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7857 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7858 let config = UserConfig::default();
7860 // Values are taken from the fuzz input that uncovered this panic.
7861 let amt_msat = 21_7020_5185_1423_0019;
7863 let blinded_path = BlindedPath {
7864 introduction_node: IntroductionNode::NodeId(our_id),
7865 blinding_point: ln_test_utils::pubkey(42),
7867 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7868 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7871 let blinded_payinfo = BlindedPayInfo {
7872 fee_base_msat: 10_4425_1395,
7873 fee_proportional_millionths: 0,
7874 htlc_minimum_msat: 21_7301_9934_9094_0931,
7875 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7876 cltv_expiry_delta: 0,
7877 features: BlindedHopFeatures::empty(),
7879 let mut blinded_hints = vec![
7880 (blinded_payinfo.clone(), blinded_path.clone()),
7881 (blinded_payinfo.clone(), blinded_path.clone()),
7882 (blinded_payinfo.clone(), blinded_path.clone()),
7884 blinded_hints[1].0.fee_base_msat = 5052_9027;
7885 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7886 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7888 blinded_hints[2].1.introduction_node = IntroductionNode::NodeId(nodes[6]);
7890 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7891 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7892 .with_bolt12_features(bolt12_features.clone()).unwrap();
7894 let netgraph = network_graph.read_only();
7895 let route_params = RouteParameters::from_payment_params_and_value(
7896 payment_params, amt_msat);
7897 if let Err(LightningError { err, .. }) = get_route(
7898 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7900 assert_eq!(err, "Failed to find a path to the given destination");
7905 fn min_htlc_overpay_violates_max_htlc() {
7906 do_min_htlc_overpay_violates_max_htlc(true);
7907 do_min_htlc_overpay_violates_max_htlc(false);
7909 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7910 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7911 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7912 // to `targets` and build an invalid path with it, and subsequently hit a debug panic asserting
7913 // that the used liquidity for a hop was less than its available liquidity limit.
7914 let secp_ctx = Secp256k1::new();
7915 let logger = Arc::new(ln_test_utils::TestLogger::new());
7916 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7917 let scorer = ln_test_utils::TestScorer::new();
7918 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7919 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7920 let config = UserConfig::default();
7922 // Values are taken from the fuzz input that uncovered this panic.
7923 let amt_msat = 7_4009_8048;
7924 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7925 let first_hop_outbound_capacity = 2_7345_2000;
7926 let first_hops = vec![get_channel_details(
7927 Some(200), nodes[0], channelmanager::provided_init_features(&config),
7928 first_hop_outbound_capacity
7931 let base_fee = 1_6778_3453;
7932 let htlc_min = 2_5165_8240;
7933 let payment_params = if blinded_payee {
7934 let blinded_path = BlindedPath {
7935 introduction_node: IntroductionNode::NodeId(nodes[0]),
7936 blinding_point: ln_test_utils::pubkey(42),
7938 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7939 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7942 let blinded_payinfo = BlindedPayInfo {
7943 fee_base_msat: base_fee,
7944 fee_proportional_millionths: 0,
7945 htlc_minimum_msat: htlc_min,
7946 htlc_maximum_msat: htlc_min * 1000,
7947 cltv_expiry_delta: 0,
7948 features: BlindedHopFeatures::empty(),
7950 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7951 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
7952 .with_bolt12_features(bolt12_features.clone()).unwrap()
7954 let route_hint = RouteHint(vec![RouteHintHop {
7955 src_node_id: nodes[0],
7956 short_channel_id: 42,
7958 base_msat: base_fee,
7959 proportional_millionths: 0,
7961 cltv_expiry_delta: 10,
7962 htlc_minimum_msat: Some(htlc_min),
7963 htlc_maximum_msat: None,
7966 PaymentParameters::from_node_id(nodes[1], 42)
7967 .with_route_hints(vec![route_hint]).unwrap()
7968 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7971 let netgraph = network_graph.read_only();
7972 let route_params = RouteParameters::from_payment_params_and_value(
7973 payment_params, amt_msat);
7974 if let Err(LightningError { err, .. }) = get_route(
7975 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7976 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7978 assert_eq!(err, "Failed to find a path to the given destination");
7983 fn previously_used_liquidity_violates_max_htlc() {
7984 do_previously_used_liquidity_violates_max_htlc(true);
7985 do_previously_used_liquidity_violates_max_htlc(false);
7988 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
7989 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
7990 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
7991 // candidate. In this case, the candidate does not have enough due to a previous path taking up
7992 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
7993 // asserting that the used liquidity for a hop was less than its available liquidity limit.
7994 let secp_ctx = Secp256k1::new();
7995 let logger = Arc::new(ln_test_utils::TestLogger::new());
7996 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7997 let scorer = ln_test_utils::TestScorer::new();
7998 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7999 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8000 let config = UserConfig::default();
8002 // Values are taken from the fuzz input that uncovered this panic.
8003 let amt_msat = 52_4288;
8004 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8005 let first_hops = vec![get_channel_details(
8006 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
8007 ), get_channel_details(
8008 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
8011 let base_fees = [0, 425_9840, 0, 0];
8012 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
8013 let payment_params = if blinded_payee {
8014 let blinded_path = BlindedPath {
8015 introduction_node: IntroductionNode::NodeId(nodes[0]),
8016 blinding_point: ln_test_utils::pubkey(42),
8018 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8019 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8022 let mut blinded_hints = Vec::new();
8023 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
8024 blinded_hints.push((BlindedPayInfo {
8025 fee_base_msat: *base_fee,
8026 fee_proportional_millionths: 0,
8027 htlc_minimum_msat: *htlc_min,
8028 htlc_maximum_msat: htlc_min * 100,
8029 cltv_expiry_delta: 10,
8030 features: BlindedHopFeatures::empty(),
8031 }, blinded_path.clone()));
8033 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8034 PaymentParameters::blinded(blinded_hints.clone())
8035 .with_bolt12_features(bolt12_features.clone()).unwrap()
8037 let mut route_hints = Vec::new();
8038 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
8039 route_hints.push(RouteHint(vec![RouteHintHop {
8040 src_node_id: nodes[0],
8041 short_channel_id: 42 + idx as u64,
8043 base_msat: *base_fee,
8044 proportional_millionths: 0,
8046 cltv_expiry_delta: 10,
8047 htlc_minimum_msat: Some(*htlc_min),
8048 htlc_maximum_msat: Some(htlc_min * 100),
8051 PaymentParameters::from_node_id(nodes[1], 42)
8052 .with_route_hints(route_hints).unwrap()
8053 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8056 let netgraph = network_graph.read_only();
8057 let route_params = RouteParameters::from_payment_params_and_value(
8058 payment_params, amt_msat);
8060 let route = get_route(
8061 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8062 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8064 assert_eq!(route.paths.len(), 1);
8065 assert_eq!(route.get_total_amount(), amt_msat);
8069 fn candidate_path_min() {
8070 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
8071 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
8072 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
8073 // would add a connecting first_hop node that did not have enough contribution amount, leading
8074 // to a debug panic upon invalid path construction.
8075 let secp_ctx = Secp256k1::new();
8076 let logger = Arc::new(ln_test_utils::TestLogger::new());
8077 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8078 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
8079 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8080 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8081 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8082 let config = UserConfig::default();
8084 // Values are taken from the fuzz input that uncovered this panic.
8085 let amt_msat = 7_4009_8048;
8086 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
8087 let first_hops = vec![get_channel_details(
8088 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
8091 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
8092 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8093 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8094 short_channel_id: 6,
8097 cltv_expiry_delta: (6 << 4) | 0,
8098 htlc_minimum_msat: 0,
8099 htlc_maximum_msat: MAX_VALUE_MSAT,
8101 fee_proportional_millionths: 0,
8102 excess_data: Vec::new()
8104 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
8106 let htlc_min = 2_5165_8240;
8107 let blinded_hints = vec![
8109 fee_base_msat: 1_6778_3453,
8110 fee_proportional_millionths: 0,
8111 htlc_minimum_msat: htlc_min,
8112 htlc_maximum_msat: htlc_min * 100,
8113 cltv_expiry_delta: 10,
8114 features: BlindedHopFeatures::empty(),
8116 introduction_node: IntroductionNode::NodeId(nodes[0]),
8117 blinding_point: ln_test_utils::pubkey(42),
8119 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8120 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8124 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8125 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8126 .with_bolt12_features(bolt12_features.clone()).unwrap();
8127 let route_params = RouteParameters::from_payment_params_and_value(
8128 payment_params, amt_msat);
8129 let netgraph = network_graph.read_only();
8131 if let Err(LightningError { err, .. }) = get_route(
8132 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8133 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8136 assert_eq!(err, "Failed to find a path to the given destination");
8141 fn path_contribution_includes_min_htlc_overpay() {
8142 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
8143 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
8144 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
8145 // selection, both tested here.
8146 let secp_ctx = Secp256k1::new();
8147 let logger = Arc::new(ln_test_utils::TestLogger::new());
8148 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8149 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8150 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8151 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8152 let config = UserConfig::default();
8154 // Values are taken from the fuzz input that uncovered this panic.
8155 let amt_msat = 562_0000;
8156 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8157 let first_hops = vec![
8158 get_channel_details(
8159 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
8163 let htlc_mins = [49_0000, 1125_0000];
8164 let payment_params = {
8165 let blinded_path = BlindedPath {
8166 introduction_node: IntroductionNode::NodeId(nodes[0]),
8167 blinding_point: ln_test_utils::pubkey(42),
8169 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8170 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8173 let mut blinded_hints = Vec::new();
8174 for htlc_min in htlc_mins.iter() {
8175 blinded_hints.push((BlindedPayInfo {
8177 fee_proportional_millionths: 0,
8178 htlc_minimum_msat: *htlc_min,
8179 htlc_maximum_msat: *htlc_min * 100,
8180 cltv_expiry_delta: 10,
8181 features: BlindedHopFeatures::empty(),
8182 }, blinded_path.clone()));
8184 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8185 PaymentParameters::blinded(blinded_hints.clone())
8186 .with_bolt12_features(bolt12_features.clone()).unwrap()
8189 let netgraph = network_graph.read_only();
8190 let route_params = RouteParameters::from_payment_params_and_value(
8191 payment_params, amt_msat);
8192 let route = get_route(
8193 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8194 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8197 assert_eq!(route.paths.len(), 1);
8198 assert_eq!(route.get_total_amount(), amt_msat);
8202 fn first_hop_preferred_over_hint() {
8203 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
8204 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
8205 let secp_ctx = Secp256k1::new();
8206 let logger = Arc::new(ln_test_utils::TestLogger::new());
8207 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8208 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
8209 let scorer = ln_test_utils::TestScorer::new();
8210 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8211 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8212 let config = UserConfig::default();
8214 let amt_msat = 1_000_000;
8215 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
8217 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
8218 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
8219 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8220 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8221 short_channel_id: 1,
8224 cltv_expiry_delta: 42,
8225 htlc_minimum_msat: 1_000,
8226 htlc_maximum_msat: 10_000_000,
8228 fee_proportional_millionths: 0,
8229 excess_data: Vec::new()
8231 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8232 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8233 short_channel_id: 1,
8236 cltv_expiry_delta: 42,
8237 htlc_minimum_msat: 1_000,
8238 htlc_maximum_msat: 10_000_000,
8240 fee_proportional_millionths: 0,
8241 excess_data: Vec::new()
8244 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
8245 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
8246 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8247 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8248 short_channel_id: 2,
8251 cltv_expiry_delta: 42,
8252 htlc_minimum_msat: 1_000,
8253 htlc_maximum_msat: 10_000_000,
8255 fee_proportional_millionths: 0,
8256 excess_data: Vec::new()
8258 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8259 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8260 short_channel_id: 2,
8263 cltv_expiry_delta: 42,
8264 htlc_minimum_msat: 1_000,
8265 htlc_maximum_msat: 10_000_000,
8267 fee_proportional_millionths: 0,
8268 excess_data: Vec::new()
8271 let dest_node_id = nodes[2];
8273 let route_hint = RouteHint(vec![RouteHintHop {
8274 src_node_id: our_node_id,
8275 short_channel_id: 44,
8278 proportional_millionths: 0,
8280 cltv_expiry_delta: 10,
8281 htlc_minimum_msat: None,
8282 htlc_maximum_msat: Some(5_000_000),
8285 src_node_id: nodes[0],
8286 short_channel_id: 45,
8289 proportional_millionths: 0,
8291 cltv_expiry_delta: 10,
8292 htlc_minimum_msat: None,
8293 htlc_maximum_msat: None,
8296 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8297 .with_route_hints(vec![route_hint]).unwrap()
8298 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8299 let route_params = RouteParameters::from_payment_params_and_value(
8300 payment_params, amt_msat);
8302 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8304 let first_hop = get_channel_details(Some(1), nodes[0],
8305 channelmanager::provided_init_features(&config), 999_999);
8306 let first_hops = vec![first_hop];
8308 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8309 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8310 &Default::default(), &random_seed_bytes).unwrap();
8311 assert_eq!(route.paths.len(), 1);
8312 assert_eq!(route.get_total_amount(), amt_msat);
8313 assert_eq!(route.paths[0].hops.len(), 2);
8314 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8315 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8316 assert_eq!(route.get_total_fees(), 123);
8318 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8319 // for a first hop channel.
8320 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8321 first_hop.outbound_scid_alias = Some(44);
8322 let first_hops = vec![first_hop];
8324 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8325 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8326 &Default::default(), &random_seed_bytes);
8327 assert!(route_res.is_err());
8329 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8330 // use the cheaper second hop of the route hint.
8331 let mut first_hop = get_channel_details(Some(1), nodes[0],
8332 channelmanager::provided_init_features(&config), 10_000_000);
8333 first_hop.outbound_scid_alias = Some(44);
8334 let first_hops = vec![first_hop];
8336 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8337 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8338 &Default::default(), &random_seed_bytes).unwrap();
8339 assert_eq!(route.paths.len(), 1);
8340 assert_eq!(route.get_total_amount(), amt_msat);
8341 assert_eq!(route.paths[0].hops.len(), 2);
8342 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8343 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8344 assert_eq!(route.get_total_fees(), 123);
8348 fn allow_us_being_first_hint() {
8349 // Check that we consider a route hint even if we are the src of the first hop.
8350 let secp_ctx = Secp256k1::new();
8351 let logger = Arc::new(ln_test_utils::TestLogger::new());
8352 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8353 let scorer = ln_test_utils::TestScorer::new();
8354 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8355 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8356 let config = UserConfig::default();
8358 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8360 let amt_msat = 1_000_000;
8361 let dest_node_id = nodes[1];
8363 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8364 let first_hops = vec![first_hop];
8366 let route_hint = RouteHint(vec![RouteHintHop {
8367 src_node_id: our_node_id,
8368 short_channel_id: 44,
8371 proportional_millionths: 0,
8373 cltv_expiry_delta: 10,
8374 htlc_minimum_msat: None,
8375 htlc_maximum_msat: None,
8378 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8379 .with_route_hints(vec![route_hint]).unwrap()
8380 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8382 let route_params = RouteParameters::from_payment_params_and_value(
8383 payment_params, amt_msat);
8386 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8387 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8388 &Default::default(), &random_seed_bytes).unwrap();
8390 assert_eq!(route.paths.len(), 1);
8391 assert_eq!(route.get_total_amount(), amt_msat);
8392 assert_eq!(route.get_total_fees(), 0);
8393 assert_eq!(route.paths[0].hops.len(), 1);
8395 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8399 #[cfg(all(any(test, ldk_bench), feature = "std"))]
8400 pub(crate) mod bench_utils {
8403 use std::time::Duration;
8405 use bitcoin::hashes::Hash;
8406 use bitcoin::secp256k1::SecretKey;
8408 use crate::chain::transaction::OutPoint;
8409 use crate::routing::scoring::ScoreUpdate;
8410 use crate::sign::KeysManager;
8411 use crate::ln::ChannelId;
8412 use crate::ln::channelmanager::{self, ChannelCounterparty};
8413 use crate::util::config::UserConfig;
8414 use crate::util::test_utils::TestLogger;
8416 /// Tries to open a network graph file, or panics with a URL to fetch it.
8417 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
8418 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
8419 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
8420 .or_else(|_| { // Fall back to guessing based on the binary location
8421 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8422 let mut path = std::env::current_exe().unwrap();
8423 path.pop(); // lightning-...
8425 path.pop(); // debug
8426 path.pop(); // target
8427 path.push("lightning");
8428 path.push("net_graph-2023-01-18.bin");
8431 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8432 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8433 let mut path = std::env::current_exe().unwrap();
8434 path.pop(); // bench...
8436 path.pop(); // debug
8437 path.pop(); // target
8438 path.pop(); // bench
8439 path.push("lightning");
8440 path.push("net_graph-2023-01-18.bin");
8443 .map_err(|_| "Please fetch https://bitcoin.ninja/ldk-net_graph-v0.0.113-2023-01-18.bin and place it at lightning/net_graph-2023-01-18.bin");
8444 #[cfg(require_route_graph_test)]
8445 return Ok(res.unwrap());
8446 #[cfg(not(require_route_graph_test))]
8450 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
8451 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
8454 pub(crate) fn payer_pubkey() -> PublicKey {
8455 let secp_ctx = Secp256k1::new();
8456 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8460 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8462 channel_id: ChannelId::new_zero(),
8463 counterparty: ChannelCounterparty {
8464 features: channelmanager::provided_init_features(&UserConfig::default()),
8466 unspendable_punishment_reserve: 0,
8467 forwarding_info: None,
8468 outbound_htlc_minimum_msat: None,
8469 outbound_htlc_maximum_msat: None,
8471 funding_txo: Some(OutPoint {
8472 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8475 short_channel_id: Some(1),
8476 inbound_scid_alias: None,
8477 outbound_scid_alias: None,
8478 channel_value_satoshis: 10_000_000_000,
8480 balance_msat: 10_000_000_000,
8481 outbound_capacity_msat: 10_000_000_000,
8482 next_outbound_htlc_minimum_msat: 0,
8483 next_outbound_htlc_limit_msat: 10_000_000_000,
8484 inbound_capacity_msat: 0,
8485 unspendable_punishment_reserve: None,
8486 confirmations_required: None,
8487 confirmations: None,
8488 force_close_spend_delay: None,
8490 is_channel_ready: true,
8493 inbound_htlc_minimum_msat: None,
8494 inbound_htlc_maximum_msat: None,
8496 feerate_sat_per_1000_weight: None,
8497 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
8498 pending_inbound_htlcs: Vec::new(),
8499 pending_outbound_htlcs: Vec::new(),
8503 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8504 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8505 starting_amount: u64, route_count: usize,
8506 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8507 let payer = payer_pubkey();
8508 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8509 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8511 let nodes = graph.read_only().nodes().clone();
8512 let mut route_endpoints = Vec::new();
8513 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
8514 // with some routes we picked being un-routable.
8515 for _ in 0..route_count * 3 / 2 {
8517 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8518 let src = PublicKey::from_slice(nodes.unordered_keys()
8519 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8520 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8521 let dst = PublicKey::from_slice(nodes.unordered_keys()
8522 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8523 let params = PaymentParameters::from_node_id(dst, 42)
8524 .with_bolt11_features(features.clone()).unwrap();
8525 let first_hop = first_hop(src);
8526 let amt_msat = starting_amount + seed % 1_000_000;
8527 let route_params = RouteParameters::from_payment_params_and_value(
8528 params.clone(), amt_msat);
8530 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8531 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8533 // ...and seed the scorer with success and failure data...
8534 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8535 let mut score_amt = seed % 1_000_000_000;
8537 // Generate fail/success paths for a wider range of potential amounts with
8538 // MPP enabled to give us a chance to apply penalties for more potential
8540 let mpp_features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
8541 let params = PaymentParameters::from_node_id(dst, 42)
8542 .with_bolt11_features(mpp_features).unwrap();
8543 let route_params = RouteParameters::from_payment_params_and_value(
8544 params.clone(), score_amt);
8545 let route_res = get_route(&payer, &route_params, &graph.read_only(),
8546 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
8547 &random_seed_bytes);
8548 if let Ok(route) = route_res {
8549 for path in route.paths {
8550 if seed & 0x80 == 0 {
8551 scorer.payment_path_successful(&path, Duration::ZERO);
8553 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
8554 scorer.payment_path_failed(&path, short_channel_id, Duration::ZERO);
8556 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8560 // If we couldn't find a path with a higher amount, reduce and try again.
8564 route_endpoints.push((first_hop, params, amt_msat));
8570 // Because we've changed channel scores, it's possible we'll take different routes to the
8571 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
8572 // requires a too-high CLTV delta.
8573 route_endpoints.retain(|(first_hop, params, amt_msat)| {
8574 let route_params = RouteParameters::from_payment_params_and_value(
8575 params.clone(), *amt_msat);
8576 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8577 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
8579 route_endpoints.truncate(route_count);
8580 assert_eq!(route_endpoints.len(), route_count);
8588 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8589 use crate::sign::{EntropySource, KeysManager};
8590 use crate::ln::channelmanager;
8591 use crate::ln::features::Bolt11InvoiceFeatures;
8592 use crate::routing::gossip::NetworkGraph;
8593 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
8594 use crate::util::config::UserConfig;
8595 use crate::util::logger::{Logger, Record};
8596 use crate::util::test_utils::TestLogger;
8598 use criterion::Criterion;
8600 struct DummyLogger {}
8601 impl Logger for DummyLogger {
8602 fn log(&self, _record: Record) {}
8605 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8606 let logger = TestLogger::new();
8607 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8608 let scorer = FixedPenaltyScorer::with_penalty(0);
8609 generate_routes(bench, &network_graph, scorer, &Default::default(),
8610 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8613 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8614 let logger = TestLogger::new();
8615 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8616 let scorer = FixedPenaltyScorer::with_penalty(0);
8617 generate_routes(bench, &network_graph, scorer, &Default::default(),
8618 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8619 "generate_mpp_routes_with_zero_penalty_scorer");
8622 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8623 let logger = TestLogger::new();
8624 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8625 let params = ProbabilisticScoringFeeParameters::default();
8626 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8627 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8628 "generate_routes_with_probabilistic_scorer");
8631 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8632 let logger = TestLogger::new();
8633 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8634 let params = ProbabilisticScoringFeeParameters::default();
8635 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8636 generate_routes(bench, &network_graph, scorer, ¶ms,
8637 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8638 "generate_mpp_routes_with_probabilistic_scorer");
8641 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8642 let logger = TestLogger::new();
8643 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8644 let params = ProbabilisticScoringFeeParameters::default();
8645 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8646 generate_routes(bench, &network_graph, scorer, ¶ms,
8647 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8648 "generate_large_mpp_routes_with_probabilistic_scorer");
8651 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8652 let logger = TestLogger::new();
8653 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8654 let mut params = ProbabilisticScoringFeeParameters::default();
8655 params.linear_success_probability = false;
8656 let scorer = ProbabilisticScorer::new(
8657 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8658 generate_routes(bench, &network_graph, scorer, ¶ms,
8659 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8660 "generate_routes_with_nonlinear_probabilistic_scorer");
8663 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8664 let logger = TestLogger::new();
8665 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8666 let mut params = ProbabilisticScoringFeeParameters::default();
8667 params.linear_success_probability = false;
8668 let scorer = ProbabilisticScorer::new(
8669 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8670 generate_routes(bench, &network_graph, scorer, ¶ms,
8671 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8672 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8675 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8676 let logger = TestLogger::new();
8677 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8678 let mut params = ProbabilisticScoringFeeParameters::default();
8679 params.linear_success_probability = false;
8680 let scorer = ProbabilisticScorer::new(
8681 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8682 generate_routes(bench, &network_graph, scorer, ¶ms,
8683 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8684 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8687 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8688 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8689 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8690 bench_name: &'static str,
8692 let payer = bench_utils::payer_pubkey();
8693 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8694 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8696 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8697 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8699 // ...then benchmark finding paths between the nodes we learned.
8701 bench.bench_function(bench_name, |b| b.iter(|| {
8702 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8703 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8704 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8705 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());