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};
15 use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, PaymentConstraints, PaymentRelay, ReceiveTlvs};
16 use crate::ln::PaymentHash;
17 use crate::ln::channelmanager::{ChannelDetails, PaymentId};
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>>, L: Deref, ES: Deref, S: Deref> where
38 S::Target: for <'a> LockableScore<'a>,
39 ES::Target: EntropySource,
45 score_params: crate::routing::scoring::ProbabilisticScoringFeeParameters,
48 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, ES: Deref, S: Deref> DefaultRouter<G, L, ES, S> where
50 S::Target: for <'a> LockableScore<'a>,
51 ES::Target: EntropySource,
53 /// Creates a new router.
54 pub fn new(network_graph: G, logger: L, entropy_source: ES, scorer: S, score_params: crate::routing::scoring::ProbabilisticScoringFeeParameters) -> Self {
55 Self { network_graph, logger, entropy_source, scorer, score_params }
59 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, ES: Deref, S: Deref> Router for DefaultRouter<G, L, ES, S> where
61 S::Target: for <'a> LockableScore<'a>,
62 ES::Target: EntropySource,
67 params: &RouteParameters,
68 first_hops: Option<&[&ChannelDetails]>,
69 inflight_htlcs: InFlightHtlcs
70 ) -> Result<Route, LightningError> {
71 let random_seed_bytes = self.entropy_source.get_secure_random_bytes();
73 payer, params, &self.network_graph, first_hops, &*self.logger,
74 &ScorerAccountingForInFlightHtlcs::new(self.scorer.read_lock(), &inflight_htlcs),
80 fn create_blinded_payment_paths<
81 T: secp256k1::Signing + secp256k1::Verification
83 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
84 amount_msats: u64, secp_ctx: &Secp256k1<T>
85 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
86 // Limit the number of blinded paths that are computed.
87 const MAX_PAYMENT_PATHS: usize = 3;
89 // Ensure peers have at least three channels so that it is more difficult to infer the
90 // recipient's node_id.
91 const MIN_PEER_CHANNELS: usize = 3;
93 let network_graph = self.network_graph.deref().read_only();
94 let paths = first_hops.into_iter()
95 .filter(|details| details.counterparty.features.supports_route_blinding())
96 .filter(|details| amount_msats <= details.inbound_capacity_msat)
97 .filter(|details| amount_msats >= details.inbound_htlc_minimum_msat.unwrap_or(0))
98 .filter(|details| amount_msats <= details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX))
99 .filter(|details| network_graph
100 .node(&NodeId::from_pubkey(&details.counterparty.node_id))
101 .map(|node_info| node_info.channels.len() >= MIN_PEER_CHANNELS)
104 .filter_map(|details| {
105 let short_channel_id = match details.get_inbound_payment_scid() {
106 Some(short_channel_id) => short_channel_id,
109 let payment_relay: PaymentRelay = match details.counterparty.forwarding_info {
110 Some(forwarding_info) => match forwarding_info.try_into() {
111 Ok(payment_relay) => payment_relay,
112 Err(()) => return None,
117 let cltv_expiry_delta = payment_relay.cltv_expiry_delta as u32;
118 let payment_constraints = PaymentConstraints {
119 max_cltv_expiry: tlvs.payment_constraints.max_cltv_expiry + cltv_expiry_delta,
120 htlc_minimum_msat: details.inbound_htlc_minimum_msat.unwrap_or(0),
127 features: BlindedHopFeatures::empty(),
129 node_id: details.counterparty.node_id,
130 htlc_maximum_msat: details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX),
133 .map(|forward_node| {
134 BlindedPath::new_for_payment(
135 vec![forward_node], recipient, tlvs.clone(), u64::MAX, &*self.entropy_source, secp_ctx
138 .take(MAX_PAYMENT_PATHS)
139 .collect::<Result<Vec<_>, _>>();
142 Ok(paths) if !paths.is_empty() => Ok(paths),
144 if network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient)) {
145 BlindedPath::one_hop_for_payment(recipient, tlvs, &*self.entropy_source, secp_ctx)
146 .map(|path| vec![path])
155 impl< G: Deref<Target = NetworkGraph<L>>, L: Deref, ES: Deref, S: Deref> MessageRouter for DefaultRouter<G, L, ES, S> where
157 S::Target: for <'a> LockableScore<'a>,
158 ES::Target: EntropySource,
161 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
162 ) -> Result<OnionMessagePath, ()> {
163 DefaultMessageRouter::<_, _, ES>::find_path(&self.network_graph, sender, peers, destination)
166 fn create_blinded_paths<
167 T: secp256k1::Signing + secp256k1::Verification
169 &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
170 ) -> Result<Vec<BlindedPath>, ()> {
171 DefaultMessageRouter::create_blinded_paths(&self.network_graph, recipient, peers, &self.entropy_source, secp_ctx)
175 /// A trait defining behavior for routing a payment.
176 pub trait Router: MessageRouter {
177 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
179 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
180 /// and [`RouteParameters::final_value_msat`], respectively.
182 &self, payer: &PublicKey, route_params: &RouteParameters,
183 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
184 ) -> Result<Route, LightningError>;
186 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
188 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
189 /// and [`RouteParameters::final_value_msat`], respectively.
191 /// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
193 fn find_route_with_id(
194 &self, payer: &PublicKey, route_params: &RouteParameters,
195 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
196 _payment_hash: PaymentHash, _payment_id: PaymentId
197 ) -> Result<Route, LightningError> {
198 self.find_route(payer, route_params, first_hops, inflight_htlcs)
201 /// Creates [`BlindedPath`]s for payment to the `recipient` node. The channels in `first_hops`
202 /// are assumed to be with the `recipient`'s peers. The payment secret and any constraints are
204 fn create_blinded_payment_paths<
205 T: secp256k1::Signing + secp256k1::Verification
207 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
208 amount_msats: u64, secp_ctx: &Secp256k1<T>
209 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()>;
212 /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
214 /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
217 /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
218 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> where S::Target: ScoreLookUp {
220 // Maps a channel's short channel id and its direction to the liquidity used up.
221 inflight_htlcs: &'a InFlightHtlcs,
223 impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
224 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
225 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
226 ScorerAccountingForInFlightHtlcs {
233 impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
234 #[cfg(not(c_bindings))]
235 type ScoreParams = <S::Target as ScoreLookUp>::ScoreParams;
236 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &crate::routing::scoring::ProbabilisticScoringFeeParameters) -> u64 {
237 let target = match candidate.target() {
238 Some(target) => target,
239 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
241 let short_channel_id = match candidate.short_channel_id() {
242 Some(short_channel_id) => short_channel_id,
243 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
245 let source = candidate.source();
246 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
247 &source, &target, short_channel_id
249 let usage = ChannelUsage {
250 inflight_htlc_msat: usage.inflight_htlc_msat.saturating_add(used_liquidity),
254 self.scorer.channel_penalty_msat(candidate, usage, score_params)
256 self.scorer.channel_penalty_msat(candidate, usage, score_params)
261 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
262 /// in-use channel liquidity.
264 pub struct InFlightHtlcs(
265 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
266 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
267 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
269 HashMap<(u64, bool), u64>
273 /// Constructs an empty `InFlightHtlcs`.
274 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
276 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
277 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
278 if path.hops.is_empty() { return };
280 let mut cumulative_msat = 0;
281 if let Some(tail) = &path.blinded_tail {
282 cumulative_msat += tail.final_value_msat;
285 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
286 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
287 // the router excludes the payer node. In the following lines, the payer's information is
288 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
289 // in our sliding window of two.
290 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
291 .map(|hop| hop.pubkey)
292 .chain(core::iter::once(payer_node_id));
294 // Taking the reversed vector from above, we zip it with just the reversed hops list to
295 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
296 // the total amount sent.
297 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
298 cumulative_msat += next_hop.fee_msat;
300 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
301 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
302 .or_insert(cumulative_msat);
306 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
308 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
310 .entry((channel_scid, source < target))
311 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
312 .or_insert(used_msat);
315 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
317 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
318 self.0.get(&(channel_scid, source < target)).map(|v| *v)
322 impl Writeable for InFlightHtlcs {
323 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
326 impl Readable for InFlightHtlcs {
327 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
328 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
329 Ok(Self(infight_map))
333 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
334 /// that leads to it.
335 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
336 pub struct RouteHop {
337 /// The node_id of the node at this hop.
338 pub pubkey: PublicKey,
339 /// The node_announcement features of the node at this hop. For the last hop, these may be
340 /// amended to match the features present in the invoice this node generated.
341 pub node_features: NodeFeatures,
342 /// The channel that should be used from the previous hop to reach this node.
343 pub short_channel_id: u64,
344 /// The channel_announcement features of the channel that should be used from the previous hop
345 /// to reach this node.
346 pub channel_features: ChannelFeatures,
347 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
348 /// If this is the last hop in [`Path::hops`]:
349 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
350 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
352 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
354 /// The CLTV delta added for this hop.
355 /// If this is the last hop in [`Path::hops`]:
356 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
357 /// * otherwise, this is the CLTV delta expected at the destination
359 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
360 pub cltv_expiry_delta: u32,
361 /// Indicates whether this hop is possibly announced in the public network graph.
363 /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
364 /// either know for sure it's announced in the public graph, or if any public channels exist
365 /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
366 /// the channel to be unannounced.
368 /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
369 pub maybe_announced_channel: bool,
372 impl_writeable_tlv_based!(RouteHop, {
373 (0, pubkey, required),
374 (1, maybe_announced_channel, (default_value, true)),
375 (2, node_features, required),
376 (4, short_channel_id, required),
377 (6, channel_features, required),
378 (8, fee_msat, required),
379 (10, cltv_expiry_delta, required),
382 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
383 /// their [`Bolt12Invoice`].
385 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
386 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
387 pub struct BlindedTail {
388 /// The hops of the [`BlindedPath`] provided by the recipient.
390 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
391 pub hops: Vec<BlindedHop>,
392 /// The blinding point of the [`BlindedPath`] provided by the recipient.
394 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
395 pub blinding_point: PublicKey,
396 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
397 /// inferring the destination. May be 0.
398 pub excess_final_cltv_expiry_delta: u32,
399 /// The total amount paid on this [`Path`], excluding the fees.
400 pub final_value_msat: u64,
403 impl_writeable_tlv_based!(BlindedTail, {
404 (0, hops, required_vec),
405 (2, blinding_point, required),
406 (4, excess_final_cltv_expiry_delta, required),
407 (6, final_value_msat, required),
410 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
411 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
412 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
414 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
415 pub hops: Vec<RouteHop>,
416 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
417 pub blinded_tail: Option<BlindedTail>,
421 /// Gets the fees for a given path, excluding any excess paid to the recipient.
422 pub fn fee_msat(&self) -> u64 {
423 match &self.blinded_tail {
424 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
426 // Do not count last hop of each path since that's the full value of the payment
427 self.hops.split_last().map_or(0,
428 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
433 /// Gets the total amount paid on this [`Path`], excluding the fees.
434 pub fn final_value_msat(&self) -> u64 {
435 match &self.blinded_tail {
436 Some(blinded_tail) => blinded_tail.final_value_msat,
437 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
441 /// Gets the final hop's CLTV expiry delta.
442 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
443 match &self.blinded_tail {
445 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
450 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
451 /// it can take multiple paths. Each path is composed of one or more hops through the network.
452 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
454 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
455 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
457 pub paths: Vec<Path>,
458 /// The `route_params` parameter passed to [`find_route`].
460 /// This is used by `ChannelManager` to track information which may be required for retries.
462 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
463 pub route_params: Option<RouteParameters>,
467 /// Returns the total amount of fees paid on this [`Route`].
469 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
470 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
471 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
473 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
474 pub fn get_total_fees(&self) -> u64 {
475 let overpaid_value_msat = self.route_params.as_ref()
476 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
477 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
480 /// Returns the total amount paid on this [`Route`], excluding the fees.
482 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
483 /// we had to reach the [`htlc_minimum_msat`] limits.
485 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
486 pub fn get_total_amount(&self) -> u64 {
487 self.paths.iter().map(|path| path.final_value_msat()).sum()
491 impl fmt::Display for Route {
492 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
493 log_route!(self).fmt(f)
497 const SERIALIZATION_VERSION: u8 = 1;
498 const MIN_SERIALIZATION_VERSION: u8 = 1;
500 impl Writeable for Route {
501 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
502 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
503 (self.paths.len() as u64).write(writer)?;
504 let mut blinded_tails = Vec::new();
505 for path in self.paths.iter() {
506 (path.hops.len() as u8).write(writer)?;
507 for (idx, hop) in path.hops.iter().enumerate() {
509 if let Some(blinded_tail) = &path.blinded_tail {
510 if blinded_tails.is_empty() {
511 blinded_tails = Vec::with_capacity(path.hops.len());
513 blinded_tails.push(None);
516 blinded_tails.push(Some(blinded_tail));
517 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
520 write_tlv_fields!(writer, {
521 // For compatibility with LDK versions prior to 0.0.117, we take the individual
522 // RouteParameters' fields and reconstruct them on read.
523 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
524 (2, blinded_tails, optional_vec),
525 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
526 (5, self.route_params.as_ref().map(|p| p.max_total_routing_fee_msat), option),
532 impl Readable for Route {
533 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
534 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
535 let path_count: u64 = Readable::read(reader)?;
536 if path_count == 0 { return Err(DecodeError::InvalidValue); }
537 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
538 let mut min_final_cltv_expiry_delta = u32::max_value();
539 for _ in 0..path_count {
540 let hop_count: u8 = Readable::read(reader)?;
541 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
542 for _ in 0..hop_count {
543 hops.push(Readable::read(reader)?);
545 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
546 min_final_cltv_expiry_delta =
547 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
548 paths.push(Path { hops, blinded_tail: None });
550 _init_and_read_len_prefixed_tlv_fields!(reader, {
551 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
552 (2, blinded_tails, optional_vec),
553 (3, final_value_msat, option),
554 (5, max_total_routing_fee_msat, option)
556 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
557 if blinded_tails.len() != 0 {
558 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
559 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
560 path.blinded_tail = blinded_tail_opt;
564 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
565 let route_params = match (payment_params, final_value_msat) {
566 (Some(payment_params), Some(final_value_msat)) => {
567 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
572 Ok(Route { paths, route_params })
576 /// Parameters needed to find a [`Route`].
578 /// Passed to [`find_route`] and [`build_route_from_hops`].
579 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
580 pub struct RouteParameters {
581 /// The parameters of the failed payment path.
582 pub payment_params: PaymentParameters,
584 /// The amount in msats sent on the failed payment path.
585 pub final_value_msat: u64,
587 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
589 /// This limit also applies to the total fees that may arise while retrying failed payment
592 /// Note that values below a few sats may result in some paths being spuriously ignored.
593 pub max_total_routing_fee_msat: Option<u64>,
596 impl RouteParameters {
597 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
599 /// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
600 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
601 Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
605 impl Writeable for RouteParameters {
606 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
607 write_tlv_fields!(writer, {
608 (0, self.payment_params, required),
609 (1, self.max_total_routing_fee_msat, option),
610 (2, self.final_value_msat, required),
611 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
612 // `RouteParameters` directly. For compatibility, we write it here.
613 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
619 impl Readable for RouteParameters {
620 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
621 _init_and_read_len_prefixed_tlv_fields!(reader, {
622 (0, payment_params, (required: ReadableArgs, 0)),
623 (1, max_total_routing_fee_msat, option),
624 (2, final_value_msat, required),
625 (4, final_cltv_delta, option),
627 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
628 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
629 if final_cltv_expiry_delta == &0 {
630 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
635 final_value_msat: final_value_msat.0.unwrap(),
636 max_total_routing_fee_msat,
641 /// Maximum total CTLV difference we allow for a full payment path.
642 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
644 /// Maximum number of paths we allow an (MPP) payment to have.
645 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
646 // limits, but for now more than 10 paths likely carries too much one-path failure.
647 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
649 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
651 // The median hop CLTV expiry delta currently seen in the network.
652 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
654 // During routing, we only consider paths shorter than our maximum length estimate.
655 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
656 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
657 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
659 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
660 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
661 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
662 // (payment_secret and total_msat) = 93 bytes for the final hop.
663 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
664 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
665 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
667 /// Information used to route a payment.
668 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
669 pub struct PaymentParameters {
670 /// Information about the payee, such as their features and route hints for their channels.
673 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
674 pub expiry_time: Option<u64>,
676 /// The maximum total CLTV delta we accept for the route.
677 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
678 pub max_total_cltv_expiry_delta: u32,
680 /// The maximum number of paths that may be used by (MPP) payments.
681 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
682 pub max_path_count: u8,
684 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
685 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
686 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
687 /// increasing failure probability for those paths.
689 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
690 /// restriction have been found. While paths which meet this criteria will be searched for, it
691 /// is ultimately up to the scorer to select them over other paths.
693 /// A value of 0 will allow payments up to and including a channel's total announced usable
694 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
697 pub max_channel_saturation_power_of_half: u8,
699 /// A list of SCIDs which this payment was previously attempted over and which caused the
700 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
702 pub previously_failed_channels: Vec<u64>,
704 /// A list of indices corresponding to blinded paths in [`Payee::Blinded::route_hints`] which this
705 /// payment was previously attempted over and which caused the payment to fail. Future attempts
706 /// for the same payment shouldn't be relayed through any of these blinded paths.
707 pub previously_failed_blinded_path_idxs: Vec<u64>,
710 impl Writeable for PaymentParameters {
711 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
712 let mut clear_hints = &vec![];
713 let mut blinded_hints = &vec![];
715 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
716 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
718 write_tlv_fields!(writer, {
719 (0, self.payee.node_id(), option),
720 (1, self.max_total_cltv_expiry_delta, required),
721 (2, self.payee.features(), option),
722 (3, self.max_path_count, required),
723 (4, *clear_hints, required_vec),
724 (5, self.max_channel_saturation_power_of_half, required),
725 (6, self.expiry_time, option),
726 (7, self.previously_failed_channels, required_vec),
727 (8, *blinded_hints, optional_vec),
728 (9, self.payee.final_cltv_expiry_delta(), option),
729 (11, self.previously_failed_blinded_path_idxs, required_vec),
735 impl ReadableArgs<u32> for PaymentParameters {
736 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
737 _init_and_read_len_prefixed_tlv_fields!(reader, {
738 (0, payee_pubkey, option),
739 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
740 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
741 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
742 (4, clear_route_hints, required_vec),
743 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
744 (6, expiry_time, option),
745 (7, previously_failed_channels, optional_vec),
746 (8, blinded_route_hints, optional_vec),
747 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
748 (11, previously_failed_blinded_path_idxs, optional_vec),
750 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
751 let payee = if blinded_route_hints.len() != 0 {
752 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
754 route_hints: blinded_route_hints,
755 features: features.and_then(|f: Features| f.bolt12()),
759 route_hints: clear_route_hints,
760 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
761 features: features.and_then(|f| f.bolt11()),
762 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
766 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
767 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
769 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
771 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
772 previously_failed_blinded_path_idxs: previously_failed_blinded_path_idxs.unwrap_or(Vec::new()),
778 impl PaymentParameters {
779 /// Creates a payee with the node id of the given `pubkey`.
781 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
783 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
785 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
787 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
788 max_path_count: DEFAULT_MAX_PATH_COUNT,
789 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
790 previously_failed_channels: Vec::new(),
791 previously_failed_blinded_path_idxs: Vec::new(),
795 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
797 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
800 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
801 /// whether your router will be allowed to find a multi-part route for this payment. If you
802 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
803 /// [`RecipientOnionFields::secret_only`].
805 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
806 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
807 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
808 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
809 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
812 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
813 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
814 /// [`PaymentParameters::expiry_time`].
815 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
816 Self::blinded(invoice.payment_paths().to_vec())
817 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
818 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
821 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
822 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
824 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
826 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
827 max_path_count: DEFAULT_MAX_PATH_COUNT,
828 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
829 previously_failed_channels: Vec::new(),
830 previously_failed_blinded_path_idxs: Vec::new(),
834 /// Includes the payee's features. Errors if the parameters were not initialized with
835 /// [`PaymentParameters::from_bolt12_invoice`].
837 /// This is not exported to bindings users since bindings don't support move semantics
838 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
840 Payee::Clear { .. } => Err(()),
841 Payee::Blinded { route_hints, .. } =>
842 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
846 /// Includes the payee's features. Errors if the parameters were initialized with
847 /// [`PaymentParameters::from_bolt12_invoice`].
849 /// This is not exported to bindings users since bindings don't support move semantics
850 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
852 Payee::Blinded { .. } => Err(()),
853 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
855 payee: Payee::Clear {
856 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
862 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
863 /// [`PaymentParameters::from_bolt12_invoice`].
865 /// This is not exported to bindings users since bindings don't support move semantics
866 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
868 Payee::Blinded { .. } => Err(()),
869 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
871 payee: Payee::Clear {
872 route_hints, node_id, features, final_cltv_expiry_delta,
878 /// Includes a payment expiration in seconds relative to the UNIX epoch.
880 /// This is not exported to bindings users since bindings don't support move semantics
881 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
882 Self { expiry_time: Some(expiry_time), ..self }
885 /// Includes a limit for the total CLTV expiry delta which is considered during routing
887 /// This is not exported to bindings users since bindings don't support move semantics
888 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
889 Self { max_total_cltv_expiry_delta, ..self }
892 /// Includes a limit for the maximum number of payment paths that may be used.
894 /// This is not exported to bindings users since bindings don't support move semantics
895 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
896 Self { max_path_count, ..self }
899 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
900 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
902 /// This is not exported to bindings users since bindings don't support move semantics
903 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
904 Self { max_channel_saturation_power_of_half, ..self }
907 pub(crate) fn insert_previously_failed_blinded_path(&mut self, failed_blinded_tail: &BlindedTail) {
908 let mut found_blinded_tail = false;
909 for (idx, (_, path)) in self.payee.blinded_route_hints().iter().enumerate() {
910 if failed_blinded_tail.hops == path.blinded_hops &&
911 failed_blinded_tail.blinding_point == path.blinding_point
913 self.previously_failed_blinded_path_idxs.push(idx as u64);
914 found_blinded_tail = true;
917 debug_assert!(found_blinded_tail);
921 /// The recipient of a payment, differing based on whether they've hidden their identity with route
923 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
925 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
926 /// will be included in the final [`Route`].
928 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
930 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
931 /// Features supported by the payee.
933 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
935 features: Option<Bolt12InvoiceFeatures>,
937 /// The recipient included these route hints in their BOLT11 invoice.
939 /// The node id of the payee.
941 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
942 route_hints: Vec<RouteHint>,
943 /// Features supported by the payee.
945 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
946 /// does not contain any features.
948 /// [`for_keysend`]: PaymentParameters::for_keysend
949 features: Option<Bolt11InvoiceFeatures>,
950 /// The minimum CLTV delta at the end of the route. This value must not be zero.
951 final_cltv_expiry_delta: u32,
956 fn node_id(&self) -> Option<PublicKey> {
958 Self::Clear { node_id, .. } => Some(*node_id),
962 fn node_features(&self) -> Option<NodeFeatures> {
964 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
965 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
968 fn supports_basic_mpp(&self) -> bool {
970 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
971 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
974 fn features(&self) -> Option<FeaturesRef> {
976 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
977 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
980 fn final_cltv_expiry_delta(&self) -> Option<u32> {
982 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
986 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
988 Self::Blinded { route_hints, .. } => &route_hints[..],
989 Self::Clear { .. } => &[]
993 fn unblinded_route_hints(&self) -> &[RouteHint] {
995 Self::Blinded { .. } => &[],
996 Self::Clear { route_hints, .. } => &route_hints[..]
1001 enum FeaturesRef<'a> {
1002 Bolt11(&'a Bolt11InvoiceFeatures),
1003 Bolt12(&'a Bolt12InvoiceFeatures),
1006 Bolt11(Bolt11InvoiceFeatures),
1007 Bolt12(Bolt12InvoiceFeatures),
1011 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
1013 Self::Bolt12(f) => Some(f),
1017 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
1019 Self::Bolt11(f) => Some(f),
1025 impl<'a> Writeable for FeaturesRef<'a> {
1026 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1028 Self::Bolt11(f) => Ok(f.write(w)?),
1029 Self::Bolt12(f) => Ok(f.write(w)?),
1034 impl ReadableArgs<bool> for Features {
1035 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
1036 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
1037 Ok(Self::Bolt12(Readable::read(reader)?))
1041 /// A list of hops along a payment path terminating with a channel to the recipient.
1042 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1043 pub struct RouteHint(pub Vec<RouteHintHop>);
1045 impl Writeable for RouteHint {
1046 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1047 (self.0.len() as u64).write(writer)?;
1048 for hop in self.0.iter() {
1055 impl Readable for RouteHint {
1056 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1057 let hop_count: u64 = Readable::read(reader)?;
1058 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
1059 for _ in 0..hop_count {
1060 hops.push(Readable::read(reader)?);
1066 /// A channel descriptor for a hop along a payment path.
1068 /// While this generally comes from BOLT 11's `r` field, this struct includes more fields than are
1069 /// available in BOLT 11. Thus, encoding and decoding this via `lightning-invoice` is lossy, as
1070 /// fields not supported in BOLT 11 will be stripped.
1071 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1072 pub struct RouteHintHop {
1073 /// The node_id of the non-target end of the route
1074 pub src_node_id: PublicKey,
1075 /// The short_channel_id of this channel
1076 pub short_channel_id: u64,
1077 /// The fees which must be paid to use this channel
1078 pub fees: RoutingFees,
1079 /// The difference in CLTV values between this node and the next node.
1080 pub cltv_expiry_delta: u16,
1081 /// The minimum value, in msat, which must be relayed to the next hop.
1082 pub htlc_minimum_msat: Option<u64>,
1083 /// The maximum value in msat available for routing with a single HTLC.
1084 pub htlc_maximum_msat: Option<u64>,
1087 impl_writeable_tlv_based!(RouteHintHop, {
1088 (0, src_node_id, required),
1089 (1, htlc_minimum_msat, option),
1090 (2, short_channel_id, required),
1091 (3, htlc_maximum_msat, option),
1092 (4, fees, required),
1093 (6, cltv_expiry_delta, required),
1096 #[derive(Eq, PartialEq)]
1097 #[repr(align(64))] // Force the size to 64 bytes
1098 struct RouteGraphNode {
1101 // The maximum value a yet-to-be-constructed payment path might flow through this node.
1102 // This value is upper-bounded by us by:
1103 // - how much is needed for a path being constructed
1104 // - how much value can channels following this node (up to the destination) can contribute,
1105 // considering their capacity and fees
1106 value_contribution_msat: u64,
1107 total_cltv_delta: u32,
1108 /// The number of hops walked up to this node.
1109 path_length_to_node: u8,
1112 impl cmp::Ord for RouteGraphNode {
1113 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
1114 other.score.cmp(&self.score).then_with(|| other.node_id.cmp(&self.node_id))
1118 impl cmp::PartialOrd for RouteGraphNode {
1119 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
1120 Some(self.cmp(other))
1124 // While RouteGraphNode can be laid out with fewer bytes, performance appears to be improved
1125 // substantially when it is laid out at exactly 64 bytes.
1127 // Thus, we use `#[repr(C)]` on the struct to force a suboptimal layout and check that it stays 64
1129 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1130 const _GRAPH_NODE_SMALL: usize = 64 - core::mem::size_of::<RouteGraphNode>();
1131 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1132 const _GRAPH_NODE_FIXED_SIZE: usize = core::mem::size_of::<RouteGraphNode>() - 64;
1134 /// A [`CandidateRouteHop::FirstHop`] entry.
1135 #[derive(Clone, Debug)]
1136 pub struct FirstHopCandidate<'a> {
1137 /// Channel details of the first hop
1139 /// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1140 /// has been funded and is able to pay), and accessor methods may panic otherwise.
1142 /// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1144 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1145 pub details: &'a ChannelDetails,
1146 /// The node id of the payer, which is also the source side of this candidate route hop.
1148 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1149 pub payer_node_id: &'a NodeId,
1152 /// A [`CandidateRouteHop::PublicHop`] entry.
1153 #[derive(Clone, Debug)]
1154 pub struct PublicHopCandidate<'a> {
1155 /// Information about the channel, including potentially its capacity and
1156 /// direction-specific information.
1158 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1159 pub info: DirectedChannelInfo<'a>,
1160 /// The short channel ID of the channel, i.e. the identifier by which we refer to this
1162 pub short_channel_id: u64,
1165 /// A [`CandidateRouteHop::PrivateHop`] entry.
1166 #[derive(Clone, Debug)]
1167 pub struct PrivateHopCandidate<'a> {
1168 /// Information about the private hop communicated via BOLT 11.
1170 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1171 pub hint: &'a RouteHintHop,
1172 /// Node id of the next hop in BOLT 11 route hint.
1174 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1175 pub target_node_id: &'a NodeId
1178 /// A [`CandidateRouteHop::Blinded`] entry.
1179 #[derive(Clone, Debug)]
1180 pub struct BlindedPathCandidate<'a> {
1181 /// Information about the blinded path including the fee, HTLC amount limits, and
1182 /// cryptographic material required to build an HTLC through the given path.
1184 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1185 pub hint: &'a (BlindedPayInfo, BlindedPath),
1186 /// Index of the hint in the original list of blinded hints.
1188 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1189 /// a short channel ID for this hop.
1193 /// A [`CandidateRouteHop::OneHopBlinded`] entry.
1194 #[derive(Clone, Debug)]
1195 pub struct OneHopBlindedPathCandidate<'a> {
1196 /// Information about the blinded path including the fee, HTLC amount limits, and
1197 /// cryptographic material required to build an HTLC terminating with the given path.
1199 /// Note that the [`BlindedPayInfo`] is ignored here.
1201 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1202 pub hint: &'a (BlindedPayInfo, BlindedPath),
1203 /// Index of the hint in the original list of blinded hints.
1205 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1206 /// a short channel ID for this hop.
1210 /// A wrapper around the various hop representations.
1212 /// Can be used to examine the properties of a hop,
1213 /// potentially to decide whether to include it in a route.
1214 #[derive(Clone, Debug)]
1215 pub enum CandidateRouteHop<'a> {
1216 /// A hop from the payer, where the outbound liquidity is known.
1217 FirstHop(FirstHopCandidate<'a>),
1218 /// A hop found in the [`ReadOnlyNetworkGraph`].
1219 PublicHop(PublicHopCandidate<'a>),
1220 /// A private hop communicated by the payee, generally via a BOLT 11 invoice.
1222 /// Because BOLT 11 route hints can take multiple hops to get to the destination, this may not
1223 /// terminate at the payee.
1224 PrivateHop(PrivateHopCandidate<'a>),
1225 /// A blinded path which starts with an introduction point and ultimately terminates with the
1228 /// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1229 /// `None` in this state.
1231 /// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1232 /// path, the full path is treated as a single [`CandidateRouteHop`].
1233 Blinded(BlindedPathCandidate<'a>),
1234 /// Similar to [`Self::Blinded`], but the path here only has one hop.
1236 /// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1237 /// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1238 /// payee's identity - it's the introduction point!
1240 /// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1241 /// to the hops *between* the introduction node and the destination.
1243 /// This primarily exists to track that we need to included a blinded path at the end of our
1244 /// [`Route`], even though it doesn't actually add an additional hop in the payment.
1245 OneHopBlinded(OneHopBlindedPathCandidate<'a>),
1248 impl<'a> CandidateRouteHop<'a> {
1249 /// Returns the short channel ID for this hop, if one is known.
1251 /// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1252 /// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1254 /// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1255 /// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1256 /// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1257 /// (which is always true for channels which are funded and ready for use).
1259 /// In other words, this should always return `Some` as long as the candidate hop is not a
1260 /// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1262 /// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1263 /// define a global namespace.
1265 fn short_channel_id(&self) -> Option<u64> {
1267 CandidateRouteHop::FirstHop(hop) => hop.details.get_outbound_payment_scid(),
1268 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1269 CandidateRouteHop::PrivateHop(hop) => Some(hop.hint.short_channel_id),
1270 CandidateRouteHop::Blinded(_) => None,
1271 CandidateRouteHop::OneHopBlinded(_) => None,
1275 /// Returns the globally unique short channel ID for this hop, if one is known.
1277 /// This only returns `Some` if the channel is public (either our own, or one we've learned
1278 /// from the public network graph), and thus the short channel ID we have for this channel is
1279 /// globally unique and identifies this channel in a global namespace.
1281 pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1283 CandidateRouteHop::FirstHop(hop) => if hop.details.is_public { hop.details.short_channel_id } else { None },
1284 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1285 CandidateRouteHop::PrivateHop(_) => None,
1286 CandidateRouteHop::Blinded(_) => None,
1287 CandidateRouteHop::OneHopBlinded(_) => None,
1291 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1292 fn features(&self) -> ChannelFeatures {
1294 CandidateRouteHop::FirstHop(hop) => hop.details.counterparty.features.to_context(),
1295 CandidateRouteHop::PublicHop(hop) => hop.info.channel().features.clone(),
1296 CandidateRouteHop::PrivateHop(_) => ChannelFeatures::empty(),
1297 CandidateRouteHop::Blinded(_) => ChannelFeatures::empty(),
1298 CandidateRouteHop::OneHopBlinded(_) => ChannelFeatures::empty(),
1302 /// Returns the required difference in HTLC CLTV expiry between the [`Self::source`] and the
1303 /// next-hop for an HTLC taking this hop.
1305 /// This is the time that the node(s) in this hop have to claim the HTLC on-chain if the
1306 /// next-hop goes on chain with a payment preimage.
1308 pub fn cltv_expiry_delta(&self) -> u32 {
1310 CandidateRouteHop::FirstHop(_) => 0,
1311 CandidateRouteHop::PublicHop(hop) => hop.info.direction().cltv_expiry_delta as u32,
1312 CandidateRouteHop::PrivateHop(hop) => hop.hint.cltv_expiry_delta as u32,
1313 CandidateRouteHop::Blinded(hop) => hop.hint.0.cltv_expiry_delta as u32,
1314 CandidateRouteHop::OneHopBlinded(_) => 0,
1318 /// Returns the minimum amount that can be sent over this hop, in millisatoshis.
1320 pub fn htlc_minimum_msat(&self) -> u64 {
1322 CandidateRouteHop::FirstHop(hop) => hop.details.next_outbound_htlc_minimum_msat,
1323 CandidateRouteHop::PublicHop(hop) => hop.info.direction().htlc_minimum_msat,
1324 CandidateRouteHop::PrivateHop(hop) => hop.hint.htlc_minimum_msat.unwrap_or(0),
1325 CandidateRouteHop::Blinded(hop) => hop.hint.0.htlc_minimum_msat,
1326 CandidateRouteHop::OneHopBlinded { .. } => 0,
1330 /// Returns the fees that must be paid to route an HTLC over this channel.
1332 pub fn fees(&self) -> RoutingFees {
1334 CandidateRouteHop::FirstHop(_) => RoutingFees {
1335 base_msat: 0, proportional_millionths: 0,
1337 CandidateRouteHop::PublicHop(hop) => hop.info.direction().fees,
1338 CandidateRouteHop::PrivateHop(hop) => hop.hint.fees,
1339 CandidateRouteHop::Blinded(hop) => {
1341 base_msat: hop.hint.0.fee_base_msat,
1342 proportional_millionths: hop.hint.0.fee_proportional_millionths
1345 CandidateRouteHop::OneHopBlinded(_) =>
1346 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1350 /// Fetch the effective capacity of this hop.
1352 /// Note that this may be somewhat expensive, so calls to this should be limited and results
1354 fn effective_capacity(&self) -> EffectiveCapacity {
1356 CandidateRouteHop::FirstHop(hop) => EffectiveCapacity::ExactLiquidity {
1357 liquidity_msat: hop.details.next_outbound_htlc_limit_msat,
1359 CandidateRouteHop::PublicHop(hop) => hop.info.effective_capacity(),
1360 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. }) =>
1361 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1362 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. }) =>
1363 EffectiveCapacity::Infinite,
1364 CandidateRouteHop::Blinded(hop) =>
1365 EffectiveCapacity::HintMaxHTLC { amount_msat: hop.hint.0.htlc_maximum_msat },
1366 CandidateRouteHop::OneHopBlinded(_) => EffectiveCapacity::Infinite,
1370 /// Returns an ID describing the given hop.
1372 /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1374 fn id(&self) -> CandidateHopId {
1376 CandidateRouteHop::Blinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1377 CandidateRouteHop::OneHopBlinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1378 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1381 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1383 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1389 fn blinded_hint_idx(&self) -> Option<usize> {
1391 Self::Blinded(BlindedPathCandidate { hint_idx, .. }) |
1392 Self::OneHopBlinded(OneHopBlindedPathCandidate { hint_idx, .. }) => {
1398 /// Returns the source node id of current hop.
1400 /// Source node id refers to the node forwarding the HTLC through this hop.
1402 /// For [`Self::FirstHop`] we return payer's node id.
1404 pub fn source(&self) -> NodeId {
1406 CandidateRouteHop::FirstHop(hop) => *hop.payer_node_id,
1407 CandidateRouteHop::PublicHop(hop) => *hop.info.source(),
1408 CandidateRouteHop::PrivateHop(hop) => hop.hint.src_node_id.into(),
1409 CandidateRouteHop::Blinded(hop) => hop.hint.1.introduction_node_id.into(),
1410 CandidateRouteHop::OneHopBlinded(hop) => hop.hint.1.introduction_node_id.into(),
1413 /// Returns the target node id of this hop, if known.
1415 /// Target node id refers to the node receiving the HTLC after this hop.
1417 /// For [`Self::Blinded`] we return `None` because the ultimate destination after the blinded
1418 /// path is unknown.
1420 /// For [`Self::OneHopBlinded`] we return `None` because the target is the same as the source,
1421 /// and such a return value would be somewhat nonsensical.
1423 pub fn target(&self) -> Option<NodeId> {
1425 CandidateRouteHop::FirstHop(hop) => Some(hop.details.counterparty.node_id.into()),
1426 CandidateRouteHop::PublicHop(hop) => Some(*hop.info.target()),
1427 CandidateRouteHop::PrivateHop(hop) => Some(*hop.target_node_id),
1428 CandidateRouteHop::Blinded(_) => None,
1429 CandidateRouteHop::OneHopBlinded(_) => None,
1434 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1436 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1438 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1439 /// isn't guaranteed to be unique at all.
1441 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1442 /// difficult-to-use API.
1443 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1444 enum CandidateHopId {
1445 /// Contains (scid, src_node_id < target_node_id)
1447 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1452 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1453 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1455 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1456 EffectiveCapacity::Infinite => u64::max_value(),
1457 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1458 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1459 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1460 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1461 // expected to have been generated from up-to-date capacity information.
1462 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1463 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1464 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1468 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1469 -> bool where I1::Item: PartialEq<I2::Item> {
1471 let a = iter_a.next();
1472 let b = iter_b.next();
1473 if a.is_none() && b.is_none() { return true; }
1474 if a.is_none() || b.is_none() { return false; }
1475 if a.unwrap().ne(&b.unwrap()) { return false; }
1479 /// It's useful to keep track of the hops associated with the fees required to use them,
1480 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1481 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1482 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1484 #[repr(C)] // Force fields to appear in the order we define them.
1485 struct PathBuildingHop<'a> {
1486 candidate: CandidateRouteHop<'a>,
1487 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1488 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1489 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1490 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1491 /// avoid processing them again.
1492 was_processed: bool,
1493 /// Used to compare channels when choosing the for routing.
1494 /// Includes paying for the use of a hop and the following hops, as well as
1495 /// an estimated cost of reaching this hop.
1496 /// Might get stale when fees are recomputed. Primarily for internal use.
1497 total_fee_msat: u64,
1498 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1499 /// walk and may be invalid thereafter.
1500 path_htlc_minimum_msat: u64,
1501 /// All penalties incurred from this channel on the way to the destination, as calculated using
1502 /// channel scoring.
1503 path_penalty_msat: u64,
1505 // The last 16 bytes are on the next cache line by default in glibc's malloc. Thus, we should
1506 // only place fields which are not hot there. Luckily, the next three fields are only read if
1507 // we end up on the selected path, and only in the final path layout phase, so we don't care
1508 // too much if reading them is slow.
1512 /// All the fees paid *after* this channel on the way to the destination
1513 next_hops_fee_msat: u64,
1514 /// Fee paid for the use of the current channel (see candidate.fees()).
1515 /// The value will be actually deducted from the counterparty balance on the previous link.
1516 hop_use_fee_msat: u64,
1518 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1519 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1520 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1521 // value_contribution_msat, which requires tracking it here. See comments below where it is
1522 // used for more info.
1523 value_contribution_msat: u64,
1526 // Checks that the entries in the `find_route` `dist` map fit in (exactly) two standard x86-64
1527 // cache lines. Sadly, they're not guaranteed to actually lie on a cache line (and in fact,
1528 // generally won't, because at least glibc's malloc will align to a nice, big, round
1529 // boundary...plus 16), but at least it will reduce the amount of data we'll need to load.
1531 // Note that these assertions only pass on somewhat recent rustc, and thus are gated on the
1534 const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::<(NodeId, PathBuildingHop)>();
1536 const _NODE_MAP_SIZE_EXACTLY_CACHE_LINES: usize = core::mem::size_of::<(NodeId, PathBuildingHop)>() - 128;
1538 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1539 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1540 let mut debug_struct = f.debug_struct("PathBuildingHop");
1542 .field("node_id", &self.candidate.target())
1543 .field("short_channel_id", &self.candidate.short_channel_id())
1544 .field("total_fee_msat", &self.total_fee_msat)
1545 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1546 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1547 .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)))
1548 .field("path_penalty_msat", &self.path_penalty_msat)
1549 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1550 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1551 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1552 let debug_struct = debug_struct
1553 .field("value_contribution_msat", &self.value_contribution_msat);
1554 debug_struct.finish()
1558 // Instantiated with a list of hops with correct data in them collected during path finding,
1559 // an instance of this struct should be further modified only via given methods.
1561 struct PaymentPath<'a> {
1562 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1565 impl<'a> PaymentPath<'a> {
1566 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1567 fn get_value_msat(&self) -> u64 {
1568 self.hops.last().unwrap().0.fee_msat
1571 fn get_path_penalty_msat(&self) -> u64 {
1572 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1575 fn get_total_fee_paid_msat(&self) -> u64 {
1576 if self.hops.len() < 1 {
1580 // Can't use next_hops_fee_msat because it gets outdated.
1581 for (i, (hop, _)) in self.hops.iter().enumerate() {
1582 if i != self.hops.len() - 1 {
1583 result += hop.fee_msat;
1589 fn get_cost_msat(&self) -> u64 {
1590 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1593 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1594 // to change fees may result in an inconsistency.
1596 // Sometimes we call this function right after constructing a path which is inconsistent in
1597 // that it the value being transferred has decreased while we were doing path finding, leading
1598 // to the fees being paid not lining up with the actual limits.
1600 // Note that this function is not aware of the available_liquidity limit, and thus does not
1601 // support increasing the value being transferred beyond what was selected during the initial
1604 // Returns the amount that this path contributes to the total payment value, which may be greater
1605 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1606 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1607 let mut extra_contribution_msat = 0;
1608 let mut total_fee_paid_msat = 0 as u64;
1609 for i in (0..self.hops.len()).rev() {
1610 let last_hop = i == self.hops.len() - 1;
1612 // For non-last-hop, this value will represent the fees paid on the current hop. It
1613 // will consist of the fees for the use of the next hop, and extra fees to match
1614 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1615 let mut cur_hop_fees_msat = 0;
1617 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1620 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1621 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1622 cur_hop.path_penalty_msat += extra_contribution_msat;
1623 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1624 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1625 // set it too high just to maliciously take more fees by exploiting this
1626 // match htlc_minimum_msat logic.
1627 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1628 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1629 // Note that there is a risk that *previous hops* (those closer to us, as we go
1630 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1632 // This might make us end up with a broken route, although this should be super-rare
1633 // in practice, both because of how healthy channels look like, and how we pick
1634 // channels in add_entry.
1635 // Also, this can't be exploited more heavily than *announce a free path and fail
1637 cur_hop_transferred_amount_msat += extra_fees_msat;
1639 // We remember and return the extra fees on the final hop to allow accounting for
1640 // them in the path's value contribution.
1642 extra_contribution_msat = extra_fees_msat;
1644 total_fee_paid_msat += extra_fees_msat;
1645 cur_hop_fees_msat += extra_fees_msat;
1650 // Final hop is a special case: it usually has just value_msat (by design), but also
1651 // it still could overpay for the htlc_minimum_msat.
1652 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1654 // Propagate updated fees for the use of the channels to one hop back, where they
1655 // will be actually paid (fee_msat). The last hop is handled above separately.
1656 cur_hop.fee_msat = cur_hop_fees_msat;
1659 // Fee for the use of the current hop which will be deducted on the previous hop.
1660 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1661 // this channel is free for us.
1663 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1664 cur_hop.hop_use_fee_msat = new_fee;
1665 total_fee_paid_msat += new_fee;
1667 // It should not be possible because this function is called only to reduce the
1668 // value. In that case, compute_fee was already called with the same fees for
1669 // larger amount and there was no overflow.
1674 value_msat + extra_contribution_msat
1679 /// Calculate the fees required to route the given amount over a channel with the given fees.
1680 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1681 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1682 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1686 /// Calculate the fees required to route the given amount over a channel with the given fees,
1687 /// saturating to [`u64::max_value`].
1688 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1689 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1690 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1691 .saturating_add(channel_fees.base_msat as u64)
1694 /// The default `features` we assume for a node in a route, when no `features` are known about that
1697 /// Default features are:
1698 /// * variable_length_onion_optional
1699 fn default_node_features() -> NodeFeatures {
1700 let mut features = NodeFeatures::empty();
1701 features.set_variable_length_onion_optional();
1705 struct LoggedPayeePubkey(Option<PublicKey>);
1706 impl fmt::Display for LoggedPayeePubkey {
1707 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1710 "payee node id ".fmt(f)?;
1714 "blinded payee".fmt(f)
1720 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1721 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1722 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1724 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1725 "blinded route hint with introduction node id ".fmt(f)?;
1726 hint.1.introduction_node_id.fmt(f)?;
1727 " and blinding point ".fmt(f)?;
1728 hint.1.blinding_point.fmt(f)
1730 CandidateRouteHop::FirstHop(_) => {
1731 "first hop with SCID ".fmt(f)?;
1732 self.0.short_channel_id().unwrap().fmt(f)
1734 CandidateRouteHop::PrivateHop(_) => {
1735 "route hint with SCID ".fmt(f)?;
1736 self.0.short_channel_id().unwrap().fmt(f)
1740 self.0.short_channel_id().unwrap().fmt(f)
1747 fn sort_first_hop_channels(
1748 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1749 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1751 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1752 // most like to use.
1754 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1755 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1758 // Second, because simply always sorting in descending order would always use our largest
1759 // available outbound capacity, needlessly fragmenting our available channel capacities,
1760 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1761 // which have enough, but not too much, capacity for the payment.
1763 // Available outbound balances factor in liquidity already reserved for previously found paths.
1764 channels.sort_unstable_by(|chan_a, chan_b| {
1765 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1766 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1767 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1768 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1769 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1770 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1771 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1772 // Sort in descending order
1773 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1775 // Sort in ascending order
1776 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1781 /// Finds a route from us (payer) to the given target node (payee).
1783 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1784 /// in the given [`RouteParameters::payment_params`].
1785 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1787 /// Private routing paths between a public node and the target may be included in the `payee` field
1788 /// of [`RouteParameters::payment_params`].
1790 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1791 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1792 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1794 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1795 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1796 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1800 /// Panics if first_hops contains channels without `short_channel_id`s;
1801 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1803 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1804 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1805 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1806 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1807 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1808 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1809 scorer: &S, score_params: &crate::routing::scoring::ProbabilisticScoringFeeParameters, random_seed_bytes: &[u8; 32]
1810 ) -> Result<Route, LightningError>
1811 where L::Target: Logger, GL::Target: Logger {
1812 let graph_lock = network_graph.read_only();
1813 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1814 scorer, score_params, random_seed_bytes)?;
1815 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1819 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1820 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1821 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &crate::routing::scoring::ProbabilisticScoringFeeParameters,
1822 _random_seed_bytes: &[u8; 32]
1823 ) -> Result<Route, LightningError>
1824 where L::Target: Logger {
1826 let payment_params = &route_params.payment_params;
1827 let final_value_msat = route_params.final_value_msat;
1828 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1829 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1830 // so use a dummy id for this in the blinded case.
1831 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1832 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1833 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1834 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1835 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1837 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1838 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1840 if our_node_id == maybe_dummy_payee_node_id {
1841 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1844 if final_value_msat > MAX_VALUE_MSAT {
1845 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1848 if final_value_msat == 0 {
1849 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1852 match &payment_params.payee {
1853 Payee::Clear { route_hints, node_id, .. } => {
1854 for route in route_hints.iter() {
1855 for hop in &route.0 {
1856 if hop.src_node_id == *node_id {
1857 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1862 Payee::Blinded { route_hints, .. } => {
1863 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1864 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});
1866 for (_, blinded_path) in route_hints.iter() {
1867 if blinded_path.blinded_hops.len() == 0 {
1868 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1869 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1870 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1871 } else if blinded_path.blinded_hops.len() == 1 &&
1872 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1873 && p.introduction_node_id != blinded_path.introduction_node_id)
1875 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1880 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1881 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1882 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});
1885 // The general routing idea is the following:
1886 // 1. Fill first/last hops communicated by the caller.
1887 // 2. Attempt to construct a path from payer to payee for transferring
1888 // any ~sufficient (described later) value.
1889 // If succeed, remember which channels were used and how much liquidity they have available,
1890 // so that future paths don't rely on the same liquidity.
1891 // 3. Proceed to the next step if:
1892 // - we hit the recommended target value;
1893 // - OR if we could not construct a new path. Any next attempt will fail too.
1894 // Otherwise, repeat step 2.
1895 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1896 // (not recommended value).
1897 // 5. If yes, proceed. If not, fail routing.
1898 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1899 // transferred up to the transfer target value.
1900 // 7. Reduce the value of the last path until we are sending only the target value.
1901 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1902 // them so that we're not sending two HTLCs along the same path.
1904 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1905 // distance from the payee
1907 // We are not a faithful Dijkstra's implementation because we can change values which impact
1908 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1909 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1910 // the value we are currently attempting to send over a path, we simply reduce the value being
1911 // sent along the path for any hops after that channel. This may imply that later fees (which
1912 // we've already tabulated) are lower because a smaller value is passing through the channels
1913 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1914 // channels which were selected earlier (and which may still be used for other paths without a
1915 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1918 // One potentially problematic case for this algorithm would be if there are many
1919 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1920 // graph walking), we may never find a path which is not liquidity-limited and has lower
1921 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1922 // Because we only consider paths with at least 5% of the total value being sent, the damage
1923 // from such a case should be limited, however this could be further reduced in the future by
1924 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1925 // limits for the purposes of fee calculation.
1927 // Alternatively, we could store more detailed path information in the heap (targets, below)
1928 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1929 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1930 // and practically (as we would need to store dynamically-allocated path information in heap
1931 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1932 // results of such an algorithm would likely be biased towards lower-value paths.
1934 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1935 // outside of our current search value, running a path search more times to gather candidate
1936 // paths at different values. While this may be acceptable, further path searches may increase
1937 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1938 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1939 // the same time, remaining generic across different payment values.
1941 let network_channels = network_graph.channels();
1942 let network_nodes = network_graph.nodes();
1944 if payment_params.max_path_count == 0 {
1945 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1948 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1949 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1951 let allow_mpp = if payment_params.max_path_count == 1 {
1953 } else if payment_params.payee.supports_basic_mpp() {
1955 } else if let Some(payee) = payee_node_id_opt {
1956 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1957 |info| info.features.supports_basic_mpp()))
1960 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1962 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph with a fee limit of {} msat",
1963 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
1964 if allow_mpp { "with" } else { "without" },
1965 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " },
1966 max_total_routing_fee_msat);
1969 // Prepare the data we'll use for payee-to-payer search by
1970 // inserting first hops suggested by the caller as targets.
1971 // Our search will then attempt to reach them while traversing from the payee node.
1972 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1973 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1974 if let Some(hops) = first_hops {
1976 if chan.get_outbound_payment_scid().is_none() {
1977 panic!("first_hops should be filled in with usable channels, not pending ones");
1979 if chan.counterparty.node_id == *our_node_pubkey {
1980 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1983 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1984 .or_insert(Vec::new())
1987 if first_hop_targets.is_empty() {
1988 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1992 let mut private_hop_key_cache = HashMap::with_capacity(
1993 payment_params.payee.unblinded_route_hints().iter().map(|path| path.0.len()).sum()
1996 // Because we store references to private hop node_ids in `dist`, below, we need them to exist
1997 // (as `NodeId`, not `PublicKey`) for the lifetime of `dist`. Thus, we calculate all the keys
1998 // we'll need here and simply fetch them when routing.
1999 private_hop_key_cache.insert(maybe_dummy_payee_pk, NodeId::from_pubkey(&maybe_dummy_payee_pk));
2000 for route in payment_params.payee.unblinded_route_hints().iter() {
2001 for hop in route.0.iter() {
2002 private_hop_key_cache.insert(hop.src_node_id, NodeId::from_pubkey(&hop.src_node_id));
2006 // The main heap containing all candidate next-hops sorted by their score (max(fee,
2007 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
2008 // adding duplicate entries when we find a better path to a given node.
2009 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
2011 // Map from node_id to information about the best current path to that node, including feerate
2013 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
2015 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
2016 // indicating that we may wish to try again with a higher value, potentially paying to meet an
2017 // htlc_minimum with extra fees while still finding a cheaper path.
2018 let mut hit_minimum_limit;
2020 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
2021 // We start with a path_value of the exact amount we want, and if that generates a route we may
2022 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
2023 // amount we want in total across paths, selecting the best subset at the end.
2024 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
2025 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
2026 let mut path_value_msat = final_value_msat;
2028 // Routing Fragmentation Mitigation heuristic:
2030 // Routing fragmentation across many payment paths increases the overall routing
2031 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
2032 // Taking too many smaller paths also increases the chance of payment failure.
2033 // Thus to avoid this effect, we require from our collected links to provide
2034 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
2035 // This requirement is currently set to be 1/max_path_count of the payment
2036 // value to ensure we only ever return routes that do not violate this limit.
2037 let minimal_value_contribution_msat: u64 = if allow_mpp {
2038 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
2043 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
2044 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
2045 // drop the requirement by setting this to 0.
2046 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
2048 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
2049 // determine if the channel can be used by additional MPP paths or to inform path finding
2050 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
2051 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
2053 let mut used_liquidities: HashMap<CandidateHopId, u64> =
2054 HashMap::with_capacity(network_nodes.len());
2056 // Keeping track of how much value we already collected across other paths. Helps to decide
2057 // when we want to stop looking for new paths.
2058 let mut already_collected_value_msat = 0;
2060 for (_, channels) in first_hop_targets.iter_mut() {
2061 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
2065 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
2066 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
2068 // Remember how many candidates we ignored to allow for some logging afterwards.
2069 let mut num_ignored_value_contribution: u32 = 0;
2070 let mut num_ignored_path_length_limit: u32 = 0;
2071 let mut num_ignored_cltv_delta_limit: u32 = 0;
2072 let mut num_ignored_previously_failed: u32 = 0;
2073 let mut num_ignored_total_fee_limit: u32 = 0;
2074 let mut num_ignored_avoid_overpayment: u32 = 0;
2075 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
2077 macro_rules! add_entry {
2078 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
2079 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
2080 // since that value has to be transferred over this channel.
2081 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
2082 ( $candidate: expr, $next_hops_fee_msat: expr,
2083 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
2084 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
2085 // We "return" whether we updated the path at the end, and how much we can route via
2086 // this channel, via this:
2087 let mut hop_contribution_amt_msat = None;
2088 // Channels to self should not be used. This is more of belt-and-suspenders, because in
2089 // practice these cases should be caught earlier:
2090 // - for regular channels at channel announcement (TODO)
2091 // - for first and last hops early in get_route
2092 let src_node_id = $candidate.source();
2093 if Some(src_node_id) != $candidate.target() {
2094 let scid_opt = $candidate.short_channel_id();
2095 let effective_capacity = $candidate.effective_capacity();
2096 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
2098 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
2099 // It may be misleading because we might later choose to reduce the value transferred
2100 // over these channels, and the channel which was insufficient might become sufficient.
2101 // Worst case: we drop a good channel here because it can't cover the high following
2102 // fees caused by one expensive channel, but then this channel could have been used
2103 // if the amount being transferred over this path is lower.
2104 // We do this for now, but this is a subject for removal.
2105 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
2106 let used_liquidity_msat = used_liquidities
2107 .get(&$candidate.id())
2108 .map_or(0, |used_liquidity_msat| {
2109 available_value_contribution_msat = available_value_contribution_msat
2110 .saturating_sub(*used_liquidity_msat);
2111 *used_liquidity_msat
2114 // Verify the liquidity offered by this channel complies to the minimal contribution.
2115 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
2116 // Do not consider candidate hops that would exceed the maximum path length.
2117 let path_length_to_node = $next_hops_path_length + 1;
2118 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
2120 // Do not consider candidates that exceed the maximum total cltv expiry limit.
2121 // In order to already account for some of the privacy enhancing random CLTV
2122 // expiry delta offset we add on top later, we subtract a rough estimate
2123 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
2124 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
2125 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
2126 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
2127 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
2128 .saturating_add($candidate.cltv_expiry_delta());
2129 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
2131 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
2132 // Includes paying fees for the use of the following channels.
2133 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
2134 Some(result) => result,
2135 // Can't overflow due to how the values were computed right above.
2136 None => unreachable!(),
2138 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2139 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
2140 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
2142 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2143 let may_overpay_to_meet_path_minimum_msat =
2144 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
2145 recommended_value_msat >= $candidate.htlc_minimum_msat()) ||
2146 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
2147 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
2149 let payment_failed_on_this_channel = match scid_opt {
2150 Some(scid) => payment_params.previously_failed_channels.contains(&scid),
2151 None => match $candidate.blinded_hint_idx() {
2153 payment_params.previously_failed_blinded_path_idxs.contains(&(idx as u64))
2159 let (should_log_candidate, first_hop_details) = match $candidate {
2160 CandidateRouteHop::FirstHop(hop) => (true, Some(hop.details)),
2161 CandidateRouteHop::PrivateHop(_) => (true, None),
2162 CandidateRouteHop::Blinded(_) => (true, None),
2163 CandidateRouteHop::OneHopBlinded(_) => (true, None),
2167 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
2168 // bother considering this channel. If retrying with recommended_value_msat may
2169 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
2170 // around again with a higher amount.
2171 if !contributes_sufficient_value {
2172 if should_log_candidate {
2173 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
2175 if let Some(details) = first_hop_details {
2177 "First hop candidate next_outbound_htlc_limit_msat: {}",
2178 details.next_outbound_htlc_limit_msat,
2182 num_ignored_value_contribution += 1;
2183 } else if exceeds_max_path_length {
2184 if should_log_candidate {
2185 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
2187 num_ignored_path_length_limit += 1;
2188 } else if exceeds_cltv_delta_limit {
2189 if should_log_candidate {
2190 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
2192 if let Some(_) = first_hop_details {
2194 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
2195 hop_total_cltv_delta,
2196 max_total_cltv_expiry_delta,
2200 num_ignored_cltv_delta_limit += 1;
2201 } else if payment_failed_on_this_channel {
2202 if should_log_candidate {
2203 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
2205 num_ignored_previously_failed += 1;
2206 } else if may_overpay_to_meet_path_minimum_msat {
2207 if should_log_candidate {
2209 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit.",
2210 LoggedCandidateHop(&$candidate));
2212 if let Some(details) = first_hop_details {
2214 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2215 details.next_outbound_htlc_minimum_msat,
2219 num_ignored_avoid_overpayment += 1;
2220 hit_minimum_limit = true;
2221 } else if over_path_minimum_msat {
2222 // Note that low contribution here (limited by available_liquidity_msat)
2223 // might violate htlc_minimum_msat on the hops which are next along the
2224 // payment path (upstream to the payee). To avoid that, we recompute
2225 // path fees knowing the final path contribution after constructing it.
2226 let curr_min = cmp::max(
2227 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
2229 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
2230 .saturating_add(curr_min);
2231 let hm_entry = dist.entry(src_node_id);
2232 let old_entry = hm_entry.or_insert_with(|| {
2233 // If there was previously no known way to access the source node
2234 // (recall it goes payee-to-payer) of short_channel_id, first add a
2235 // semi-dummy record just to compute the fees to reach the source node.
2236 // This will affect our decision on selecting short_channel_id
2237 // as a way to reach the $candidate.target() node.
2239 candidate: $candidate.clone(),
2241 next_hops_fee_msat: u64::max_value(),
2242 hop_use_fee_msat: u64::max_value(),
2243 total_fee_msat: u64::max_value(),
2244 path_htlc_minimum_msat,
2245 path_penalty_msat: u64::max_value(),
2246 was_processed: false,
2247 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2248 value_contribution_msat,
2252 #[allow(unused_mut)] // We only use the mut in cfg(test)
2253 let mut should_process = !old_entry.was_processed;
2254 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2256 // In test/fuzzing builds, we do extra checks to make sure the skipping
2257 // of already-seen nodes only happens in cases we expect (see below).
2258 if !should_process { should_process = true; }
2262 let mut hop_use_fee_msat = 0;
2263 let mut total_fee_msat: u64 = $next_hops_fee_msat;
2265 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2266 // will have the same effective-fee
2267 if src_node_id != our_node_id {
2268 // Note that `u64::max_value` means we'll always fail the
2269 // `old_entry.total_fee_msat > total_fee_msat` check below
2270 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
2271 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2274 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2275 if total_fee_msat > max_total_routing_fee_msat {
2276 if should_log_candidate {
2277 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2279 if let Some(_) = first_hop_details {
2281 "First hop candidate routing fee: {}. Limit: {}",
2283 max_total_routing_fee_msat,
2287 num_ignored_total_fee_limit += 1;
2289 let channel_usage = ChannelUsage {
2290 amount_msat: amount_to_transfer_over_msat,
2291 inflight_htlc_msat: used_liquidity_msat,
2294 let channel_penalty_msat =
2295 scorer.channel_penalty_msat($candidate,
2298 let path_penalty_msat = $next_hops_path_penalty_msat
2299 .saturating_add(channel_penalty_msat);
2301 // Update the way of reaching $candidate.source()
2302 // with the given short_channel_id (from $candidate.target()),
2303 // if this way is cheaper than the already known
2304 // (considering the cost to "reach" this channel from the route destination,
2305 // the cost of using this channel,
2306 // and the cost of routing to the source node of this channel).
2307 // Also, consider that htlc_minimum_msat_difference, because we might end up
2308 // paying it. Consider the following exploit:
2309 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2310 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2311 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2312 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2314 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2315 // but it may require additional tracking - we don't want to double-count
2316 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2317 // can't use something that may decrease on future hops.
2318 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2319 .saturating_add(old_entry.path_penalty_msat);
2320 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2321 .saturating_add(path_penalty_msat);
2323 if !old_entry.was_processed && new_cost < old_cost {
2324 let new_graph_node = RouteGraphNode {
2325 node_id: src_node_id,
2326 score: cmp::max(total_fee_msat, path_htlc_minimum_msat).saturating_add(path_penalty_msat),
2327 total_cltv_delta: hop_total_cltv_delta,
2328 value_contribution_msat,
2329 path_length_to_node,
2331 targets.push(new_graph_node);
2332 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2333 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2334 old_entry.total_fee_msat = total_fee_msat;
2335 old_entry.candidate = $candidate.clone();
2336 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2337 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2338 old_entry.path_penalty_msat = path_penalty_msat;
2339 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2341 old_entry.value_contribution_msat = value_contribution_msat;
2343 hop_contribution_amt_msat = Some(value_contribution_msat);
2344 } else if old_entry.was_processed && new_cost < old_cost {
2345 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2347 // If we're skipping processing a node which was previously
2348 // processed even though we found another path to it with a
2349 // cheaper fee, check that it was because the second path we
2350 // found (which we are processing now) has a lower value
2351 // contribution due to an HTLC minimum limit.
2353 // e.g. take a graph with two paths from node 1 to node 2, one
2354 // through channel A, and one through channel B. Channel A and
2355 // B are both in the to-process heap, with their scores set by
2356 // a higher htlc_minimum than fee.
2357 // Channel A is processed first, and the channels onwards from
2358 // node 1 are added to the to-process heap. Thereafter, we pop
2359 // Channel B off of the heap, note that it has a much more
2360 // restrictive htlc_maximum_msat, and recalculate the fees for
2361 // all of node 1's channels using the new, reduced, amount.
2363 // This would be bogus - we'd be selecting a higher-fee path
2364 // with a lower htlc_maximum_msat instead of the one we'd
2365 // already decided to use.
2366 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2368 value_contribution_msat + path_penalty_msat <
2369 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2376 if should_log_candidate {
2378 "Ignoring {} due to its htlc_minimum_msat limit.",
2379 LoggedCandidateHop(&$candidate));
2381 if let Some(details) = first_hop_details {
2383 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2384 details.next_outbound_htlc_minimum_msat,
2388 num_ignored_htlc_minimum_msat_limit += 1;
2392 hop_contribution_amt_msat
2396 let default_node_features = default_node_features();
2398 // Find ways (channels with destination) to reach a given node and store them
2399 // in the corresponding data structures (routing graph etc).
2400 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2401 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2402 // This data can later be helpful to optimize routing (pay lower fees).
2403 macro_rules! add_entries_to_cheapest_to_target_node {
2404 ( $node: expr, $node_id: expr, $next_hops_value_contribution: expr,
2405 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2406 let fee_to_target_msat;
2407 let next_hops_path_htlc_minimum_msat;
2408 let next_hops_path_penalty_msat;
2409 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
2410 let was_processed = elem.was_processed;
2411 elem.was_processed = true;
2412 fee_to_target_msat = elem.total_fee_msat;
2413 next_hops_path_htlc_minimum_msat = elem.path_htlc_minimum_msat;
2414 next_hops_path_penalty_msat = elem.path_penalty_msat;
2417 // Entries are added to dist in add_entry!() when there is a channel from a node.
2418 // Because there are no channels from payee, it will not have a dist entry at this point.
2419 // If we're processing any other node, it is always be the result of a channel from it.
2420 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2421 fee_to_target_msat = 0;
2422 next_hops_path_htlc_minimum_msat = 0;
2423 next_hops_path_penalty_msat = 0;
2428 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
2429 for details in first_channels {
2430 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2431 details, payer_node_id: &our_node_id,
2433 add_entry!(&candidate, fee_to_target_msat,
2434 $next_hops_value_contribution,
2435 next_hops_path_htlc_minimum_msat, next_hops_path_penalty_msat,
2436 $next_hops_cltv_delta, $next_hops_path_length);
2440 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2443 &default_node_features
2446 if !features.requires_unknown_bits() {
2447 for chan_id in $node.channels.iter() {
2448 let chan = network_channels.get(chan_id).unwrap();
2449 if !chan.features.requires_unknown_bits() {
2450 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2451 if first_hops.is_none() || *source != our_node_id {
2452 if directed_channel.direction().enabled {
2453 let candidate = CandidateRouteHop::PublicHop(PublicHopCandidate {
2454 info: directed_channel,
2455 short_channel_id: *chan_id,
2457 add_entry!(&candidate,
2459 $next_hops_value_contribution,
2460 next_hops_path_htlc_minimum_msat,
2461 next_hops_path_penalty_msat,
2462 $next_hops_cltv_delta, $next_hops_path_length);
2473 let mut payment_paths = Vec::<PaymentPath>::new();
2475 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2476 'paths_collection: loop {
2477 // For every new path, start from scratch, except for used_liquidities, which
2478 // helps to avoid reusing previously selected paths in future iterations.
2481 hit_minimum_limit = false;
2483 // If first hop is a private channel and the only way to reach the payee, this is the only
2484 // place where it could be added.
2485 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2486 for details in first_channels {
2487 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2488 details, payer_node_id: &our_node_id,
2490 let added = add_entry!(&candidate, 0, path_value_msat,
2491 0, 0u64, 0, 0).is_some();
2492 log_trace!(logger, "{} direct route to payee via {}",
2493 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2497 // Add the payee as a target, so that the payee-to-payer
2498 // search algorithm knows what to start with.
2499 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2500 // The payee is not in our network graph, so nothing to add here.
2501 // There is still a chance of reaching them via last_hops though,
2502 // so don't yet fail the payment here.
2503 // If not, targets.pop() will not even let us enter the loop in step 2.
2506 add_entries_to_cheapest_to_target_node!(node, payee, path_value_msat, 0, 0);
2511 // If a caller provided us with last hops, add them to routing targets. Since this happens
2512 // earlier than general path finding, they will be somewhat prioritized, although currently
2513 // it matters only if the fees are exactly the same.
2514 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2515 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2516 let have_intro_node_in_graph =
2517 // Only add the hops in this route to our candidate set if either
2518 // we have a direct channel to the first hop or the first hop is
2519 // in the regular network graph.
2520 first_hop_targets.get(&intro_node_id).is_some() ||
2521 network_nodes.get(&intro_node_id).is_some();
2522 if !have_intro_node_in_graph || our_node_id == intro_node_id { continue }
2523 let candidate = if hint.1.blinded_hops.len() == 1 {
2524 CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, hint_idx })
2525 } else { CandidateRouteHop::Blinded(BlindedPathCandidate { hint, hint_idx }) };
2526 let mut path_contribution_msat = path_value_msat;
2527 if let Some(hop_used_msat) = add_entry!(&candidate,
2528 0, path_contribution_msat, 0, 0_u64, 0, 0)
2530 path_contribution_msat = hop_used_msat;
2532 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2533 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2535 for details in first_channels {
2536 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2537 details, payer_node_id: &our_node_id,
2539 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2543 let path_min = candidate.htlc_minimum_msat().saturating_add(
2544 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2545 add_entry!(&first_hop_candidate, blinded_path_fee,
2546 path_contribution_msat, path_min, 0_u64, candidate.cltv_expiry_delta(),
2547 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2551 for route in payment_params.payee.unblinded_route_hints().iter()
2552 .filter(|route| !route.0.is_empty())
2554 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2555 let first_hop_src_is_reachable =
2556 // Only add the hops in this route to our candidate set if either we are part of
2557 // the first hop, we have a direct channel to the first hop, or the first hop is in
2558 // the regular network graph.
2559 our_node_id == first_hop_src_id ||
2560 first_hop_targets.get(&first_hop_src_id).is_some() ||
2561 network_nodes.get(&first_hop_src_id).is_some();
2562 if first_hop_src_is_reachable {
2563 // We start building the path from reverse, i.e., from payee
2564 // to the first RouteHintHop in the path.
2565 let hop_iter = route.0.iter().rev();
2566 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2567 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2568 let mut hop_used = true;
2569 let mut aggregate_next_hops_fee_msat: u64 = 0;
2570 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2571 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2572 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2573 let mut aggregate_next_hops_path_length: u8 = 0;
2574 let mut aggregate_path_contribution_msat = path_value_msat;
2576 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2577 let target = private_hop_key_cache.get(&prev_hop_id).unwrap();
2579 if let Some(first_channels) = first_hop_targets.get(&target) {
2580 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2581 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2582 hop.short_channel_id);
2587 let candidate = network_channels
2588 .get(&hop.short_channel_id)
2589 .and_then(|channel| channel.as_directed_to(&target))
2590 .map(|(info, _)| CandidateRouteHop::PublicHop(PublicHopCandidate {
2592 short_channel_id: hop.short_channel_id,
2594 .unwrap_or_else(|| CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: hop, target_node_id: target }));
2596 if let Some(hop_used_msat) = add_entry!(&candidate,
2597 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2598 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2599 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2601 aggregate_path_contribution_msat = hop_used_msat;
2603 // If this hop was not used then there is no use checking the preceding
2604 // hops in the RouteHint. We can break by just searching for a direct
2605 // channel between last checked hop and first_hop_targets.
2609 let used_liquidity_msat = used_liquidities
2610 .get(&candidate.id()).copied()
2612 let channel_usage = ChannelUsage {
2613 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2614 inflight_htlc_msat: used_liquidity_msat,
2615 effective_capacity: candidate.effective_capacity(),
2617 let channel_penalty_msat = scorer.channel_penalty_msat(
2618 &candidate, channel_usage, score_params
2620 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2621 .saturating_add(channel_penalty_msat);
2623 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2624 .saturating_add(hop.cltv_expiry_delta as u32);
2626 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2629 // Searching for a direct channel between last checked hop and first_hop_targets
2630 if let Some(first_channels) = first_hop_targets.get_mut(&target) {
2631 sort_first_hop_channels(first_channels, &used_liquidities,
2632 recommended_value_msat, our_node_pubkey);
2633 for details in first_channels {
2634 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2635 details, payer_node_id: &our_node_id,
2637 add_entry!(&first_hop_candidate,
2638 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2639 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2640 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2648 // In the next values of the iterator, the aggregate fees already reflects
2649 // the sum of value sent from payer (final_value_msat) and routing fees
2650 // for the last node in the RouteHint. We need to just add the fees to
2651 // route through the current node so that the preceding node (next iteration)
2653 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2654 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2655 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2657 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2658 // this route hint's source node to forward said min over this channel.
2659 aggregate_next_hops_path_htlc_minimum_msat = {
2660 let curr_htlc_min = cmp::max(
2661 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2663 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2664 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2667 if idx == route.0.len() - 1 {
2668 // The last hop in this iterator is the first hop in
2669 // overall RouteHint.
2670 // If this hop connects to a node with which we have a direct channel,
2671 // ignore the network graph and, if the last hop was added, add our
2672 // direct channel to the candidate set.
2674 // Note that we *must* check if the last hop was added as `add_entry`
2675 // always assumes that the third argument is a node to which we have a
2677 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2678 sort_first_hop_channels(first_channels, &used_liquidities,
2679 recommended_value_msat, our_node_pubkey);
2680 for details in first_channels {
2681 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2682 details, payer_node_id: &our_node_id,
2684 add_entry!(&first_hop_candidate,
2685 aggregate_next_hops_fee_msat,
2686 aggregate_path_contribution_msat,
2687 aggregate_next_hops_path_htlc_minimum_msat,
2688 aggregate_next_hops_path_penalty_msat,
2689 aggregate_next_hops_cltv_delta,
2690 aggregate_next_hops_path_length);
2698 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2700 // At this point, targets are filled with the data from first and
2701 // last hops communicated by the caller, and the payment receiver.
2702 let mut found_new_path = false;
2705 // If this loop terminates due the exhaustion of targets, two situations are possible:
2706 // - not enough outgoing liquidity:
2707 // 0 < already_collected_value_msat < final_value_msat
2708 // - enough outgoing liquidity:
2709 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2710 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2711 // paths_collection will be stopped because found_new_path==false.
2712 // This is not necessarily a routing failure.
2713 'path_construction: while let Some(RouteGraphNode { node_id, total_cltv_delta, mut value_contribution_msat, path_length_to_node, .. }) = targets.pop() {
2715 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2716 // traversing the graph and arrange the path out of what we found.
2717 if node_id == our_node_id {
2718 let mut new_entry = dist.remove(&our_node_id).unwrap();
2719 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2722 let mut features_set = false;
2723 let target = ordered_hops.last().unwrap().0.candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2724 if let Some(first_channels) = first_hop_targets.get(&target) {
2725 for details in first_channels {
2726 if let CandidateRouteHop::FirstHop(FirstHopCandidate { details: last_hop_details, .. })
2727 = ordered_hops.last().unwrap().0.candidate
2729 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2730 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2731 features_set = true;
2738 if let Some(node) = network_nodes.get(&target) {
2739 if let Some(node_info) = node.announcement_info.as_ref() {
2740 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2742 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2745 // We can fill in features for everything except hops which were
2746 // provided via the invoice we're paying. We could guess based on the
2747 // recipient's features but for now we simply avoid guessing at all.
2751 // Means we successfully traversed from the payer to the payee, now
2752 // save this path for the payment route. Also, update the liquidity
2753 // remaining on the used hops, so that we take them into account
2754 // while looking for more paths.
2755 if target == maybe_dummy_payee_node_id {
2759 new_entry = match dist.remove(&target) {
2760 Some(payment_hop) => payment_hop,
2761 // We can't arrive at None because, if we ever add an entry to targets,
2762 // we also fill in the entry in dist (see add_entry!).
2763 None => unreachable!(),
2765 // We "propagate" the fees one hop backward (topologically) here,
2766 // so that fees paid for a HTLC forwarding on the current channel are
2767 // associated with the previous channel (where they will be subtracted).
2768 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2769 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2771 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2772 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2774 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2775 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2777 let mut payment_path = PaymentPath {hops: ordered_hops};
2779 // We could have possibly constructed a slightly inconsistent path: since we reduce
2780 // value being transferred along the way, we could have violated htlc_minimum_msat
2781 // on some channels we already passed (assuming dest->source direction). Here, we
2782 // recompute the fees again, so that if that's the case, we match the currently
2783 // underpaid htlc_minimum_msat with fees.
2784 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2785 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2786 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2788 // Since a path allows to transfer as much value as
2789 // the smallest channel it has ("bottleneck"), we should recompute
2790 // the fees so sender HTLC don't overpay fees when traversing
2791 // larger channels than the bottleneck. This may happen because
2792 // when we were selecting those channels we were not aware how much value
2793 // this path will transfer, and the relative fee for them
2794 // might have been computed considering a larger value.
2795 // Remember that we used these channels so that we don't rely
2796 // on the same liquidity in future paths.
2797 let mut prevented_redundant_path_selection = false;
2798 for (hop, _) in payment_path.hops.iter() {
2799 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2800 let used_liquidity_msat = used_liquidities
2801 .entry(hop.candidate.id())
2802 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2803 .or_insert(spent_on_hop_msat);
2804 let hop_capacity = hop.candidate.effective_capacity();
2805 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2806 if *used_liquidity_msat == hop_max_msat {
2807 // If this path used all of this channel's available liquidity, we know
2808 // this path will not be selected again in the next loop iteration.
2809 prevented_redundant_path_selection = true;
2811 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2813 if !prevented_redundant_path_selection {
2814 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2815 // we'll probably end up picking the same path again on the next iteration.
2816 // Decrease the available liquidity of a hop in the middle of the path.
2817 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2818 let exhausted = u64::max_value();
2820 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2821 LoggedCandidateHop(victim_candidate));
2822 if let Some(scid) = victim_candidate.short_channel_id() {
2823 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2824 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2828 // Track the total amount all our collected paths allow to send so that we know
2829 // when to stop looking for more paths
2830 already_collected_value_msat += value_contribution_msat;
2832 payment_paths.push(payment_path);
2833 found_new_path = true;
2834 break 'path_construction;
2837 // If we found a path back to the payee, we shouldn't try to process it again. This is
2838 // the equivalent of the `elem.was_processed` check in
2839 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2840 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2842 // Otherwise, since the current target node is not us,
2843 // keep "unrolling" the payment graph from payee to payer by
2844 // finding a way to reach the current target from the payer side.
2845 match network_nodes.get(&node_id) {
2848 add_entries_to_cheapest_to_target_node!(node, node_id,
2849 value_contribution_msat,
2850 total_cltv_delta, path_length_to_node);
2856 if !found_new_path && channel_saturation_pow_half != 0 {
2857 channel_saturation_pow_half = 0;
2858 continue 'paths_collection;
2860 // If we don't support MPP, no use trying to gather more value ever.
2861 break 'paths_collection;
2865 // Stop either when the recommended value is reached or if no new path was found in this
2867 // In the latter case, making another path finding attempt won't help,
2868 // because we deterministically terminated the search due to low liquidity.
2869 if !found_new_path && channel_saturation_pow_half != 0 {
2870 channel_saturation_pow_half = 0;
2871 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2872 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
2873 path_value_msat = recommended_value_msat;
2874 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2875 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2876 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2877 break 'paths_collection;
2878 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2879 // Further, if this was our first walk of the graph, and we weren't limited by an
2880 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2881 // limited by an htlc_minimum_msat value, find another path with a higher value,
2882 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2883 // still keeping a lower total fee than this path.
2884 if !hit_minimum_limit {
2885 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2886 break 'paths_collection;
2888 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.");
2889 path_value_msat = recommended_value_msat;
2893 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2894 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
2895 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
2896 num_ignored_total_fee_limit;
2897 if num_ignored_total > 0 {
2899 "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.",
2900 num_ignored_value_contribution, num_ignored_path_length_limit,
2901 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
2902 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
2903 num_ignored_total_fee_limit, num_ignored_total);
2907 if payment_paths.len() == 0 {
2908 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2911 if already_collected_value_msat < final_value_msat {
2912 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2916 let mut selected_route = payment_paths;
2918 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2919 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2921 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2922 // the value they contribute towards the payment amount.
2923 // We sort in descending order as we will remove from the front in `retain`, next.
2924 selected_route.sort_unstable_by(|a, b|
2925 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2926 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2929 // We should make sure that at least 1 path left.
2930 let mut paths_left = selected_route.len();
2931 selected_route.retain(|path| {
2932 if paths_left == 1 {
2935 let path_value_msat = path.get_value_msat();
2936 if path_value_msat <= overpaid_value_msat {
2937 overpaid_value_msat -= path_value_msat;
2943 debug_assert!(selected_route.len() > 0);
2945 if overpaid_value_msat != 0 {
2947 // Now, subtract the remaining overpaid value from the most-expensive path.
2948 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2949 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2950 selected_route.sort_unstable_by(|a, b| {
2951 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2952 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2953 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2955 let expensive_payment_path = selected_route.first_mut().unwrap();
2957 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2958 // can't go negative.
2959 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2960 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2964 // Sort by the path itself and combine redundant paths.
2965 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2966 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2968 selected_route.sort_unstable_by_key(|path| {
2969 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2970 debug_assert!(path.hops.len() <= key.len());
2971 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
2976 for idx in 0..(selected_route.len() - 1) {
2977 if idx + 1 >= selected_route.len() { break; }
2978 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
2979 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
2980 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2981 selected_route[idx].update_value_and_recompute_fees(new_value);
2982 selected_route.remove(idx + 1);
2986 let mut paths = Vec::new();
2987 for payment_path in selected_route {
2988 let mut hops = Vec::with_capacity(payment_path.hops.len());
2989 for (hop, node_features) in payment_path.hops.iter()
2990 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2992 let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
2993 let maybe_announced_channel = if let CandidateRouteHop::PublicHop(_) = hop.candidate {
2994 // If we sourced the hop from the graph we're sure the target node is announced.
2996 } else if let CandidateRouteHop::FirstHop(first_hop) = &hop.candidate {
2997 // If this is a first hop we also know if it's announced.
2998 first_hop.details.is_public
3000 // If we sourced it any other way, we double-check the network graph to see if
3001 // there are announced channels between the endpoints. If so, the hop might be
3002 // referring to any of the announced channels, as its `short_channel_id` might be
3003 // an alias, in which case we don't take any chances here.
3004 network_graph.node(&target).map_or(false, |hop_node|
3005 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
3006 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
3010 hops.push(RouteHop {
3011 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
3012 node_features: node_features.clone(),
3013 short_channel_id: hop.candidate.short_channel_id().unwrap(),
3014 channel_features: hop.candidate.features(),
3015 fee_msat: hop.fee_msat,
3016 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
3017 maybe_announced_channel,
3020 let mut final_cltv_delta = final_cltv_expiry_delta;
3021 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
3022 if let Some(blinded_path) = h.candidate.blinded_path() {
3023 final_cltv_delta = h.candidate.cltv_expiry_delta();
3025 hops: blinded_path.blinded_hops.clone(),
3026 blinding_point: blinded_path.blinding_point,
3027 excess_final_cltv_expiry_delta: 0,
3028 final_value_msat: h.fee_msat,
3032 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
3033 // applicable for the previous hop.
3034 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
3035 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
3038 paths.push(Path { hops, blinded_tail });
3040 // Make sure we would never create a route with more paths than we allow.
3041 debug_assert!(paths.len() <= payment_params.max_path_count.into());
3043 if let Some(node_features) = payment_params.payee.node_features() {
3044 for path in paths.iter_mut() {
3045 path.hops.last_mut().unwrap().node_features = node_features.clone();
3049 let route = Route { paths, route_params: Some(route_params.clone()) };
3051 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
3052 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
3053 if route.get_total_fees() > max_total_routing_fee_msat {
3054 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
3055 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
3059 log_info!(logger, "Got route: {}", log_route!(route));
3063 // When an adversarial intermediary node observes a payment, it may be able to infer its
3064 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
3065 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
3066 // payment path by adding a randomized 'shadow route' offset to the final hop.
3067 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
3068 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
3070 let network_channels = network_graph.channels();
3071 let network_nodes = network_graph.nodes();
3073 for path in route.paths.iter_mut() {
3074 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
3076 // Remember the last three nodes of the random walk and avoid looping back on them.
3077 // Init with the last three nodes from the actual path, if possible.
3078 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
3079 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
3080 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
3082 // Choose the last publicly known node as the starting point for the random walk.
3083 let mut cur_hop: Option<NodeId> = None;
3084 let mut path_nonce = [0u8; 12];
3085 if let Some(starting_hop) = path.hops.iter().rev()
3086 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
3087 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
3088 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
3091 // Init PRNG with the path-dependant nonce, which is static for private paths.
3092 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
3093 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
3095 // Pick a random path length in [1 .. 3]
3096 prng.process_in_place(&mut random_path_bytes);
3097 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
3099 for random_hop in 0..random_walk_length {
3100 // If we don't find a suitable offset in the public network graph, we default to
3101 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3102 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
3104 if let Some(cur_node_id) = cur_hop {
3105 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
3106 // Randomly choose the next unvisited hop.
3107 prng.process_in_place(&mut random_path_bytes);
3108 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
3109 .checked_rem(cur_node.channels.len())
3110 .and_then(|index| cur_node.channels.get(index))
3111 .and_then(|id| network_channels.get(id)) {
3112 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
3113 if !nodes_to_avoid.iter().any(|x| x == next_id) {
3114 nodes_to_avoid[random_hop] = *next_id;
3115 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
3116 cur_hop = Some(*next_id);
3123 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
3124 .checked_add(random_hop_offset)
3125 .unwrap_or(shadow_ctlv_expiry_delta_offset);
3128 // Limit the total offset to reduce the worst-case locked liquidity timevalue
3129 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
3130 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
3132 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
3133 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3134 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
3135 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
3136 max_path_offset = cmp::max(
3137 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
3138 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
3139 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
3141 // Add 'shadow' CLTV offset to the final hop
3142 if let Some(tail) = path.blinded_tail.as_mut() {
3143 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
3144 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
3146 if let Some(last_hop) = path.hops.last_mut() {
3147 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
3148 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
3153 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
3154 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
3156 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
3157 pub fn build_route_from_hops<L: Deref, GL: Deref>(
3158 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3159 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
3160 ) -> Result<Route, LightningError>
3161 where L::Target: Logger, GL::Target: Logger {
3162 let graph_lock = network_graph.read_only();
3163 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
3164 &graph_lock, logger, random_seed_bytes)?;
3165 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
3169 fn build_route_from_hops_internal<L: Deref>(
3170 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3171 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
3172 ) -> Result<Route, LightningError> where L::Target: Logger {
3175 our_node_id: NodeId,
3176 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
3179 impl ScoreLookUp for HopScorer {
3180 #[cfg(not(c_bindings))]
3181 type ScoreParams = ();
3182 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
3183 _usage: ChannelUsage, _score_params: &crate::routing::scoring::ProbabilisticScoringFeeParameters) -> u64
3185 let mut cur_id = self.our_node_id;
3186 for i in 0..self.hop_ids.len() {
3187 if let Some(next_id) = self.hop_ids[i] {
3188 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
3200 impl<'a> Writeable for HopScorer {
3202 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
3207 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
3208 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
3211 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
3212 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
3213 for i in 0..hops.len() {
3214 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
3217 let scorer = HopScorer { our_node_id, hop_ids };
3219 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
3224 use crate::blinded_path::{BlindedHop, BlindedPath};
3225 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
3226 use crate::routing::utxo::UtxoResult;
3227 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
3228 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
3229 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop, PublicHopCandidate};
3230 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
3231 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
3232 use crate::chain::transaction::OutPoint;
3233 use crate::sign::EntropySource;
3234 use crate::ln::ChannelId;
3235 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
3236 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
3237 use crate::ln::channelmanager;
3238 use crate::offers::invoice::BlindedPayInfo;
3239 use crate::util::config::UserConfig;
3240 use crate::util::test_utils as ln_test_utils;
3241 use crate::crypto::chacha20::ChaCha20;
3242 use crate::util::ser::{Readable, Writeable};
3244 use crate::util::ser::Writer;
3246 use bitcoin::hashes::Hash;
3247 use bitcoin::network::constants::Network;
3248 use bitcoin::blockdata::constants::ChainHash;
3249 use bitcoin::blockdata::script::Builder;
3250 use bitcoin::blockdata::opcodes;
3251 use bitcoin::blockdata::transaction::TxOut;
3252 use bitcoin::hashes::hex::FromHex;
3253 use bitcoin::secp256k1::{PublicKey,SecretKey};
3254 use bitcoin::secp256k1::Secp256k1;
3256 use crate::io::Cursor;
3257 use crate::prelude::*;
3258 use crate::sync::Arc;
3260 use core::convert::TryInto;
3262 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3263 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
3264 channelmanager::ChannelDetails {
3265 channel_id: ChannelId::new_zero(),
3266 counterparty: channelmanager::ChannelCounterparty {
3269 unspendable_punishment_reserve: 0,
3270 forwarding_info: None,
3271 outbound_htlc_minimum_msat: None,
3272 outbound_htlc_maximum_msat: None,
3274 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3277 outbound_scid_alias: None,
3278 inbound_scid_alias: None,
3279 channel_value_satoshis: 0,
3282 outbound_capacity_msat,
3283 next_outbound_htlc_limit_msat: outbound_capacity_msat,
3284 next_outbound_htlc_minimum_msat: 0,
3285 inbound_capacity_msat: 42,
3286 unspendable_punishment_reserve: None,
3287 confirmations_required: None,
3288 confirmations: None,
3289 force_close_spend_delay: None,
3290 is_outbound: true, is_channel_ready: true,
3291 is_usable: true, is_public: true,
3292 inbound_htlc_minimum_msat: None,
3293 inbound_htlc_maximum_msat: None,
3295 feerate_sat_per_1000_weight: None,
3296 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
3301 fn simple_route_test() {
3302 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3303 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3304 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3305 let scorer = ln_test_utils::TestScorer::new();
3306 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3307 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3309 // Simple route to 2 via 1
3311 let route_params = RouteParameters::from_payment_params_and_value(
3312 payment_params.clone(), 0);
3313 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3314 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3315 &Default::default(), &random_seed_bytes) {
3316 assert_eq!(err, "Cannot send a payment of 0 msat");
3317 } else { panic!(); }
3319 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3320 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3321 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3322 assert_eq!(route.paths[0].hops.len(), 2);
3324 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3325 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3326 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3327 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3328 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3329 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3331 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3332 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3333 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3334 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3335 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3336 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3340 fn invalid_first_hop_test() {
3341 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3342 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3343 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3344 let scorer = ln_test_utils::TestScorer::new();
3345 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3346 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3348 // Simple route to 2 via 1
3350 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3352 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3353 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3354 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3355 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3356 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3357 } else { panic!(); }
3359 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3360 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3361 assert_eq!(route.paths[0].hops.len(), 2);
3365 fn htlc_minimum_test() {
3366 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3367 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3368 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3369 let scorer = ln_test_utils::TestScorer::new();
3370 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3371 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3373 // Simple route to 2 via 1
3375 // Disable other paths
3376 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3377 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3378 short_channel_id: 12,
3380 flags: 2, // to disable
3381 cltv_expiry_delta: 0,
3382 htlc_minimum_msat: 0,
3383 htlc_maximum_msat: MAX_VALUE_MSAT,
3385 fee_proportional_millionths: 0,
3386 excess_data: Vec::new()
3388 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3389 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3390 short_channel_id: 3,
3392 flags: 2, // to disable
3393 cltv_expiry_delta: 0,
3394 htlc_minimum_msat: 0,
3395 htlc_maximum_msat: MAX_VALUE_MSAT,
3397 fee_proportional_millionths: 0,
3398 excess_data: Vec::new()
3400 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3401 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3402 short_channel_id: 13,
3404 flags: 2, // to disable
3405 cltv_expiry_delta: 0,
3406 htlc_minimum_msat: 0,
3407 htlc_maximum_msat: MAX_VALUE_MSAT,
3409 fee_proportional_millionths: 0,
3410 excess_data: Vec::new()
3412 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3413 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3414 short_channel_id: 6,
3416 flags: 2, // to disable
3417 cltv_expiry_delta: 0,
3418 htlc_minimum_msat: 0,
3419 htlc_maximum_msat: MAX_VALUE_MSAT,
3421 fee_proportional_millionths: 0,
3422 excess_data: Vec::new()
3424 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3425 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3426 short_channel_id: 7,
3428 flags: 2, // to disable
3429 cltv_expiry_delta: 0,
3430 htlc_minimum_msat: 0,
3431 htlc_maximum_msat: MAX_VALUE_MSAT,
3433 fee_proportional_millionths: 0,
3434 excess_data: Vec::new()
3437 // Check against amount_to_transfer_over_msat.
3438 // Set minimal HTLC of 200_000_000 msat.
3439 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3440 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3441 short_channel_id: 2,
3444 cltv_expiry_delta: 0,
3445 htlc_minimum_msat: 200_000_000,
3446 htlc_maximum_msat: MAX_VALUE_MSAT,
3448 fee_proportional_millionths: 0,
3449 excess_data: Vec::new()
3452 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3454 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3455 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3456 short_channel_id: 4,
3459 cltv_expiry_delta: 0,
3460 htlc_minimum_msat: 0,
3461 htlc_maximum_msat: 199_999_999,
3463 fee_proportional_millionths: 0,
3464 excess_data: Vec::new()
3467 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3468 let route_params = RouteParameters::from_payment_params_and_value(
3469 payment_params, 199_999_999);
3470 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3471 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3472 &Default::default(), &random_seed_bytes) {
3473 assert_eq!(err, "Failed to find a path to the given destination");
3474 } else { panic!(); }
3476 // Lift the restriction on the first hop.
3477 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3478 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3479 short_channel_id: 2,
3482 cltv_expiry_delta: 0,
3483 htlc_minimum_msat: 0,
3484 htlc_maximum_msat: MAX_VALUE_MSAT,
3486 fee_proportional_millionths: 0,
3487 excess_data: Vec::new()
3490 // A payment above the minimum should pass
3491 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3492 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3493 assert_eq!(route.paths[0].hops.len(), 2);
3497 fn htlc_minimum_overpay_test() {
3498 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3499 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3500 let config = UserConfig::default();
3501 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3502 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3504 let scorer = ln_test_utils::TestScorer::new();
3505 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3506 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3508 // A route to node#2 via two paths.
3509 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3510 // Thus, they can't send 60 without overpaying.
3511 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3512 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3513 short_channel_id: 2,
3516 cltv_expiry_delta: 0,
3517 htlc_minimum_msat: 35_000,
3518 htlc_maximum_msat: 40_000,
3520 fee_proportional_millionths: 0,
3521 excess_data: Vec::new()
3523 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3524 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3525 short_channel_id: 12,
3528 cltv_expiry_delta: 0,
3529 htlc_minimum_msat: 35_000,
3530 htlc_maximum_msat: 40_000,
3532 fee_proportional_millionths: 0,
3533 excess_data: Vec::new()
3537 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3538 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3539 short_channel_id: 13,
3542 cltv_expiry_delta: 0,
3543 htlc_minimum_msat: 0,
3544 htlc_maximum_msat: MAX_VALUE_MSAT,
3546 fee_proportional_millionths: 0,
3547 excess_data: Vec::new()
3549 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3550 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3551 short_channel_id: 4,
3554 cltv_expiry_delta: 0,
3555 htlc_minimum_msat: 0,
3556 htlc_maximum_msat: MAX_VALUE_MSAT,
3558 fee_proportional_millionths: 0,
3559 excess_data: Vec::new()
3562 // Disable other paths
3563 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3564 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3565 short_channel_id: 1,
3567 flags: 2, // to disable
3568 cltv_expiry_delta: 0,
3569 htlc_minimum_msat: 0,
3570 htlc_maximum_msat: MAX_VALUE_MSAT,
3572 fee_proportional_millionths: 0,
3573 excess_data: Vec::new()
3576 let mut route_params = RouteParameters::from_payment_params_and_value(
3577 payment_params.clone(), 60_000);
3578 route_params.max_total_routing_fee_msat = Some(15_000);
3579 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3580 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3581 // Overpay fees to hit htlc_minimum_msat.
3582 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3583 // TODO: this could be better balanced to overpay 10k and not 15k.
3584 assert_eq!(overpaid_fees, 15_000);
3586 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3587 // while taking even more fee to match htlc_minimum_msat.
3588 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3589 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3590 short_channel_id: 12,
3593 cltv_expiry_delta: 0,
3594 htlc_minimum_msat: 65_000,
3595 htlc_maximum_msat: 80_000,
3597 fee_proportional_millionths: 0,
3598 excess_data: Vec::new()
3600 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3601 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3602 short_channel_id: 2,
3605 cltv_expiry_delta: 0,
3606 htlc_minimum_msat: 0,
3607 htlc_maximum_msat: MAX_VALUE_MSAT,
3609 fee_proportional_millionths: 0,
3610 excess_data: Vec::new()
3612 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3613 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3614 short_channel_id: 4,
3617 cltv_expiry_delta: 0,
3618 htlc_minimum_msat: 0,
3619 htlc_maximum_msat: MAX_VALUE_MSAT,
3621 fee_proportional_millionths: 100_000,
3622 excess_data: Vec::new()
3625 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3626 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3627 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3628 assert_eq!(route.paths.len(), 1);
3629 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3630 let fees = route.paths[0].hops[0].fee_msat;
3631 assert_eq!(fees, 5_000);
3633 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_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 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3637 // the other channel.
3638 assert_eq!(route.paths.len(), 1);
3639 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3640 let fees = route.paths[0].hops[0].fee_msat;
3641 assert_eq!(fees, 5_000);
3645 fn htlc_minimum_recipient_overpay_test() {
3646 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3647 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3648 let config = UserConfig::default();
3649 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3650 let scorer = ln_test_utils::TestScorer::new();
3651 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3652 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3654 // Route to node2 over a single path which requires overpaying the recipient themselves.
3656 // First disable all paths except the us -> node1 -> node2 path
3657 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3658 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3659 short_channel_id: 13,
3662 cltv_expiry_delta: 0,
3663 htlc_minimum_msat: 0,
3664 htlc_maximum_msat: 0,
3666 fee_proportional_millionths: 0,
3667 excess_data: Vec::new()
3670 // Set channel 4 to free but with a high htlc_minimum_msat
3671 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3672 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3673 short_channel_id: 4,
3676 cltv_expiry_delta: 0,
3677 htlc_minimum_msat: 15_000,
3678 htlc_maximum_msat: MAX_VALUE_MSAT,
3680 fee_proportional_millionths: 0,
3681 excess_data: Vec::new()
3684 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3685 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3686 // what we try to find a route for, so this test only just happens to work out to exactly
3688 let mut route_params = RouteParameters::from_payment_params_and_value(
3689 payment_params.clone(), 5_000);
3690 route_params.max_total_routing_fee_msat = Some(9_999);
3691 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3692 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3693 &Default::default(), &random_seed_bytes) {
3694 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3695 } else { panic!(); }
3697 let mut route_params = RouteParameters::from_payment_params_and_value(
3698 payment_params.clone(), 5_000);
3699 route_params.max_total_routing_fee_msat = Some(10_000);
3700 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3701 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3702 assert_eq!(route.get_total_fees(), 10_000);
3706 fn disable_channels_test() {
3707 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3708 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3709 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3710 let scorer = ln_test_utils::TestScorer::new();
3711 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3712 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3714 // // Disable channels 4 and 12 by flags=2
3715 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3716 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3717 short_channel_id: 4,
3719 flags: 2, // to disable
3720 cltv_expiry_delta: 0,
3721 htlc_minimum_msat: 0,
3722 htlc_maximum_msat: MAX_VALUE_MSAT,
3724 fee_proportional_millionths: 0,
3725 excess_data: Vec::new()
3727 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3728 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3729 short_channel_id: 12,
3731 flags: 2, // to disable
3732 cltv_expiry_delta: 0,
3733 htlc_minimum_msat: 0,
3734 htlc_maximum_msat: MAX_VALUE_MSAT,
3736 fee_proportional_millionths: 0,
3737 excess_data: Vec::new()
3740 // If all the channels require some features we don't understand, route should fail
3741 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3742 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3743 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3744 &Default::default(), &random_seed_bytes) {
3745 assert_eq!(err, "Failed to find a path to the given destination");
3746 } else { panic!(); }
3748 // If we specify a channel to node7, that overrides our local channel view and that gets used
3749 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3750 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3751 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3752 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3753 &Default::default(), &random_seed_bytes).unwrap();
3754 assert_eq!(route.paths[0].hops.len(), 2);
3756 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3757 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3758 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3759 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3760 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3761 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3763 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3764 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3765 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3766 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3767 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3768 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3772 fn disable_node_test() {
3773 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3774 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3775 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3776 let scorer = ln_test_utils::TestScorer::new();
3777 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3778 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3780 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3781 let mut unknown_features = NodeFeatures::empty();
3782 unknown_features.set_unknown_feature_required();
3783 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3784 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3785 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3787 // If all nodes require some features we don't understand, route should fail
3788 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3789 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3790 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3791 &Default::default(), &random_seed_bytes) {
3792 assert_eq!(err, "Failed to find a path to the given destination");
3793 } else { panic!(); }
3795 // If we specify a channel to node7, that overrides our local channel view and that gets used
3796 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3797 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3798 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3799 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3800 &Default::default(), &random_seed_bytes).unwrap();
3801 assert_eq!(route.paths[0].hops.len(), 2);
3803 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3804 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3805 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3806 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3807 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3808 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3810 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3811 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3812 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3813 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3814 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3815 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3817 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3818 // naively) assume that the user checked the feature bits on the invoice, which override
3819 // the node_announcement.
3823 fn our_chans_test() {
3824 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3825 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3826 let scorer = ln_test_utils::TestScorer::new();
3827 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3828 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3830 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3831 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3832 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3833 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3834 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3835 assert_eq!(route.paths[0].hops.len(), 3);
3837 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3838 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3839 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3840 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3841 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3842 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3844 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3845 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3846 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3847 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3848 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3849 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3851 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3852 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3853 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3854 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3855 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3856 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3858 // If we specify a channel to node7, that overrides our local channel view and that gets used
3859 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3860 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3861 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3862 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3863 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3864 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3865 &Default::default(), &random_seed_bytes).unwrap();
3866 assert_eq!(route.paths[0].hops.len(), 2);
3868 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3869 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3870 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3871 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3872 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3873 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3875 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3876 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3877 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3878 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3879 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3880 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3883 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3884 let zero_fees = RoutingFees {
3886 proportional_millionths: 0,
3888 vec![RouteHint(vec![RouteHintHop {
3889 src_node_id: nodes[3],
3890 short_channel_id: 8,
3892 cltv_expiry_delta: (8 << 4) | 1,
3893 htlc_minimum_msat: None,
3894 htlc_maximum_msat: None,
3896 ]), RouteHint(vec![RouteHintHop {
3897 src_node_id: nodes[4],
3898 short_channel_id: 9,
3901 proportional_millionths: 0,
3903 cltv_expiry_delta: (9 << 4) | 1,
3904 htlc_minimum_msat: None,
3905 htlc_maximum_msat: None,
3906 }]), RouteHint(vec![RouteHintHop {
3907 src_node_id: nodes[5],
3908 short_channel_id: 10,
3910 cltv_expiry_delta: (10 << 4) | 1,
3911 htlc_minimum_msat: None,
3912 htlc_maximum_msat: None,
3916 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3917 let zero_fees = RoutingFees {
3919 proportional_millionths: 0,
3921 vec![RouteHint(vec![RouteHintHop {
3922 src_node_id: nodes[2],
3923 short_channel_id: 5,
3926 proportional_millionths: 0,
3928 cltv_expiry_delta: (5 << 4) | 1,
3929 htlc_minimum_msat: None,
3930 htlc_maximum_msat: None,
3932 src_node_id: nodes[3],
3933 short_channel_id: 8,
3935 cltv_expiry_delta: (8 << 4) | 1,
3936 htlc_minimum_msat: None,
3937 htlc_maximum_msat: None,
3939 ]), RouteHint(vec![RouteHintHop {
3940 src_node_id: nodes[4],
3941 short_channel_id: 9,
3944 proportional_millionths: 0,
3946 cltv_expiry_delta: (9 << 4) | 1,
3947 htlc_minimum_msat: None,
3948 htlc_maximum_msat: None,
3949 }]), RouteHint(vec![RouteHintHop {
3950 src_node_id: nodes[5],
3951 short_channel_id: 10,
3953 cltv_expiry_delta: (10 << 4) | 1,
3954 htlc_minimum_msat: None,
3955 htlc_maximum_msat: None,
3960 fn partial_route_hint_test() {
3961 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3962 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3963 let scorer = ln_test_utils::TestScorer::new();
3964 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3965 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3967 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3968 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3969 // RouteHint may be partially used by the algo to build the best path.
3971 // First check that last hop can't have its source as the payee.
3972 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3973 src_node_id: nodes[6],
3974 short_channel_id: 8,
3977 proportional_millionths: 0,
3979 cltv_expiry_delta: (8 << 4) | 1,
3980 htlc_minimum_msat: None,
3981 htlc_maximum_msat: None,
3984 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3985 invalid_last_hops.push(invalid_last_hop);
3987 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3988 .with_route_hints(invalid_last_hops).unwrap();
3989 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3990 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3991 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3992 &Default::default(), &random_seed_bytes) {
3993 assert_eq!(err, "Route hint cannot have the payee as the source.");
3994 } else { panic!(); }
3997 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3998 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3999 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4000 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4001 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4002 assert_eq!(route.paths[0].hops.len(), 5);
4004 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4005 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4006 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4007 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4008 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4009 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4011 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4012 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4013 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4014 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4015 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4016 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4018 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4019 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4020 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4021 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4022 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4023 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4025 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4026 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4027 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4028 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4029 // If we have a peer in the node map, we'll use their features here since we don't have
4030 // a way of figuring out their features from the invoice:
4031 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4032 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4034 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4035 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4036 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4037 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4038 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4039 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4042 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4043 let zero_fees = RoutingFees {
4045 proportional_millionths: 0,
4047 vec![RouteHint(vec![RouteHintHop {
4048 src_node_id: nodes[3],
4049 short_channel_id: 8,
4051 cltv_expiry_delta: (8 << 4) | 1,
4052 htlc_minimum_msat: None,
4053 htlc_maximum_msat: None,
4054 }]), RouteHint(vec![
4056 ]), RouteHint(vec![RouteHintHop {
4057 src_node_id: nodes[5],
4058 short_channel_id: 10,
4060 cltv_expiry_delta: (10 << 4) | 1,
4061 htlc_minimum_msat: None,
4062 htlc_maximum_msat: None,
4067 fn ignores_empty_last_hops_test() {
4068 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4069 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4070 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
4071 let scorer = ln_test_utils::TestScorer::new();
4072 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4073 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4075 // Test handling of an empty RouteHint passed in Invoice.
4076 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4077 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4078 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4079 assert_eq!(route.paths[0].hops.len(), 5);
4081 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4082 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4083 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4084 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4085 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4086 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4088 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4089 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4090 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4091 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4092 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4093 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4095 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4096 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4097 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4098 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4099 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4100 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4102 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4103 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4104 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4105 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4106 // If we have a peer in the node map, we'll use their features here since we don't have
4107 // a way of figuring out their features from the invoice:
4108 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4109 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4111 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4112 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4113 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4114 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4115 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4116 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4119 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
4121 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
4122 let zero_fees = RoutingFees {
4124 proportional_millionths: 0,
4126 vec![RouteHint(vec![RouteHintHop {
4127 src_node_id: hint_hops[0],
4128 short_channel_id: 0xff00,
4131 proportional_millionths: 0,
4133 cltv_expiry_delta: (5 << 4) | 1,
4134 htlc_minimum_msat: None,
4135 htlc_maximum_msat: None,
4137 src_node_id: hint_hops[1],
4138 short_channel_id: 0xff01,
4140 cltv_expiry_delta: (8 << 4) | 1,
4141 htlc_minimum_msat: None,
4142 htlc_maximum_msat: None,
4147 fn multi_hint_last_hops_test() {
4148 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4149 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4150 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
4151 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4152 let scorer = ln_test_utils::TestScorer::new();
4153 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4154 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4155 // Test through channels 2, 3, 0xff00, 0xff01.
4156 // Test shows that multiple hop hints are considered.
4158 // Disabling channels 6 & 7 by flags=2
4159 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4160 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4161 short_channel_id: 6,
4163 flags: 2, // to disable
4164 cltv_expiry_delta: 0,
4165 htlc_minimum_msat: 0,
4166 htlc_maximum_msat: MAX_VALUE_MSAT,
4168 fee_proportional_millionths: 0,
4169 excess_data: Vec::new()
4171 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4172 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4173 short_channel_id: 7,
4175 flags: 2, // to disable
4176 cltv_expiry_delta: 0,
4177 htlc_minimum_msat: 0,
4178 htlc_maximum_msat: MAX_VALUE_MSAT,
4180 fee_proportional_millionths: 0,
4181 excess_data: Vec::new()
4184 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4185 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4186 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4187 assert_eq!(route.paths[0].hops.len(), 4);
4189 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4190 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4191 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4192 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4193 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4194 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4196 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4197 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4198 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4199 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4200 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4201 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4203 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4204 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4205 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4206 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4207 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4208 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4210 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4211 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4212 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4213 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4214 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4215 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4219 fn private_multi_hint_last_hops_test() {
4220 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4221 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4223 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4224 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4226 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4227 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4228 let scorer = ln_test_utils::TestScorer::new();
4229 // Test through channels 2, 3, 0xff00, 0xff01.
4230 // Test shows that multiple hop hints are considered.
4232 // Disabling channels 6 & 7 by flags=2
4233 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4234 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4235 short_channel_id: 6,
4237 flags: 2, // to disable
4238 cltv_expiry_delta: 0,
4239 htlc_minimum_msat: 0,
4240 htlc_maximum_msat: MAX_VALUE_MSAT,
4242 fee_proportional_millionths: 0,
4243 excess_data: Vec::new()
4245 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4246 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4247 short_channel_id: 7,
4249 flags: 2, // to disable
4250 cltv_expiry_delta: 0,
4251 htlc_minimum_msat: 0,
4252 htlc_maximum_msat: MAX_VALUE_MSAT,
4254 fee_proportional_millionths: 0,
4255 excess_data: Vec::new()
4258 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4259 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4260 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4261 assert_eq!(route.paths[0].hops.len(), 4);
4263 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4264 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4265 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4266 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4267 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4268 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4270 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4271 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4272 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4273 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4274 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4275 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4277 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4278 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4279 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4280 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4281 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4282 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4284 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4285 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4286 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4287 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4288 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4289 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4292 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4293 let zero_fees = RoutingFees {
4295 proportional_millionths: 0,
4297 vec![RouteHint(vec![RouteHintHop {
4298 src_node_id: nodes[4],
4299 short_channel_id: 11,
4301 cltv_expiry_delta: (11 << 4) | 1,
4302 htlc_minimum_msat: None,
4303 htlc_maximum_msat: None,
4305 src_node_id: nodes[3],
4306 short_channel_id: 8,
4308 cltv_expiry_delta: (8 << 4) | 1,
4309 htlc_minimum_msat: None,
4310 htlc_maximum_msat: None,
4311 }]), RouteHint(vec![RouteHintHop {
4312 src_node_id: nodes[4],
4313 short_channel_id: 9,
4316 proportional_millionths: 0,
4318 cltv_expiry_delta: (9 << 4) | 1,
4319 htlc_minimum_msat: None,
4320 htlc_maximum_msat: None,
4321 }]), RouteHint(vec![RouteHintHop {
4322 src_node_id: nodes[5],
4323 short_channel_id: 10,
4325 cltv_expiry_delta: (10 << 4) | 1,
4326 htlc_minimum_msat: None,
4327 htlc_maximum_msat: None,
4332 fn last_hops_with_public_channel_test() {
4333 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4334 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4335 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4336 let scorer = ln_test_utils::TestScorer::new();
4337 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4338 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4339 // This test shows that public routes can be present in the invoice
4340 // which would be handled in the same manner.
4342 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4343 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4344 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4345 assert_eq!(route.paths[0].hops.len(), 5);
4347 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4348 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4349 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4350 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4351 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4352 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4354 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4355 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4356 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4357 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4358 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4359 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4361 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4362 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4363 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4364 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4365 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4366 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4368 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4369 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4370 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4371 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4372 // If we have a peer in the node map, we'll use their features here since we don't have
4373 // a way of figuring out their features from the invoice:
4374 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4375 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4377 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4378 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4379 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4380 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4381 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4382 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4386 fn our_chans_last_hop_connect_test() {
4387 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4388 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4389 let scorer = ln_test_utils::TestScorer::new();
4390 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4391 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4393 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4394 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4395 let mut last_hops = last_hops(&nodes);
4396 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4397 .with_route_hints(last_hops.clone()).unwrap();
4398 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4399 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4400 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4401 &Default::default(), &random_seed_bytes).unwrap();
4402 assert_eq!(route.paths[0].hops.len(), 2);
4404 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4405 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4406 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4407 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4408 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4409 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4411 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4412 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4413 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4414 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4415 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4416 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4418 last_hops[0].0[0].fees.base_msat = 1000;
4420 // Revert to via 6 as the fee on 8 goes up
4421 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4422 .with_route_hints(last_hops).unwrap();
4423 let route_params = RouteParameters::from_payment_params_and_value(
4424 payment_params.clone(), 100);
4425 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4426 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4427 assert_eq!(route.paths[0].hops.len(), 4);
4429 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4430 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4431 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4432 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4433 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4434 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4436 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4437 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4438 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4439 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4440 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4441 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4443 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4444 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4445 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4446 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4447 // If we have a peer in the node map, we'll use their features here since we don't have
4448 // a way of figuring out their features from the invoice:
4449 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4450 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4452 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4453 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4454 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4455 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4456 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4457 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4459 // ...but still use 8 for larger payments as 6 has a variable feerate
4460 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4461 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4462 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4463 assert_eq!(route.paths[0].hops.len(), 5);
4465 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4466 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4467 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4468 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4469 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4470 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4472 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4473 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4474 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4475 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4476 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4477 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4479 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4480 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4481 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4482 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4483 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4484 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4486 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4487 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4488 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4489 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4490 // If we have a peer in the node map, we'll use their features here since we don't have
4491 // a way of figuring out their features from the invoice:
4492 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4493 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4495 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4496 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4497 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4498 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4499 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4500 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4503 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> {
4504 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4505 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4506 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4508 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4509 let last_hops = RouteHint(vec![RouteHintHop {
4510 src_node_id: middle_node_id,
4511 short_channel_id: 8,
4514 proportional_millionths: last_hop_fee_prop,
4516 cltv_expiry_delta: (8 << 4) | 1,
4517 htlc_minimum_msat: None,
4518 htlc_maximum_msat: last_hop_htlc_max,
4520 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4521 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4522 let scorer = ln_test_utils::TestScorer::new();
4523 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4524 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4525 let logger = ln_test_utils::TestLogger::new();
4526 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4527 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4528 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4529 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4530 &random_seed_bytes);
4535 fn unannounced_path_test() {
4536 // We should be able to send a payment to a destination without any help of a routing graph
4537 // if we have a channel with a common counterparty that appears in the first and last hop
4539 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4541 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4542 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4543 assert_eq!(route.paths[0].hops.len(), 2);
4545 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4546 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4547 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4548 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4549 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4550 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4552 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4553 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4554 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4555 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4556 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4557 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4561 fn overflow_unannounced_path_test_liquidity_underflow() {
4562 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4563 // the last-hop had a fee which overflowed a u64, we'd panic.
4564 // This was due to us adding the first-hop from us unconditionally, causing us to think
4565 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4566 // In this test, we previously hit a subtraction underflow due to having less available
4567 // liquidity at the last hop than 0.
4568 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());
4572 fn overflow_unannounced_path_test_feerate_overflow() {
4573 // This tests for the same case as above, except instead of hitting a subtraction
4574 // underflow, we hit a case where the fee charged at a hop overflowed.
4575 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());
4579 fn available_amount_while_routing_test() {
4580 // Tests whether we choose the correct available channel amount while routing.
4582 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4583 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4584 let scorer = ln_test_utils::TestScorer::new();
4585 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4586 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4587 let config = UserConfig::default();
4588 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4589 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4592 // We will use a simple single-path route from
4593 // our node to node2 via node0: channels {1, 3}.
4595 // First disable all other paths.
4596 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4597 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4598 short_channel_id: 2,
4601 cltv_expiry_delta: 0,
4602 htlc_minimum_msat: 0,
4603 htlc_maximum_msat: 100_000,
4605 fee_proportional_millionths: 0,
4606 excess_data: Vec::new()
4608 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4609 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4610 short_channel_id: 12,
4613 cltv_expiry_delta: 0,
4614 htlc_minimum_msat: 0,
4615 htlc_maximum_msat: 100_000,
4617 fee_proportional_millionths: 0,
4618 excess_data: Vec::new()
4621 // Make the first channel (#1) very permissive,
4622 // and we will be testing all limits on the second channel.
4623 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4624 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4625 short_channel_id: 1,
4628 cltv_expiry_delta: 0,
4629 htlc_minimum_msat: 0,
4630 htlc_maximum_msat: 1_000_000_000,
4632 fee_proportional_millionths: 0,
4633 excess_data: Vec::new()
4636 // First, let's see if routing works if we have absolutely no idea about the available amount.
4637 // In this case, it should be set to 250_000 sats.
4638 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4639 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4640 short_channel_id: 3,
4643 cltv_expiry_delta: 0,
4644 htlc_minimum_msat: 0,
4645 htlc_maximum_msat: 250_000_000,
4647 fee_proportional_millionths: 0,
4648 excess_data: Vec::new()
4652 // Attempt to route more than available results in a failure.
4653 let route_params = RouteParameters::from_payment_params_and_value(
4654 payment_params.clone(), 250_000_001);
4655 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4656 &our_id, &route_params, &network_graph.read_only(), None,
4657 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4658 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4659 } else { panic!(); }
4663 // Now, attempt to route an exact amount we have should be fine.
4664 let route_params = RouteParameters::from_payment_params_and_value(
4665 payment_params.clone(), 250_000_000);
4666 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4667 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4668 assert_eq!(route.paths.len(), 1);
4669 let path = route.paths.last().unwrap();
4670 assert_eq!(path.hops.len(), 2);
4671 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4672 assert_eq!(path.final_value_msat(), 250_000_000);
4675 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4676 // Disable channel #1 and use another first hop.
4677 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4678 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4679 short_channel_id: 1,
4682 cltv_expiry_delta: 0,
4683 htlc_minimum_msat: 0,
4684 htlc_maximum_msat: 1_000_000_000,
4686 fee_proportional_millionths: 0,
4687 excess_data: Vec::new()
4690 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4691 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4694 // Attempt to route more than available results in a failure.
4695 let route_params = RouteParameters::from_payment_params_and_value(
4696 payment_params.clone(), 200_000_001);
4697 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4698 &our_id, &route_params, &network_graph.read_only(),
4699 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4700 &Default::default(), &random_seed_bytes) {
4701 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4702 } else { panic!(); }
4706 // Now, attempt to route an exact amount we have should be fine.
4707 let route_params = RouteParameters::from_payment_params_and_value(
4708 payment_params.clone(), 200_000_000);
4709 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4710 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4711 &Default::default(), &random_seed_bytes).unwrap();
4712 assert_eq!(route.paths.len(), 1);
4713 let path = route.paths.last().unwrap();
4714 assert_eq!(path.hops.len(), 2);
4715 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4716 assert_eq!(path.final_value_msat(), 200_000_000);
4719 // Enable channel #1 back.
4720 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4721 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4722 short_channel_id: 1,
4725 cltv_expiry_delta: 0,
4726 htlc_minimum_msat: 0,
4727 htlc_maximum_msat: 1_000_000_000,
4729 fee_proportional_millionths: 0,
4730 excess_data: Vec::new()
4734 // Now let's see if routing works if we know only htlc_maximum_msat.
4735 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4736 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4737 short_channel_id: 3,
4740 cltv_expiry_delta: 0,
4741 htlc_minimum_msat: 0,
4742 htlc_maximum_msat: 15_000,
4744 fee_proportional_millionths: 0,
4745 excess_data: Vec::new()
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(), 15_001);
4752 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4753 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4754 &scorer, &Default::default(), &random_seed_bytes) {
4755 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4756 } else { panic!(); }
4760 // Now, attempt to route an exact amount we have should be fine.
4761 let route_params = RouteParameters::from_payment_params_and_value(
4762 payment_params.clone(), 15_000);
4763 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4764 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4765 assert_eq!(route.paths.len(), 1);
4766 let path = route.paths.last().unwrap();
4767 assert_eq!(path.hops.len(), 2);
4768 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4769 assert_eq!(path.final_value_msat(), 15_000);
4772 // Now let's see if routing works if we know only capacity from the UTXO.
4774 // We can't change UTXO capacity on the fly, so we'll disable
4775 // the existing channel and add another one with the capacity we need.
4776 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4777 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4778 short_channel_id: 3,
4781 cltv_expiry_delta: 0,
4782 htlc_minimum_msat: 0,
4783 htlc_maximum_msat: MAX_VALUE_MSAT,
4785 fee_proportional_millionths: 0,
4786 excess_data: Vec::new()
4789 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4790 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4791 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4792 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4793 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4795 *chain_monitor.utxo_ret.lock().unwrap() =
4796 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4797 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4799 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4800 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4801 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4802 short_channel_id: 333,
4805 cltv_expiry_delta: (3 << 4) | 1,
4806 htlc_minimum_msat: 0,
4807 htlc_maximum_msat: 15_000,
4809 fee_proportional_millionths: 0,
4810 excess_data: Vec::new()
4812 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4813 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4814 short_channel_id: 333,
4817 cltv_expiry_delta: (3 << 4) | 2,
4818 htlc_minimum_msat: 0,
4819 htlc_maximum_msat: 15_000,
4821 fee_proportional_millionths: 0,
4822 excess_data: Vec::new()
4826 // Attempt to route more than available results in a failure.
4827 let route_params = RouteParameters::from_payment_params_and_value(
4828 payment_params.clone(), 15_001);
4829 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4830 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4831 &scorer, &Default::default(), &random_seed_bytes) {
4832 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4833 } else { panic!(); }
4837 // Now, attempt to route an exact amount we have should be fine.
4838 let route_params = RouteParameters::from_payment_params_and_value(
4839 payment_params.clone(), 15_000);
4840 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4841 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4842 assert_eq!(route.paths.len(), 1);
4843 let path = route.paths.last().unwrap();
4844 assert_eq!(path.hops.len(), 2);
4845 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4846 assert_eq!(path.final_value_msat(), 15_000);
4849 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4850 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4851 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4852 short_channel_id: 333,
4855 cltv_expiry_delta: 0,
4856 htlc_minimum_msat: 0,
4857 htlc_maximum_msat: 10_000,
4859 fee_proportional_millionths: 0,
4860 excess_data: Vec::new()
4864 // Attempt to route more than available results in a failure.
4865 let route_params = RouteParameters::from_payment_params_and_value(
4866 payment_params.clone(), 10_001);
4867 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4868 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4869 &scorer, &Default::default(), &random_seed_bytes) {
4870 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4871 } else { panic!(); }
4875 // Now, attempt to route an exact amount we have should be fine.
4876 let route_params = RouteParameters::from_payment_params_and_value(
4877 payment_params.clone(), 10_000);
4878 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4879 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4880 assert_eq!(route.paths.len(), 1);
4881 let path = route.paths.last().unwrap();
4882 assert_eq!(path.hops.len(), 2);
4883 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4884 assert_eq!(path.final_value_msat(), 10_000);
4889 fn available_liquidity_last_hop_test() {
4890 // Check that available liquidity properly limits the path even when only
4891 // one of the latter hops is limited.
4892 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4893 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4894 let scorer = ln_test_utils::TestScorer::new();
4895 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4896 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4897 let config = UserConfig::default();
4898 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4899 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4902 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4903 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4904 // Total capacity: 50 sats.
4906 // Disable other potential paths.
4907 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4908 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4909 short_channel_id: 2,
4912 cltv_expiry_delta: 0,
4913 htlc_minimum_msat: 0,
4914 htlc_maximum_msat: 100_000,
4916 fee_proportional_millionths: 0,
4917 excess_data: Vec::new()
4919 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4920 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4921 short_channel_id: 7,
4924 cltv_expiry_delta: 0,
4925 htlc_minimum_msat: 0,
4926 htlc_maximum_msat: 100_000,
4928 fee_proportional_millionths: 0,
4929 excess_data: Vec::new()
4934 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4935 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4936 short_channel_id: 12,
4939 cltv_expiry_delta: 0,
4940 htlc_minimum_msat: 0,
4941 htlc_maximum_msat: 100_000,
4943 fee_proportional_millionths: 0,
4944 excess_data: Vec::new()
4946 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4947 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4948 short_channel_id: 13,
4951 cltv_expiry_delta: 0,
4952 htlc_minimum_msat: 0,
4953 htlc_maximum_msat: 100_000,
4955 fee_proportional_millionths: 0,
4956 excess_data: Vec::new()
4959 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4960 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4961 short_channel_id: 6,
4964 cltv_expiry_delta: 0,
4965 htlc_minimum_msat: 0,
4966 htlc_maximum_msat: 50_000,
4968 fee_proportional_millionths: 0,
4969 excess_data: Vec::new()
4971 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4972 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4973 short_channel_id: 11,
4976 cltv_expiry_delta: 0,
4977 htlc_minimum_msat: 0,
4978 htlc_maximum_msat: 100_000,
4980 fee_proportional_millionths: 0,
4981 excess_data: Vec::new()
4984 // Attempt to route more than available results in a failure.
4985 let route_params = RouteParameters::from_payment_params_and_value(
4986 payment_params.clone(), 60_000);
4987 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4988 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4989 &scorer, &Default::default(), &random_seed_bytes) {
4990 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4991 } else { panic!(); }
4995 // Now, attempt to route 49 sats (just a bit below the capacity).
4996 let route_params = RouteParameters::from_payment_params_and_value(
4997 payment_params.clone(), 49_000);
4998 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4999 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5000 assert_eq!(route.paths.len(), 1);
5001 let mut total_amount_paid_msat = 0;
5002 for path in &route.paths {
5003 assert_eq!(path.hops.len(), 4);
5004 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5005 total_amount_paid_msat += path.final_value_msat();
5007 assert_eq!(total_amount_paid_msat, 49_000);
5011 // Attempt to route an exact amount is also fine
5012 let route_params = RouteParameters::from_payment_params_and_value(
5013 payment_params, 50_000);
5014 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5015 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5016 assert_eq!(route.paths.len(), 1);
5017 let mut total_amount_paid_msat = 0;
5018 for path in &route.paths {
5019 assert_eq!(path.hops.len(), 4);
5020 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5021 total_amount_paid_msat += path.final_value_msat();
5023 assert_eq!(total_amount_paid_msat, 50_000);
5028 fn ignore_fee_first_hop_test() {
5029 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5030 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5031 let scorer = ln_test_utils::TestScorer::new();
5032 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5033 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5034 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5036 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5037 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5038 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5039 short_channel_id: 1,
5042 cltv_expiry_delta: 0,
5043 htlc_minimum_msat: 0,
5044 htlc_maximum_msat: 100_000,
5045 fee_base_msat: 1_000_000,
5046 fee_proportional_millionths: 0,
5047 excess_data: Vec::new()
5049 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5050 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5051 short_channel_id: 3,
5054 cltv_expiry_delta: 0,
5055 htlc_minimum_msat: 0,
5056 htlc_maximum_msat: 50_000,
5058 fee_proportional_millionths: 0,
5059 excess_data: Vec::new()
5063 let route_params = RouteParameters::from_payment_params_and_value(
5064 payment_params, 50_000);
5065 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5066 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5067 assert_eq!(route.paths.len(), 1);
5068 let mut total_amount_paid_msat = 0;
5069 for path in &route.paths {
5070 assert_eq!(path.hops.len(), 2);
5071 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5072 total_amount_paid_msat += path.final_value_msat();
5074 assert_eq!(total_amount_paid_msat, 50_000);
5079 fn simple_mpp_route_test() {
5080 let (secp_ctx, _, _, _, _) = build_graph();
5081 let (_, _, _, nodes) = get_nodes(&secp_ctx);
5082 let config = UserConfig::default();
5083 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5084 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5086 do_simple_mpp_route_test(clear_payment_params);
5088 // MPP to a 1-hop blinded path for nodes[2]
5089 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
5090 let blinded_path = BlindedPath {
5091 introduction_node_id: nodes[2],
5092 blinding_point: ln_test_utils::pubkey(42),
5093 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
5095 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
5097 fee_proportional_millionths: 0,
5098 htlc_minimum_msat: 0,
5099 htlc_maximum_msat: 0,
5100 cltv_expiry_delta: 0,
5101 features: BlindedHopFeatures::empty(),
5103 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
5104 .with_bolt12_features(bolt12_features.clone()).unwrap();
5105 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
5107 // MPP to 3 2-hop blinded paths
5108 let mut blinded_path_node_0 = blinded_path.clone();
5109 blinded_path_node_0.introduction_node_id = nodes[0];
5110 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
5111 let mut node_0_payinfo = blinded_payinfo.clone();
5112 node_0_payinfo.htlc_maximum_msat = 50_000;
5114 let mut blinded_path_node_7 = blinded_path_node_0.clone();
5115 blinded_path_node_7.introduction_node_id = nodes[7];
5116 let mut node_7_payinfo = blinded_payinfo.clone();
5117 node_7_payinfo.htlc_maximum_msat = 60_000;
5119 let mut blinded_path_node_1 = blinded_path_node_0.clone();
5120 blinded_path_node_1.introduction_node_id = nodes[1];
5121 let mut node_1_payinfo = blinded_payinfo.clone();
5122 node_1_payinfo.htlc_maximum_msat = 180_000;
5124 let two_hop_blinded_payment_params = PaymentParameters::blinded(
5126 (node_0_payinfo, blinded_path_node_0),
5127 (node_7_payinfo, blinded_path_node_7),
5128 (node_1_payinfo, blinded_path_node_1)
5130 .with_bolt12_features(bolt12_features).unwrap();
5131 do_simple_mpp_route_test(two_hop_blinded_payment_params);
5135 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
5136 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5137 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5138 let scorer = ln_test_utils::TestScorer::new();
5139 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5140 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5142 // We need a route consisting of 3 paths:
5143 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5144 // To achieve this, the amount being transferred should be around
5145 // the total capacity of these 3 paths.
5147 // First, we set limits on these (previously unlimited) channels.
5148 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
5150 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5151 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5152 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5153 short_channel_id: 1,
5156 cltv_expiry_delta: 0,
5157 htlc_minimum_msat: 0,
5158 htlc_maximum_msat: 100_000,
5160 fee_proportional_millionths: 0,
5161 excess_data: Vec::new()
5163 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5164 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5165 short_channel_id: 3,
5168 cltv_expiry_delta: 0,
5169 htlc_minimum_msat: 0,
5170 htlc_maximum_msat: 50_000,
5172 fee_proportional_millionths: 0,
5173 excess_data: Vec::new()
5176 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
5177 // (total limit 60).
5178 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5179 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5180 short_channel_id: 12,
5183 cltv_expiry_delta: 0,
5184 htlc_minimum_msat: 0,
5185 htlc_maximum_msat: 60_000,
5187 fee_proportional_millionths: 0,
5188 excess_data: Vec::new()
5190 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5191 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5192 short_channel_id: 13,
5195 cltv_expiry_delta: 0,
5196 htlc_minimum_msat: 0,
5197 htlc_maximum_msat: 60_000,
5199 fee_proportional_millionths: 0,
5200 excess_data: Vec::new()
5203 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5204 // (total capacity 180 sats).
5205 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5206 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5207 short_channel_id: 2,
5210 cltv_expiry_delta: 0,
5211 htlc_minimum_msat: 0,
5212 htlc_maximum_msat: 200_000,
5214 fee_proportional_millionths: 0,
5215 excess_data: Vec::new()
5217 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5218 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5219 short_channel_id: 4,
5222 cltv_expiry_delta: 0,
5223 htlc_minimum_msat: 0,
5224 htlc_maximum_msat: 180_000,
5226 fee_proportional_millionths: 0,
5227 excess_data: Vec::new()
5231 // Attempt to route more than available results in a failure.
5232 let route_params = RouteParameters::from_payment_params_and_value(
5233 payment_params.clone(), 300_000);
5234 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5235 &our_id, &route_params, &network_graph.read_only(), None,
5236 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5237 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5238 } else { panic!(); }
5242 // Attempt to route while setting max_path_count to 0 results in a failure.
5243 let zero_payment_params = payment_params.clone().with_max_path_count(0);
5244 let route_params = RouteParameters::from_payment_params_and_value(
5245 zero_payment_params, 100);
5246 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5247 &our_id, &route_params, &network_graph.read_only(), None,
5248 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5249 assert_eq!(err, "Can't find a route with no paths allowed.");
5250 } else { panic!(); }
5254 // Attempt to route while setting max_path_count to 3 results in a failure.
5255 // This is the case because the minimal_value_contribution_msat would require each path
5256 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5257 let fail_payment_params = payment_params.clone().with_max_path_count(3);
5258 let route_params = RouteParameters::from_payment_params_and_value(
5259 fail_payment_params, 250_000);
5260 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5261 &our_id, &route_params, &network_graph.read_only(), None,
5262 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5263 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5264 } else { panic!(); }
5268 // Now, attempt to route 250 sats (just a bit below the capacity).
5269 // Our algorithm should provide us with these 3 paths.
5270 let route_params = RouteParameters::from_payment_params_and_value(
5271 payment_params.clone(), 250_000);
5272 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5273 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5274 assert_eq!(route.paths.len(), 3);
5275 let mut total_amount_paid_msat = 0;
5276 for path in &route.paths {
5277 if let Some(bt) = &path.blinded_tail {
5278 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5280 assert_eq!(path.hops.len(), 2);
5281 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5283 total_amount_paid_msat += path.final_value_msat();
5285 assert_eq!(total_amount_paid_msat, 250_000);
5289 // Attempt to route an exact amount is also fine
5290 let route_params = RouteParameters::from_payment_params_and_value(
5291 payment_params.clone(), 290_000);
5292 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5293 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5294 assert_eq!(route.paths.len(), 3);
5295 let mut total_amount_paid_msat = 0;
5296 for path in &route.paths {
5297 if payment_params.payee.blinded_route_hints().len() != 0 {
5298 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5299 if let Some(bt) = &path.blinded_tail {
5300 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5301 if bt.hops.len() > 1 {
5302 assert_eq!(path.hops.last().unwrap().pubkey,
5303 payment_params.payee.blinded_route_hints().iter()
5304 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5305 .map(|(_, p)| p.introduction_node_id).unwrap());
5307 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5310 assert_eq!(path.hops.len(), 2);
5311 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5313 total_amount_paid_msat += path.final_value_msat();
5315 assert_eq!(total_amount_paid_msat, 290_000);
5320 fn long_mpp_route_test() {
5321 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5322 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5323 let scorer = ln_test_utils::TestScorer::new();
5324 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5325 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5326 let config = UserConfig::default();
5327 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5328 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5331 // We need a route consisting of 3 paths:
5332 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5333 // Note that these paths overlap (channels 5, 12, 13).
5334 // We will route 300 sats.
5335 // Each path will have 100 sats capacity, those channels which
5336 // are used twice will have 200 sats capacity.
5338 // Disable other potential paths.
5339 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5340 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5341 short_channel_id: 2,
5344 cltv_expiry_delta: 0,
5345 htlc_minimum_msat: 0,
5346 htlc_maximum_msat: 100_000,
5348 fee_proportional_millionths: 0,
5349 excess_data: Vec::new()
5351 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5352 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5353 short_channel_id: 7,
5356 cltv_expiry_delta: 0,
5357 htlc_minimum_msat: 0,
5358 htlc_maximum_msat: 100_000,
5360 fee_proportional_millionths: 0,
5361 excess_data: Vec::new()
5364 // Path via {node0, node2} is channels {1, 3, 5}.
5365 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5366 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5367 short_channel_id: 1,
5370 cltv_expiry_delta: 0,
5371 htlc_minimum_msat: 0,
5372 htlc_maximum_msat: 100_000,
5374 fee_proportional_millionths: 0,
5375 excess_data: Vec::new()
5377 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5378 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5379 short_channel_id: 3,
5382 cltv_expiry_delta: 0,
5383 htlc_minimum_msat: 0,
5384 htlc_maximum_msat: 100_000,
5386 fee_proportional_millionths: 0,
5387 excess_data: Vec::new()
5390 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5391 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5392 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5393 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5394 short_channel_id: 5,
5397 cltv_expiry_delta: 0,
5398 htlc_minimum_msat: 0,
5399 htlc_maximum_msat: 200_000,
5401 fee_proportional_millionths: 0,
5402 excess_data: Vec::new()
5405 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5406 // Add 100 sats to the capacities of {12, 13}, because these channels
5407 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5408 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5409 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5410 short_channel_id: 12,
5413 cltv_expiry_delta: 0,
5414 htlc_minimum_msat: 0,
5415 htlc_maximum_msat: 200_000,
5417 fee_proportional_millionths: 0,
5418 excess_data: Vec::new()
5420 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5421 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5422 short_channel_id: 13,
5425 cltv_expiry_delta: 0,
5426 htlc_minimum_msat: 0,
5427 htlc_maximum_msat: 200_000,
5429 fee_proportional_millionths: 0,
5430 excess_data: Vec::new()
5433 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5434 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5435 short_channel_id: 6,
5438 cltv_expiry_delta: 0,
5439 htlc_minimum_msat: 0,
5440 htlc_maximum_msat: 100_000,
5442 fee_proportional_millionths: 0,
5443 excess_data: Vec::new()
5445 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5446 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5447 short_channel_id: 11,
5450 cltv_expiry_delta: 0,
5451 htlc_minimum_msat: 0,
5452 htlc_maximum_msat: 100_000,
5454 fee_proportional_millionths: 0,
5455 excess_data: Vec::new()
5458 // Path via {node7, node2} is channels {12, 13, 5}.
5459 // We already limited them to 200 sats (they are used twice for 100 sats).
5460 // Nothing to do here.
5463 // Attempt to route more than available results in a failure.
5464 let route_params = RouteParameters::from_payment_params_and_value(
5465 payment_params.clone(), 350_000);
5466 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5467 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5468 &scorer, &Default::default(), &random_seed_bytes) {
5469 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5470 } else { panic!(); }
5474 // Now, attempt to route 300 sats (exact amount we can route).
5475 // Our algorithm should provide us with these 3 paths, 100 sats each.
5476 let route_params = RouteParameters::from_payment_params_and_value(
5477 payment_params, 300_000);
5478 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5479 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5480 assert_eq!(route.paths.len(), 3);
5482 let mut total_amount_paid_msat = 0;
5483 for path in &route.paths {
5484 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5485 total_amount_paid_msat += path.final_value_msat();
5487 assert_eq!(total_amount_paid_msat, 300_000);
5493 fn mpp_cheaper_route_test() {
5494 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5495 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5496 let scorer = ln_test_utils::TestScorer::new();
5497 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5498 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5499 let config = UserConfig::default();
5500 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5501 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5504 // This test checks that if we have two cheaper paths and one more expensive path,
5505 // so that liquidity-wise any 2 of 3 combination is sufficient,
5506 // two cheaper paths will be taken.
5507 // These paths have equal available liquidity.
5509 // We need a combination of 3 paths:
5510 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5511 // Note that these paths overlap (channels 5, 12, 13).
5512 // Each path will have 100 sats capacity, those channels which
5513 // are used twice will have 200 sats capacity.
5515 // Disable other potential paths.
5516 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5517 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5518 short_channel_id: 2,
5521 cltv_expiry_delta: 0,
5522 htlc_minimum_msat: 0,
5523 htlc_maximum_msat: 100_000,
5525 fee_proportional_millionths: 0,
5526 excess_data: Vec::new()
5528 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5529 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5530 short_channel_id: 7,
5533 cltv_expiry_delta: 0,
5534 htlc_minimum_msat: 0,
5535 htlc_maximum_msat: 100_000,
5537 fee_proportional_millionths: 0,
5538 excess_data: Vec::new()
5541 // Path via {node0, node2} is channels {1, 3, 5}.
5542 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5543 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5544 short_channel_id: 1,
5547 cltv_expiry_delta: 0,
5548 htlc_minimum_msat: 0,
5549 htlc_maximum_msat: 100_000,
5551 fee_proportional_millionths: 0,
5552 excess_data: Vec::new()
5554 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5555 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5556 short_channel_id: 3,
5559 cltv_expiry_delta: 0,
5560 htlc_minimum_msat: 0,
5561 htlc_maximum_msat: 100_000,
5563 fee_proportional_millionths: 0,
5564 excess_data: Vec::new()
5567 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5568 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5569 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5570 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5571 short_channel_id: 5,
5574 cltv_expiry_delta: 0,
5575 htlc_minimum_msat: 0,
5576 htlc_maximum_msat: 200_000,
5578 fee_proportional_millionths: 0,
5579 excess_data: Vec::new()
5582 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5583 // Add 100 sats to the capacities of {12, 13}, because these channels
5584 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5585 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5586 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5587 short_channel_id: 12,
5590 cltv_expiry_delta: 0,
5591 htlc_minimum_msat: 0,
5592 htlc_maximum_msat: 200_000,
5594 fee_proportional_millionths: 0,
5595 excess_data: Vec::new()
5597 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5598 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5599 short_channel_id: 13,
5602 cltv_expiry_delta: 0,
5603 htlc_minimum_msat: 0,
5604 htlc_maximum_msat: 200_000,
5606 fee_proportional_millionths: 0,
5607 excess_data: Vec::new()
5610 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5611 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5612 short_channel_id: 6,
5615 cltv_expiry_delta: 0,
5616 htlc_minimum_msat: 0,
5617 htlc_maximum_msat: 100_000,
5618 fee_base_msat: 1_000,
5619 fee_proportional_millionths: 0,
5620 excess_data: Vec::new()
5622 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5623 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5624 short_channel_id: 11,
5627 cltv_expiry_delta: 0,
5628 htlc_minimum_msat: 0,
5629 htlc_maximum_msat: 100_000,
5631 fee_proportional_millionths: 0,
5632 excess_data: Vec::new()
5635 // Path via {node7, node2} is channels {12, 13, 5}.
5636 // We already limited them to 200 sats (they are used twice for 100 sats).
5637 // Nothing to do here.
5640 // Now, attempt to route 180 sats.
5641 // Our algorithm should provide us with these 2 paths.
5642 let route_params = RouteParameters::from_payment_params_and_value(
5643 payment_params, 180_000);
5644 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5645 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5646 assert_eq!(route.paths.len(), 2);
5648 let mut total_value_transferred_msat = 0;
5649 let mut total_paid_msat = 0;
5650 for path in &route.paths {
5651 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5652 total_value_transferred_msat += path.final_value_msat();
5653 for hop in &path.hops {
5654 total_paid_msat += hop.fee_msat;
5657 // If we paid fee, this would be higher.
5658 assert_eq!(total_value_transferred_msat, 180_000);
5659 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5660 assert_eq!(total_fees_paid, 0);
5665 fn fees_on_mpp_route_test() {
5666 // This test makes sure that MPP algorithm properly takes into account
5667 // fees charged on the channels, by making the fees impactful:
5668 // if the fee is not properly accounted for, the behavior is different.
5669 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5670 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5671 let scorer = ln_test_utils::TestScorer::new();
5672 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5673 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5674 let config = UserConfig::default();
5675 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5676 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5679 // We need a route consisting of 2 paths:
5680 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5681 // We will route 200 sats, Each path will have 100 sats capacity.
5683 // This test is not particularly stable: e.g.,
5684 // there's a way to route via {node0, node2, node4}.
5685 // It works while pathfinding is deterministic, but can be broken otherwise.
5686 // It's fine to ignore this concern for now.
5688 // Disable other potential paths.
5689 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5690 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5691 short_channel_id: 2,
5694 cltv_expiry_delta: 0,
5695 htlc_minimum_msat: 0,
5696 htlc_maximum_msat: 100_000,
5698 fee_proportional_millionths: 0,
5699 excess_data: Vec::new()
5702 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5703 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5704 short_channel_id: 7,
5707 cltv_expiry_delta: 0,
5708 htlc_minimum_msat: 0,
5709 htlc_maximum_msat: 100_000,
5711 fee_proportional_millionths: 0,
5712 excess_data: Vec::new()
5715 // Path via {node0, node2} is channels {1, 3, 5}.
5716 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5717 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5718 short_channel_id: 1,
5721 cltv_expiry_delta: 0,
5722 htlc_minimum_msat: 0,
5723 htlc_maximum_msat: 100_000,
5725 fee_proportional_millionths: 0,
5726 excess_data: Vec::new()
5728 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5729 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5730 short_channel_id: 3,
5733 cltv_expiry_delta: 0,
5734 htlc_minimum_msat: 0,
5735 htlc_maximum_msat: 100_000,
5737 fee_proportional_millionths: 0,
5738 excess_data: Vec::new()
5741 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5742 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5743 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5744 short_channel_id: 5,
5747 cltv_expiry_delta: 0,
5748 htlc_minimum_msat: 0,
5749 htlc_maximum_msat: 100_000,
5751 fee_proportional_millionths: 0,
5752 excess_data: Vec::new()
5755 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5756 // All channels should be 100 sats capacity. But for the fee experiment,
5757 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5758 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5759 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5760 // so no matter how large are other channels,
5761 // the whole path will be limited by 100 sats with just these 2 conditions:
5762 // - channel 12 capacity is 250 sats
5763 // - fee for channel 6 is 150 sats
5764 // Let's test this by enforcing these 2 conditions and removing other limits.
5765 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5766 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5767 short_channel_id: 12,
5770 cltv_expiry_delta: 0,
5771 htlc_minimum_msat: 0,
5772 htlc_maximum_msat: 250_000,
5774 fee_proportional_millionths: 0,
5775 excess_data: Vec::new()
5777 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5778 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5779 short_channel_id: 13,
5782 cltv_expiry_delta: 0,
5783 htlc_minimum_msat: 0,
5784 htlc_maximum_msat: MAX_VALUE_MSAT,
5786 fee_proportional_millionths: 0,
5787 excess_data: Vec::new()
5790 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5791 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5792 short_channel_id: 6,
5795 cltv_expiry_delta: 0,
5796 htlc_minimum_msat: 0,
5797 htlc_maximum_msat: MAX_VALUE_MSAT,
5798 fee_base_msat: 150_000,
5799 fee_proportional_millionths: 0,
5800 excess_data: Vec::new()
5802 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5803 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5804 short_channel_id: 11,
5807 cltv_expiry_delta: 0,
5808 htlc_minimum_msat: 0,
5809 htlc_maximum_msat: MAX_VALUE_MSAT,
5811 fee_proportional_millionths: 0,
5812 excess_data: Vec::new()
5816 // Attempt to route more than available results in a failure.
5817 let route_params = RouteParameters::from_payment_params_and_value(
5818 payment_params.clone(), 210_000);
5819 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5820 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5821 &scorer, &Default::default(), &random_seed_bytes) {
5822 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5823 } else { panic!(); }
5827 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5828 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5829 max_total_routing_fee_msat: Some(149_999) };
5830 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5831 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5832 &scorer, &Default::default(), &random_seed_bytes) {
5833 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5834 } else { panic!(); }
5838 // Now, attempt to route 200 sats (exact amount we can route).
5839 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5840 max_total_routing_fee_msat: Some(150_000) };
5841 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5842 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5843 assert_eq!(route.paths.len(), 2);
5845 let mut total_amount_paid_msat = 0;
5846 for path in &route.paths {
5847 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5848 total_amount_paid_msat += path.final_value_msat();
5850 assert_eq!(total_amount_paid_msat, 200_000);
5851 assert_eq!(route.get_total_fees(), 150_000);
5856 fn mpp_with_last_hops() {
5857 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5858 // via a single last-hop route hint, we'd fail to route if we first collected routes
5859 // totaling close but not quite enough to fund the full payment.
5861 // This was because we considered last-hop hints to have exactly the sought payment amount
5862 // instead of the amount we were trying to collect, needlessly limiting our path searching
5863 // at the very first hop.
5865 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5866 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5867 // to only have the remaining to-collect amount in available liquidity.
5869 // This bug appeared in production in some specific channel configurations.
5870 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5871 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5872 let scorer = ln_test_utils::TestScorer::new();
5873 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5874 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5875 let config = UserConfig::default();
5876 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
5877 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
5878 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5879 src_node_id: nodes[2],
5880 short_channel_id: 42,
5881 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5882 cltv_expiry_delta: 42,
5883 htlc_minimum_msat: None,
5884 htlc_maximum_msat: None,
5885 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5887 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5888 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5889 // would first use the no-fee route and then fail to find a path along the second route as
5890 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5891 // under 5% of our payment amount.
5892 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5893 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5894 short_channel_id: 1,
5897 cltv_expiry_delta: (5 << 4) | 5,
5898 htlc_minimum_msat: 0,
5899 htlc_maximum_msat: 99_000,
5900 fee_base_msat: u32::max_value(),
5901 fee_proportional_millionths: u32::max_value(),
5902 excess_data: Vec::new()
5904 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5905 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5906 short_channel_id: 2,
5909 cltv_expiry_delta: (5 << 4) | 3,
5910 htlc_minimum_msat: 0,
5911 htlc_maximum_msat: 99_000,
5912 fee_base_msat: u32::max_value(),
5913 fee_proportional_millionths: u32::max_value(),
5914 excess_data: Vec::new()
5916 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5917 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5918 short_channel_id: 4,
5921 cltv_expiry_delta: (4 << 4) | 1,
5922 htlc_minimum_msat: 0,
5923 htlc_maximum_msat: MAX_VALUE_MSAT,
5925 fee_proportional_millionths: 0,
5926 excess_data: Vec::new()
5928 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5929 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5930 short_channel_id: 13,
5932 flags: 0|2, // Channel disabled
5933 cltv_expiry_delta: (13 << 4) | 1,
5934 htlc_minimum_msat: 0,
5935 htlc_maximum_msat: MAX_VALUE_MSAT,
5937 fee_proportional_millionths: 2000000,
5938 excess_data: Vec::new()
5941 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5943 let route_params = RouteParameters::from_payment_params_and_value(
5944 payment_params, 100_000);
5945 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5946 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5947 assert_eq!(route.paths.len(), 2);
5948 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5949 // Paths are manually ordered ordered by SCID, so:
5950 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5951 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5952 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5953 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5954 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5955 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5956 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5957 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5958 assert_eq!(route.get_total_fees(), 1);
5959 assert_eq!(route.get_total_amount(), 100_000);
5963 fn drop_lowest_channel_mpp_route_test() {
5964 // This test checks that low-capacity channel is dropped when after
5965 // path finding we realize that we found more capacity than we need.
5966 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5967 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5968 let scorer = ln_test_utils::TestScorer::new();
5969 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5970 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5971 let config = UserConfig::default();
5972 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5973 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5975 .with_max_channel_saturation_power_of_half(0);
5977 // We need a route consisting of 3 paths:
5978 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5980 // The first and the second paths should be sufficient, but the third should be
5981 // cheaper, so that we select it but drop later.
5983 // First, we set limits on these (previously unlimited) channels.
5984 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5986 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5987 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5988 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5989 short_channel_id: 1,
5992 cltv_expiry_delta: 0,
5993 htlc_minimum_msat: 0,
5994 htlc_maximum_msat: 100_000,
5996 fee_proportional_millionths: 0,
5997 excess_data: Vec::new()
5999 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6000 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6001 short_channel_id: 3,
6004 cltv_expiry_delta: 0,
6005 htlc_minimum_msat: 0,
6006 htlc_maximum_msat: 50_000,
6008 fee_proportional_millionths: 0,
6009 excess_data: Vec::new()
6012 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
6013 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6014 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6015 short_channel_id: 12,
6018 cltv_expiry_delta: 0,
6019 htlc_minimum_msat: 0,
6020 htlc_maximum_msat: 60_000,
6022 fee_proportional_millionths: 0,
6023 excess_data: Vec::new()
6025 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6026 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6027 short_channel_id: 13,
6030 cltv_expiry_delta: 0,
6031 htlc_minimum_msat: 0,
6032 htlc_maximum_msat: 60_000,
6034 fee_proportional_millionths: 0,
6035 excess_data: Vec::new()
6038 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
6039 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6040 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6041 short_channel_id: 2,
6044 cltv_expiry_delta: 0,
6045 htlc_minimum_msat: 0,
6046 htlc_maximum_msat: 20_000,
6048 fee_proportional_millionths: 0,
6049 excess_data: Vec::new()
6051 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6052 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6053 short_channel_id: 4,
6056 cltv_expiry_delta: 0,
6057 htlc_minimum_msat: 0,
6058 htlc_maximum_msat: 20_000,
6060 fee_proportional_millionths: 0,
6061 excess_data: Vec::new()
6065 // Attempt to route more than available results in a failure.
6066 let route_params = RouteParameters::from_payment_params_and_value(
6067 payment_params.clone(), 150_000);
6068 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6069 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6070 &scorer, &Default::default(), &random_seed_bytes) {
6071 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6072 } else { panic!(); }
6076 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
6077 // Our algorithm should provide us with these 3 paths.
6078 let route_params = RouteParameters::from_payment_params_and_value(
6079 payment_params.clone(), 125_000);
6080 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6081 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6082 assert_eq!(route.paths.len(), 3);
6083 let mut total_amount_paid_msat = 0;
6084 for path in &route.paths {
6085 assert_eq!(path.hops.len(), 2);
6086 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6087 total_amount_paid_msat += path.final_value_msat();
6089 assert_eq!(total_amount_paid_msat, 125_000);
6093 // Attempt to route without the last small cheap channel
6094 let route_params = RouteParameters::from_payment_params_and_value(
6095 payment_params, 90_000);
6096 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6097 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6098 assert_eq!(route.paths.len(), 2);
6099 let mut total_amount_paid_msat = 0;
6100 for path in &route.paths {
6101 assert_eq!(path.hops.len(), 2);
6102 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6103 total_amount_paid_msat += path.final_value_msat();
6105 assert_eq!(total_amount_paid_msat, 90_000);
6110 fn min_criteria_consistency() {
6111 // Test that we don't use an inconsistent metric between updating and walking nodes during
6112 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
6113 // was updated with a different criterion from the heap sorting, resulting in loops in
6114 // calculated paths. We test for that specific case here.
6116 // We construct a network that looks like this:
6118 // node2 -1(3)2- node3
6122 // node1 -1(5)2- node4 -1(1)2- node6
6128 // We create a loop on the side of our real path - our destination is node 6, with a
6129 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
6130 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
6131 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
6132 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
6133 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
6134 // "previous hop" being set to node 3, creating a loop in the path.
6135 let secp_ctx = Secp256k1::new();
6136 let logger = Arc::new(ln_test_utils::TestLogger::new());
6137 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6138 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
6139 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6140 let scorer = ln_test_utils::TestScorer::new();
6141 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6142 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6143 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
6145 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
6146 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6147 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6148 short_channel_id: 6,
6151 cltv_expiry_delta: (6 << 4) | 0,
6152 htlc_minimum_msat: 0,
6153 htlc_maximum_msat: MAX_VALUE_MSAT,
6155 fee_proportional_millionths: 0,
6156 excess_data: Vec::new()
6158 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
6160 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6161 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6162 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6163 short_channel_id: 5,
6166 cltv_expiry_delta: (5 << 4) | 0,
6167 htlc_minimum_msat: 0,
6168 htlc_maximum_msat: MAX_VALUE_MSAT,
6170 fee_proportional_millionths: 0,
6171 excess_data: Vec::new()
6173 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
6175 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
6176 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6177 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6178 short_channel_id: 4,
6181 cltv_expiry_delta: (4 << 4) | 0,
6182 htlc_minimum_msat: 0,
6183 htlc_maximum_msat: MAX_VALUE_MSAT,
6185 fee_proportional_millionths: 0,
6186 excess_data: Vec::new()
6188 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6190 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6191 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
6192 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6193 short_channel_id: 3,
6196 cltv_expiry_delta: (3 << 4) | 0,
6197 htlc_minimum_msat: 0,
6198 htlc_maximum_msat: MAX_VALUE_MSAT,
6200 fee_proportional_millionths: 0,
6201 excess_data: Vec::new()
6203 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6205 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6206 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
6207 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6208 short_channel_id: 2,
6211 cltv_expiry_delta: (2 << 4) | 0,
6212 htlc_minimum_msat: 0,
6213 htlc_maximum_msat: MAX_VALUE_MSAT,
6215 fee_proportional_millionths: 0,
6216 excess_data: Vec::new()
6219 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6220 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6221 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6222 short_channel_id: 1,
6225 cltv_expiry_delta: (1 << 4) | 0,
6226 htlc_minimum_msat: 100,
6227 htlc_maximum_msat: MAX_VALUE_MSAT,
6229 fee_proportional_millionths: 0,
6230 excess_data: Vec::new()
6232 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6235 // Now ensure the route flows simply over nodes 1 and 4 to 6.
6236 let route_params = RouteParameters::from_payment_params_and_value(
6237 payment_params, 10_000);
6238 let route = get_route(&our_id, &route_params, &network.read_only(), None,
6239 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6240 assert_eq!(route.paths.len(), 1);
6241 assert_eq!(route.paths[0].hops.len(), 3);
6243 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6244 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6245 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6246 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6247 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6248 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6250 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6251 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6252 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6253 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6254 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6255 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6257 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6258 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6259 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6260 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6261 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6262 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6268 fn exact_fee_liquidity_limit() {
6269 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6270 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6271 // we calculated fees on a higher value, resulting in us ignoring such paths.
6272 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6273 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6274 let scorer = ln_test_utils::TestScorer::new();
6275 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6276 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6277 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6279 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6281 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6282 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6283 short_channel_id: 2,
6286 cltv_expiry_delta: 0,
6287 htlc_minimum_msat: 0,
6288 htlc_maximum_msat: 85_000,
6290 fee_proportional_millionths: 0,
6291 excess_data: Vec::new()
6294 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6295 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6296 short_channel_id: 12,
6299 cltv_expiry_delta: (4 << 4) | 1,
6300 htlc_minimum_msat: 0,
6301 htlc_maximum_msat: 270_000,
6303 fee_proportional_millionths: 1000000,
6304 excess_data: Vec::new()
6308 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6309 // 200% fee charged channel 13 in the 1-to-2 direction.
6310 let mut route_params = RouteParameters::from_payment_params_and_value(
6311 payment_params, 90_000);
6312 route_params.max_total_routing_fee_msat = Some(90_000*2);
6313 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6314 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6315 assert_eq!(route.paths.len(), 1);
6316 assert_eq!(route.paths[0].hops.len(), 2);
6318 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6319 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6320 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6321 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6322 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6323 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6325 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6326 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6327 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6328 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6329 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6330 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6335 fn htlc_max_reduction_below_min() {
6336 // Test that if, while walking the graph, we reduce the value being sent to meet an
6337 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6338 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6339 // resulting in us thinking there is no possible path, even if other paths exist.
6340 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6341 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6342 let scorer = ln_test_utils::TestScorer::new();
6343 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6344 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6345 let config = UserConfig::default();
6346 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6347 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6350 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6351 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6352 // then try to send 90_000.
6353 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6354 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6355 short_channel_id: 2,
6358 cltv_expiry_delta: 0,
6359 htlc_minimum_msat: 0,
6360 htlc_maximum_msat: 80_000,
6362 fee_proportional_millionths: 0,
6363 excess_data: Vec::new()
6365 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6366 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6367 short_channel_id: 4,
6370 cltv_expiry_delta: (4 << 4) | 1,
6371 htlc_minimum_msat: 90_000,
6372 htlc_maximum_msat: MAX_VALUE_MSAT,
6374 fee_proportional_millionths: 0,
6375 excess_data: Vec::new()
6379 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6380 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6381 // expensive) channels 12-13 path.
6382 let mut route_params = RouteParameters::from_payment_params_and_value(
6383 payment_params, 90_000);
6384 route_params.max_total_routing_fee_msat = Some(90_000*2);
6385 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6386 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6387 assert_eq!(route.paths.len(), 1);
6388 assert_eq!(route.paths[0].hops.len(), 2);
6390 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6391 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6392 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6393 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6394 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6395 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6397 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6398 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6399 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6400 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6401 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6402 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6407 fn multiple_direct_first_hops() {
6408 // Previously we'd only ever considered one first hop path per counterparty.
6409 // However, as we don't restrict users to one channel per peer, we really need to support
6410 // looking at all first hop paths.
6411 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6412 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6413 // route over multiple channels with the same first hop.
6414 let secp_ctx = Secp256k1::new();
6415 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6416 let logger = Arc::new(ln_test_utils::TestLogger::new());
6417 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6418 let scorer = ln_test_utils::TestScorer::new();
6419 let config = UserConfig::default();
6420 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6421 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6423 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6424 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6427 let route_params = RouteParameters::from_payment_params_and_value(
6428 payment_params.clone(), 100_000);
6429 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6430 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6431 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6432 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6433 assert_eq!(route.paths.len(), 1);
6434 assert_eq!(route.paths[0].hops.len(), 1);
6436 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6437 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6438 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6441 let route_params = RouteParameters::from_payment_params_and_value(
6442 payment_params.clone(), 100_000);
6443 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6444 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6445 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6446 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6447 assert_eq!(route.paths.len(), 2);
6448 assert_eq!(route.paths[0].hops.len(), 1);
6449 assert_eq!(route.paths[1].hops.len(), 1);
6451 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6452 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6454 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6455 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6457 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6458 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6462 // If we have a bunch of outbound channels to the same node, where most are not
6463 // sufficient to pay the full payment, but one is, we should default to just using the
6464 // one single channel that has sufficient balance, avoiding MPP.
6466 // If we have several options above the 3xpayment value threshold, we should pick the
6467 // smallest of them, avoiding further fragmenting our available outbound balance to
6469 let route_params = RouteParameters::from_payment_params_and_value(
6470 payment_params, 100_000);
6471 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6472 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6473 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6474 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6475 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6476 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6477 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6478 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6479 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6480 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6481 assert_eq!(route.paths.len(), 1);
6482 assert_eq!(route.paths[0].hops.len(), 1);
6484 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6485 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6486 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6491 fn prefers_shorter_route_with_higher_fees() {
6492 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6493 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6494 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6496 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6497 let scorer = ln_test_utils::TestScorer::new();
6498 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6499 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6500 let route_params = RouteParameters::from_payment_params_and_value(
6501 payment_params.clone(), 100);
6502 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6503 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6504 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6506 assert_eq!(route.get_total_fees(), 100);
6507 assert_eq!(route.get_total_amount(), 100);
6508 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6510 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6511 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6512 let scorer = FixedPenaltyScorer::with_penalty(100);
6513 let route_params = RouteParameters::from_payment_params_and_value(
6514 payment_params, 100);
6515 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6516 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6517 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6519 assert_eq!(route.get_total_fees(), 300);
6520 assert_eq!(route.get_total_amount(), 100);
6521 assert_eq!(path, vec![2, 4, 7, 10]);
6524 struct BadChannelScorer {
6525 short_channel_id: u64,
6529 impl Writeable for BadChannelScorer {
6530 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6532 impl ScoreLookUp for BadChannelScorer {
6533 #[cfg(not(c_bindings))]
6534 type ScoreParams = ();
6535 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params: &crate::routing::scoring::ProbabilisticScoringFeeParameters) -> u64 {
6536 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6540 struct BadNodeScorer {
6545 impl Writeable for BadNodeScorer {
6546 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6549 impl ScoreLookUp for BadNodeScorer {
6550 #[cfg(not(c_bindings))]
6551 type ScoreParams = ();
6552 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params: &crate::routing::scoring::ProbabilisticScoringFeeParameters) -> u64 {
6553 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6558 fn avoids_routing_through_bad_channels_and_nodes() {
6559 let (secp_ctx, network, _, _, logger) = build_graph();
6560 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6561 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6562 let network_graph = network.read_only();
6564 // A path to nodes[6] exists when no penalties are applied to any channel.
6565 let scorer = ln_test_utils::TestScorer::new();
6566 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6567 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6568 let route_params = RouteParameters::from_payment_params_and_value(
6569 payment_params, 100);
6570 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6571 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6572 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6574 assert_eq!(route.get_total_fees(), 100);
6575 assert_eq!(route.get_total_amount(), 100);
6576 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6578 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6579 let scorer = BadChannelScorer { short_channel_id: 6 };
6580 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6581 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6582 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6584 assert_eq!(route.get_total_fees(), 300);
6585 assert_eq!(route.get_total_amount(), 100);
6586 assert_eq!(path, vec![2, 4, 7, 10]);
6588 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6589 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6590 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6591 &scorer, &Default::default(), &random_seed_bytes) {
6592 Err(LightningError { err, .. } ) => {
6593 assert_eq!(err, "Failed to find a path to the given destination");
6595 Ok(_) => panic!("Expected error"),
6600 fn total_fees_single_path() {
6602 paths: vec![Path { hops: vec![
6604 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6605 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6606 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6609 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6610 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6611 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6614 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6615 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6616 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6618 ], blinded_tail: None }],
6622 assert_eq!(route.get_total_fees(), 250);
6623 assert_eq!(route.get_total_amount(), 225);
6627 fn total_fees_multi_path() {
6629 paths: vec![Path { hops: vec![
6631 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6632 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6633 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6636 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6637 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6638 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6640 ], blinded_tail: None }, Path { hops: vec![
6642 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6643 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6644 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6647 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6648 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6649 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6651 ], blinded_tail: None }],
6655 assert_eq!(route.get_total_fees(), 200);
6656 assert_eq!(route.get_total_amount(), 300);
6660 fn total_empty_route_no_panic() {
6661 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6662 // would both panic if the route was completely empty. We test to ensure they return 0
6663 // here, even though its somewhat nonsensical as a route.
6664 let route = Route { paths: Vec::new(), route_params: None };
6666 assert_eq!(route.get_total_fees(), 0);
6667 assert_eq!(route.get_total_amount(), 0);
6671 fn limits_total_cltv_delta() {
6672 let (secp_ctx, network, _, _, logger) = build_graph();
6673 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6674 let network_graph = network.read_only();
6676 let scorer = ln_test_utils::TestScorer::new();
6678 // Make sure that generally there is at least one route available
6679 let feasible_max_total_cltv_delta = 1008;
6680 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6681 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6682 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6683 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6684 let route_params = RouteParameters::from_payment_params_and_value(
6685 feasible_payment_params, 100);
6686 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6687 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6688 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6689 assert_ne!(path.len(), 0);
6691 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6692 let fail_max_total_cltv_delta = 23;
6693 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6694 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6695 let route_params = RouteParameters::from_payment_params_and_value(
6696 fail_payment_params, 100);
6697 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6698 &Default::default(), &random_seed_bytes)
6700 Err(LightningError { err, .. } ) => {
6701 assert_eq!(err, "Failed to find a path to the given destination");
6703 Ok(_) => panic!("Expected error"),
6708 fn avoids_recently_failed_paths() {
6709 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6710 // randomly inserting channels into it until we can't find a route anymore.
6711 let (secp_ctx, network, _, _, logger) = build_graph();
6712 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6713 let network_graph = network.read_only();
6715 let scorer = ln_test_utils::TestScorer::new();
6716 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6717 .with_max_path_count(1);
6718 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6719 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6721 // We should be able to find a route initially, and then after we fail a few random
6722 // channels eventually we won't be able to any longer.
6723 let route_params = RouteParameters::from_payment_params_and_value(
6724 payment_params.clone(), 100);
6725 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6726 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6728 let route_params = RouteParameters::from_payment_params_and_value(
6729 payment_params.clone(), 100);
6730 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6731 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6733 for chan in route.paths[0].hops.iter() {
6734 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6736 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6737 % route.paths[0].hops.len();
6738 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6744 fn limits_path_length() {
6745 let (secp_ctx, network, _, _, logger) = build_line_graph();
6746 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6747 let network_graph = network.read_only();
6749 let scorer = ln_test_utils::TestScorer::new();
6750 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6751 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6753 // First check we can actually create a long route on this graph.
6754 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6755 let route_params = RouteParameters::from_payment_params_and_value(
6756 feasible_payment_params, 100);
6757 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6758 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6759 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6760 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6762 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6763 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6764 let route_params = RouteParameters::from_payment_params_and_value(
6765 fail_payment_params, 100);
6766 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6767 &Default::default(), &random_seed_bytes)
6769 Err(LightningError { err, .. } ) => {
6770 assert_eq!(err, "Failed to find a path to the given destination");
6772 Ok(_) => panic!("Expected error"),
6777 fn adds_and_limits_cltv_offset() {
6778 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6779 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6781 let scorer = ln_test_utils::TestScorer::new();
6783 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6784 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6785 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6786 let route_params = RouteParameters::from_payment_params_and_value(
6787 payment_params.clone(), 100);
6788 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6789 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6790 assert_eq!(route.paths.len(), 1);
6792 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6794 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6795 let mut route_default = route.clone();
6796 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6797 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6798 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6799 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6800 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6802 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6803 let mut route_limited = route.clone();
6804 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6805 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6806 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6807 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6808 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6812 fn adds_plausible_cltv_offset() {
6813 let (secp_ctx, network, _, _, logger) = build_graph();
6814 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6815 let network_graph = network.read_only();
6816 let network_nodes = network_graph.nodes();
6817 let network_channels = network_graph.channels();
6818 let scorer = ln_test_utils::TestScorer::new();
6819 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6820 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6821 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6823 let route_params = RouteParameters::from_payment_params_and_value(
6824 payment_params.clone(), 100);
6825 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6826 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6827 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6829 let mut path_plausibility = vec![];
6831 for p in route.paths {
6832 // 1. Select random observation point
6833 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6834 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6836 prng.process_in_place(&mut random_bytes);
6837 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6838 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6840 // 2. Calculate what CLTV expiry delta we would observe there
6841 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6843 // 3. Starting from the observation point, find candidate paths
6844 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6845 candidates.push_back((observation_point, vec![]));
6847 let mut found_plausible_candidate = false;
6849 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6850 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6851 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6852 found_plausible_candidate = true;
6853 break 'candidate_loop;
6857 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6858 for channel_id in &cur_node.channels {
6859 if let Some(channel_info) = network_channels.get(&channel_id) {
6860 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6861 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6862 if cur_path_cltv_deltas.iter().sum::<u32>()
6863 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6864 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6865 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6866 candidates.push_back((*next_id, new_path_cltv_deltas));
6874 path_plausibility.push(found_plausible_candidate);
6876 assert!(path_plausibility.iter().all(|x| *x));
6880 fn builds_correct_path_from_hops() {
6881 let (secp_ctx, network, _, _, logger) = build_graph();
6882 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6883 let network_graph = network.read_only();
6885 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6886 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6888 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6889 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6890 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6891 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6892 Arc::clone(&logger), &random_seed_bytes).unwrap();
6893 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6894 assert_eq!(hops.len(), route.paths[0].hops.len());
6895 for (idx, hop_pubkey) in hops.iter().enumerate() {
6896 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6901 fn avoids_saturating_channels() {
6902 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6903 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6904 let decay_params = ProbabilisticScoringDecayParameters::default();
6905 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6907 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6908 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6909 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6910 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6911 short_channel_id: 4,
6914 cltv_expiry_delta: (4 << 4) | 1,
6915 htlc_minimum_msat: 0,
6916 htlc_maximum_msat: 250_000_000,
6918 fee_proportional_millionths: 0,
6919 excess_data: Vec::new()
6921 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6922 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6923 short_channel_id: 13,
6926 cltv_expiry_delta: (13 << 4) | 1,
6927 htlc_minimum_msat: 0,
6928 htlc_maximum_msat: 250_000_000,
6930 fee_proportional_millionths: 0,
6931 excess_data: Vec::new()
6934 let config = UserConfig::default();
6935 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6936 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6938 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6939 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6940 // 100,000 sats is less than the available liquidity on each channel, set above.
6941 let route_params = RouteParameters::from_payment_params_and_value(
6942 payment_params, 100_000_000);
6943 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6944 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6945 assert_eq!(route.paths.len(), 2);
6946 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6947 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6950 #[cfg(not(feature = "no-std"))]
6951 pub(super) fn random_init_seed() -> u64 {
6952 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6953 use core::hash::{BuildHasher, Hasher};
6954 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6955 println!("Using seed of {}", seed);
6960 #[cfg(not(feature = "no-std"))]
6961 fn generate_routes() {
6962 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6964 let logger = ln_test_utils::TestLogger::new();
6965 let graph = match super::bench_utils::read_network_graph(&logger) {
6973 let params = ProbabilisticScoringFeeParameters::default();
6974 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6975 let features = super::Bolt11InvoiceFeatures::empty();
6977 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6981 #[cfg(not(feature = "no-std"))]
6982 fn generate_routes_mpp() {
6983 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6985 let logger = ln_test_utils::TestLogger::new();
6986 let graph = match super::bench_utils::read_network_graph(&logger) {
6994 let params = ProbabilisticScoringFeeParameters::default();
6995 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6996 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
6998 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7002 #[cfg(not(feature = "no-std"))]
7003 fn generate_large_mpp_routes() {
7004 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
7006 let logger = ln_test_utils::TestLogger::new();
7007 let graph = match super::bench_utils::read_network_graph(&logger) {
7015 let params = ProbabilisticScoringFeeParameters::default();
7016 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
7017 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7019 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
7023 fn honors_manual_penalties() {
7024 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
7025 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7027 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7028 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7030 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
7031 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
7033 // First check set manual penalties are returned by the scorer.
7034 let usage = ChannelUsage {
7036 inflight_htlc_msat: 0,
7037 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
7039 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
7040 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
7041 let network_graph = network_graph.read_only();
7042 let channels = network_graph.channels();
7043 let channel = channels.get(&5).unwrap();
7044 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
7045 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop(PublicHopCandidate {
7047 short_channel_id: 5,
7049 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
7051 // Then check we can get a normal route
7052 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
7053 let route_params = RouteParameters::from_payment_params_and_value(
7054 payment_params, 100);
7055 let route = get_route(&our_id, &route_params, &network_graph, None,
7056 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
7057 assert!(route.is_ok());
7059 // Then check that we can't get a route if we ban an intermediate node.
7060 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
7061 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7062 assert!(route.is_err());
7064 // Finally make sure we can route again, when we remove the ban.
7065 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
7066 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7067 assert!(route.is_ok());
7071 fn abide_by_route_hint_max_htlc() {
7072 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
7073 // params in the final route.
7074 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7075 let netgraph = network_graph.read_only();
7076 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7077 let scorer = ln_test_utils::TestScorer::new();
7078 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7079 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7080 let config = UserConfig::default();
7082 let max_htlc_msat = 50_000;
7083 let route_hint_1 = RouteHint(vec![RouteHintHop {
7084 src_node_id: nodes[2],
7085 short_channel_id: 42,
7088 proportional_millionths: 0,
7090 cltv_expiry_delta: 10,
7091 htlc_minimum_msat: None,
7092 htlc_maximum_msat: Some(max_htlc_msat),
7094 let dest_node_id = ln_test_utils::pubkey(42);
7095 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7096 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
7097 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7100 // Make sure we'll error if our route hints don't have enough liquidity according to their
7101 // htlc_maximum_msat.
7102 let mut route_params = RouteParameters::from_payment_params_and_value(
7103 payment_params, max_htlc_msat + 1);
7104 route_params.max_total_routing_fee_msat = None;
7105 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
7106 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
7109 assert_eq!(err, "Failed to find a sufficient route to the given destination");
7110 } else { panic!(); }
7112 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
7113 let mut route_hint_2 = route_hint_1.clone();
7114 route_hint_2.0[0].short_channel_id = 43;
7115 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7116 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7117 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7119 let mut route_params = RouteParameters::from_payment_params_and_value(
7120 payment_params, max_htlc_msat + 1);
7121 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
7122 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
7123 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7124 assert_eq!(route.paths.len(), 2);
7125 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7126 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7130 fn direct_channel_to_hints_with_max_htlc() {
7131 // Check that if we have a first hop channel peer that's connected to multiple provided route
7132 // hints, that we properly split the payment between the route hints if needed.
7133 let logger = Arc::new(ln_test_utils::TestLogger::new());
7134 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
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 our_node_id = ln_test_utils::pubkey(42);
7141 let intermed_node_id = ln_test_utils::pubkey(43);
7142 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7144 let amt_msat = 900_000;
7145 let max_htlc_msat = 500_000;
7146 let route_hint_1 = RouteHint(vec![RouteHintHop {
7147 src_node_id: intermed_node_id,
7148 short_channel_id: 44,
7151 proportional_millionths: 0,
7153 cltv_expiry_delta: 10,
7154 htlc_minimum_msat: None,
7155 htlc_maximum_msat: Some(max_htlc_msat),
7157 src_node_id: intermed_node_id,
7158 short_channel_id: 45,
7161 proportional_millionths: 0,
7163 cltv_expiry_delta: 10,
7164 htlc_minimum_msat: None,
7165 // Check that later route hint max htlcs don't override earlier ones
7166 htlc_maximum_msat: Some(max_htlc_msat - 50),
7168 let mut route_hint_2 = route_hint_1.clone();
7169 route_hint_2.0[0].short_channel_id = 46;
7170 route_hint_2.0[1].short_channel_id = 47;
7171 let dest_node_id = ln_test_utils::pubkey(44);
7172 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7173 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7174 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7177 let route_params = RouteParameters::from_payment_params_and_value(
7178 payment_params, amt_msat);
7179 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7180 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7181 &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);
7185 assert_eq!(route.get_total_amount(), amt_msat);
7187 // Re-run but with two first hop channels connected to the same route hint peers that must be
7189 let first_hops = vec![
7190 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7191 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7193 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7194 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7195 &Default::default(), &random_seed_bytes).unwrap();
7196 assert_eq!(route.paths.len(), 2);
7197 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7198 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7199 assert_eq!(route.get_total_amount(), amt_msat);
7201 // Make sure this works for blinded route hints.
7202 let blinded_path = BlindedPath {
7203 introduction_node_id: intermed_node_id,
7204 blinding_point: ln_test_utils::pubkey(42),
7206 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
7207 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
7210 let blinded_payinfo = BlindedPayInfo {
7212 fee_proportional_millionths: 0,
7213 htlc_minimum_msat: 1,
7214 htlc_maximum_msat: max_htlc_msat,
7215 cltv_expiry_delta: 10,
7216 features: BlindedHopFeatures::empty(),
7218 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7219 let payment_params = PaymentParameters::blinded(vec![
7220 (blinded_payinfo.clone(), blinded_path.clone()),
7221 (blinded_payinfo.clone(), blinded_path.clone())])
7222 .with_bolt12_features(bolt12_features).unwrap();
7223 let route_params = RouteParameters::from_payment_params_and_value(
7224 payment_params, amt_msat);
7225 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7226 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7227 &Default::default(), &random_seed_bytes).unwrap();
7228 assert_eq!(route.paths.len(), 2);
7229 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7230 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7231 assert_eq!(route.get_total_amount(), amt_msat);
7235 fn blinded_route_ser() {
7236 let blinded_path_1 = BlindedPath {
7237 introduction_node_id: ln_test_utils::pubkey(42),
7238 blinding_point: ln_test_utils::pubkey(43),
7240 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7241 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7244 let blinded_path_2 = BlindedPath {
7245 introduction_node_id: ln_test_utils::pubkey(46),
7246 blinding_point: ln_test_utils::pubkey(47),
7248 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7249 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7252 // (De)serialize a Route with 1 blinded path out of two total paths.
7253 let mut route = Route { paths: vec![Path {
7254 hops: vec![RouteHop {
7255 pubkey: ln_test_utils::pubkey(50),
7256 node_features: NodeFeatures::empty(),
7257 short_channel_id: 42,
7258 channel_features: ChannelFeatures::empty(),
7260 cltv_expiry_delta: 0,
7261 maybe_announced_channel: true,
7263 blinded_tail: Some(BlindedTail {
7264 hops: blinded_path_1.blinded_hops,
7265 blinding_point: blinded_path_1.blinding_point,
7266 excess_final_cltv_expiry_delta: 40,
7267 final_value_msat: 100,
7269 hops: vec![RouteHop {
7270 pubkey: ln_test_utils::pubkey(51),
7271 node_features: NodeFeatures::empty(),
7272 short_channel_id: 43,
7273 channel_features: ChannelFeatures::empty(),
7275 cltv_expiry_delta: 0,
7276 maybe_announced_channel: true,
7277 }], blinded_tail: None }],
7280 let encoded_route = route.encode();
7281 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7282 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7283 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7285 // (De)serialize a Route with two paths, each containing a blinded tail.
7286 route.paths[1].blinded_tail = Some(BlindedTail {
7287 hops: blinded_path_2.blinded_hops,
7288 blinding_point: blinded_path_2.blinding_point,
7289 excess_final_cltv_expiry_delta: 41,
7290 final_value_msat: 101,
7292 let encoded_route = route.encode();
7293 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7294 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7295 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7299 fn blinded_path_inflight_processing() {
7300 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7301 // account for the blinded tail's final amount_msat.
7302 let mut inflight_htlcs = InFlightHtlcs::new();
7303 let blinded_path = BlindedPath {
7304 introduction_node_id: ln_test_utils::pubkey(43),
7305 blinding_point: ln_test_utils::pubkey(48),
7306 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7309 hops: vec![RouteHop {
7310 pubkey: ln_test_utils::pubkey(42),
7311 node_features: NodeFeatures::empty(),
7312 short_channel_id: 42,
7313 channel_features: ChannelFeatures::empty(),
7315 cltv_expiry_delta: 0,
7316 maybe_announced_channel: false,
7319 pubkey: blinded_path.introduction_node_id,
7320 node_features: NodeFeatures::empty(),
7321 short_channel_id: 43,
7322 channel_features: ChannelFeatures::empty(),
7324 cltv_expiry_delta: 0,
7325 maybe_announced_channel: false,
7327 blinded_tail: Some(BlindedTail {
7328 hops: blinded_path.blinded_hops,
7329 blinding_point: blinded_path.blinding_point,
7330 excess_final_cltv_expiry_delta: 0,
7331 final_value_msat: 200,
7334 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7335 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7336 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7340 fn blinded_path_cltv_shadow_offset() {
7341 // Make sure we add a shadow offset when sending to blinded paths.
7342 let blinded_path = BlindedPath {
7343 introduction_node_id: ln_test_utils::pubkey(43),
7344 blinding_point: ln_test_utils::pubkey(44),
7346 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7347 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7350 let mut route = Route { paths: vec![Path {
7351 hops: vec![RouteHop {
7352 pubkey: ln_test_utils::pubkey(42),
7353 node_features: NodeFeatures::empty(),
7354 short_channel_id: 42,
7355 channel_features: ChannelFeatures::empty(),
7357 cltv_expiry_delta: 0,
7358 maybe_announced_channel: false,
7361 pubkey: blinded_path.introduction_node_id,
7362 node_features: NodeFeatures::empty(),
7363 short_channel_id: 43,
7364 channel_features: ChannelFeatures::empty(),
7366 cltv_expiry_delta: 0,
7367 maybe_announced_channel: false,
7370 blinded_tail: Some(BlindedTail {
7371 hops: blinded_path.blinded_hops,
7372 blinding_point: blinded_path.blinding_point,
7373 excess_final_cltv_expiry_delta: 0,
7374 final_value_msat: 200,
7376 }], route_params: None};
7378 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7379 let (_, network_graph, _, _, _) = build_line_graph();
7380 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7381 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7382 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7386 fn simple_blinded_route_hints() {
7387 do_simple_blinded_route_hints(1);
7388 do_simple_blinded_route_hints(2);
7389 do_simple_blinded_route_hints(3);
7392 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7393 // Check that we can generate a route to a blinded path with the expected hops.
7394 let (secp_ctx, network, _, _, logger) = build_graph();
7395 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7396 let network_graph = network.read_only();
7398 let scorer = ln_test_utils::TestScorer::new();
7399 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7400 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7402 let mut blinded_path = BlindedPath {
7403 introduction_node_id: nodes[2],
7404 blinding_point: ln_test_utils::pubkey(42),
7405 blinded_hops: Vec::with_capacity(num_blinded_hops),
7407 for i in 0..num_blinded_hops {
7408 blinded_path.blinded_hops.push(
7409 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7412 let blinded_payinfo = BlindedPayInfo {
7414 fee_proportional_millionths: 500,
7415 htlc_minimum_msat: 1000,
7416 htlc_maximum_msat: 100_000_000,
7417 cltv_expiry_delta: 15,
7418 features: BlindedHopFeatures::empty(),
7421 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7422 let route_params = RouteParameters::from_payment_params_and_value(
7423 payment_params, 1001);
7424 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7425 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7426 assert_eq!(route.paths.len(), 1);
7427 assert_eq!(route.paths[0].hops.len(), 2);
7429 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7430 assert_eq!(tail.hops, blinded_path.blinded_hops);
7431 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7432 assert_eq!(tail.final_value_msat, 1001);
7434 let final_hop = route.paths[0].hops.last().unwrap();
7435 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
7436 if tail.hops.len() > 1 {
7437 assert_eq!(final_hop.fee_msat,
7438 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7439 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7441 assert_eq!(final_hop.fee_msat, 0);
7442 assert_eq!(final_hop.cltv_expiry_delta, 0);
7447 fn blinded_path_routing_errors() {
7448 // Check that we can generate a route to a blinded path with the expected hops.
7449 let (secp_ctx, network, _, _, logger) = build_graph();
7450 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7451 let network_graph = network.read_only();
7453 let scorer = ln_test_utils::TestScorer::new();
7454 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7455 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7457 let mut invalid_blinded_path = BlindedPath {
7458 introduction_node_id: nodes[2],
7459 blinding_point: ln_test_utils::pubkey(42),
7461 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7464 let blinded_payinfo = BlindedPayInfo {
7466 fee_proportional_millionths: 500,
7467 htlc_minimum_msat: 1000,
7468 htlc_maximum_msat: 100_000_000,
7469 cltv_expiry_delta: 15,
7470 features: BlindedHopFeatures::empty(),
7473 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7474 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
7475 let payment_params = PaymentParameters::blinded(vec![
7476 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7477 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7478 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7479 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7480 &scorer, &Default::default(), &random_seed_bytes)
7482 Err(LightningError { err, .. }) => {
7483 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7485 _ => panic!("Expected error")
7488 invalid_blinded_path.introduction_node_id = our_id;
7489 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7490 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7491 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7492 &Default::default(), &random_seed_bytes)
7494 Err(LightningError { err, .. }) => {
7495 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7497 _ => panic!("Expected error")
7500 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
7501 invalid_blinded_path.blinded_hops.clear();
7502 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7503 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7504 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7505 &Default::default(), &random_seed_bytes)
7507 Err(LightningError { err, .. }) => {
7508 assert_eq!(err, "0-hop blinded path provided");
7510 _ => panic!("Expected error")
7515 fn matching_intro_node_paths_provided() {
7516 // Check that if multiple blinded paths with the same intro node are provided in payment
7517 // parameters, we'll return the correct paths in the resulting MPP route.
7518 let (secp_ctx, network, _, _, logger) = build_graph();
7519 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7520 let network_graph = network.read_only();
7522 let scorer = ln_test_utils::TestScorer::new();
7523 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7524 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7525 let config = UserConfig::default();
7527 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7528 let blinded_path_1 = BlindedPath {
7529 introduction_node_id: nodes[2],
7530 blinding_point: ln_test_utils::pubkey(42),
7532 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7533 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7536 let blinded_payinfo_1 = BlindedPayInfo {
7538 fee_proportional_millionths: 0,
7539 htlc_minimum_msat: 0,
7540 htlc_maximum_msat: 30_000,
7541 cltv_expiry_delta: 0,
7542 features: BlindedHopFeatures::empty(),
7545 let mut blinded_path_2 = blinded_path_1.clone();
7546 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7547 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7548 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7550 let blinded_hints = vec![
7551 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7552 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7554 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7555 .with_bolt12_features(bolt12_features).unwrap();
7557 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7558 route_params.max_total_routing_fee_msat = Some(100_000);
7559 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7560 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7561 assert_eq!(route.paths.len(), 2);
7562 let mut total_amount_paid_msat = 0;
7563 for path in route.paths.into_iter() {
7564 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7565 if let Some(bt) = &path.blinded_tail {
7566 assert_eq!(bt.blinding_point,
7567 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7568 .map(|(_, bp)| bp.blinding_point).unwrap());
7569 } else { panic!(); }
7570 total_amount_paid_msat += path.final_value_msat();
7572 assert_eq!(total_amount_paid_msat, 100_000);
7576 fn direct_to_intro_node() {
7577 // This previously caused a debug panic in the router when asserting
7578 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7579 // direct channels we failed to account for the fee charged for use of the blinded path.
7582 // node0 -1(1)2 - node1
7583 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7584 // doesn't account for the blinded path fee.
7586 let secp_ctx = Secp256k1::new();
7587 let logger = Arc::new(ln_test_utils::TestLogger::new());
7588 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7589 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7590 let scorer = ln_test_utils::TestScorer::new();
7591 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7592 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7594 let amt_msat = 10_000_000;
7595 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7596 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7597 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7598 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7599 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7600 short_channel_id: 1,
7603 cltv_expiry_delta: 42,
7604 htlc_minimum_msat: 1_000,
7605 htlc_maximum_msat: 10_000_000,
7607 fee_proportional_millionths: 0,
7608 excess_data: Vec::new()
7610 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7611 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7612 short_channel_id: 1,
7615 cltv_expiry_delta: 42,
7616 htlc_minimum_msat: 1_000,
7617 htlc_maximum_msat: 10_000_000,
7619 fee_proportional_millionths: 0,
7620 excess_data: Vec::new()
7622 let first_hops = vec![
7623 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7625 let blinded_path = BlindedPath {
7626 introduction_node_id: nodes[1],
7627 blinding_point: ln_test_utils::pubkey(42),
7629 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7630 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7633 let blinded_payinfo = BlindedPayInfo {
7634 fee_base_msat: 1000,
7635 fee_proportional_millionths: 0,
7636 htlc_minimum_msat: 1000,
7637 htlc_maximum_msat: MAX_VALUE_MSAT,
7638 cltv_expiry_delta: 0,
7639 features: BlindedHopFeatures::empty(),
7641 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7643 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7645 let netgraph = network_graph.read_only();
7646 let route_params = RouteParameters::from_payment_params_and_value(
7647 payment_params.clone(), amt_msat);
7648 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7649 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7650 &Default::default(), &random_seed_bytes) {
7651 assert_eq!(err, "Failed to find a path to the given destination");
7652 } else { panic!("Expected error") }
7654 // Sending an exact amount accounting for the blinded path fee works.
7655 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7656 let route_params = RouteParameters::from_payment_params_and_value(
7657 payment_params, amt_minus_blinded_path_fee);
7658 let route = get_route(&nodes[0], &route_params, &netgraph,
7659 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7660 &Default::default(), &random_seed_bytes).unwrap();
7661 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7662 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7666 fn direct_to_matching_intro_nodes() {
7667 // This previously caused us to enter `unreachable` code in the following situation:
7668 // 1. We add a route candidate for intro_node contributing a high amount
7669 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7670 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7671 // amount, and update our route candidate for intro_node for the lower amount
7672 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7673 // lower contribution amount, but fail (this was previously caused by failure to account for
7674 // blinded path fees when adding first_hop<>intro_node candidates)
7675 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7676 // candidate still thinks its path is contributing the original higher amount. This caused us
7677 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7679 let secp_ctx = Secp256k1::new();
7680 let logger = Arc::new(ln_test_utils::TestLogger::new());
7681 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7682 let scorer = ln_test_utils::TestScorer::new();
7683 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7684 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7685 let config = UserConfig::default();
7687 // Values are taken from the fuzz input that uncovered this panic.
7688 let amt_msat = 21_7020_5185_1403_2640;
7689 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7690 let first_hops = vec![
7691 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7692 18446744073709551615)];
7694 let blinded_path = BlindedPath {
7695 introduction_node_id: nodes[1],
7696 blinding_point: ln_test_utils::pubkey(42),
7698 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7699 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7702 let blinded_payinfo = BlindedPayInfo {
7703 fee_base_msat: 5046_2720,
7704 fee_proportional_millionths: 0,
7705 htlc_minimum_msat: 4503_5996_2737_0496,
7706 htlc_maximum_msat: 45_0359_9627_3704_9600,
7707 cltv_expiry_delta: 0,
7708 features: BlindedHopFeatures::empty(),
7710 let mut blinded_hints = vec![
7711 (blinded_payinfo.clone(), blinded_path.clone()),
7712 (blinded_payinfo.clone(), blinded_path.clone()),
7714 blinded_hints[1].0.fee_base_msat = 419_4304;
7715 blinded_hints[1].0.fee_proportional_millionths = 257;
7716 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7717 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7718 blinded_hints[1].0.cltv_expiry_delta = 0;
7720 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7721 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7722 .with_bolt12_features(bolt12_features).unwrap();
7724 let netgraph = network_graph.read_only();
7725 let route_params = RouteParameters::from_payment_params_and_value(
7726 payment_params, amt_msat);
7727 let route = get_route(&nodes[0], &route_params, &netgraph,
7728 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7729 &Default::default(), &random_seed_bytes).unwrap();
7730 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7731 assert_eq!(route.get_total_amount(), amt_msat);
7735 fn we_are_intro_node_candidate_hops() {
7736 // This previously led to a panic in the router because we'd generate a Path with only a
7737 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7738 // where the origin node is the intro node. We now fully disallow considering candidate hops
7739 // where the origin node is the intro node.
7740 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7741 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7742 let scorer = ln_test_utils::TestScorer::new();
7743 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7744 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7745 let config = UserConfig::default();
7747 // Values are taken from the fuzz input that uncovered this panic.
7748 let amt_msat = 21_7020_5185_1423_0019;
7750 let blinded_path = BlindedPath {
7751 introduction_node_id: our_id,
7752 blinding_point: ln_test_utils::pubkey(42),
7754 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7755 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7758 let blinded_payinfo = BlindedPayInfo {
7759 fee_base_msat: 5052_9027,
7760 fee_proportional_millionths: 0,
7761 htlc_minimum_msat: 21_7020_5185_1423_0019,
7762 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7763 cltv_expiry_delta: 0,
7764 features: BlindedHopFeatures::empty(),
7766 let mut blinded_hints = vec![
7767 (blinded_payinfo.clone(), blinded_path.clone()),
7768 (blinded_payinfo.clone(), blinded_path.clone()),
7770 blinded_hints[1].1.introduction_node_id = nodes[6];
7772 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7773 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7774 .with_bolt12_features(bolt12_features.clone()).unwrap();
7776 let netgraph = network_graph.read_only();
7777 let route_params = RouteParameters::from_payment_params_and_value(
7778 payment_params, amt_msat);
7779 if let Err(LightningError { err, .. }) = get_route(
7780 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7782 assert_eq!(err, "Failed to find a path to the given destination");
7787 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7788 // This previously led to a debug panic in the router because we'd find an invalid Path with
7789 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7790 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7791 // the payment, when it was intended to only include the final value of the payment.
7792 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7793 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7794 let scorer = ln_test_utils::TestScorer::new();
7795 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7796 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7797 let config = UserConfig::default();
7799 // Values are taken from the fuzz input that uncovered this panic.
7800 let amt_msat = 21_7020_5185_1423_0019;
7802 let blinded_path = BlindedPath {
7803 introduction_node_id: our_id,
7804 blinding_point: ln_test_utils::pubkey(42),
7806 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7807 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7810 let blinded_payinfo = BlindedPayInfo {
7811 fee_base_msat: 10_4425_1395,
7812 fee_proportional_millionths: 0,
7813 htlc_minimum_msat: 21_7301_9934_9094_0931,
7814 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7815 cltv_expiry_delta: 0,
7816 features: BlindedHopFeatures::empty(),
7818 let mut blinded_hints = vec![
7819 (blinded_payinfo.clone(), blinded_path.clone()),
7820 (blinded_payinfo.clone(), blinded_path.clone()),
7821 (blinded_payinfo.clone(), blinded_path.clone()),
7823 blinded_hints[1].0.fee_base_msat = 5052_9027;
7824 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7825 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7827 blinded_hints[2].1.introduction_node_id = nodes[6];
7829 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7830 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7831 .with_bolt12_features(bolt12_features.clone()).unwrap();
7833 let netgraph = network_graph.read_only();
7834 let route_params = RouteParameters::from_payment_params_and_value(
7835 payment_params, amt_msat);
7836 if let Err(LightningError { err, .. }) = get_route(
7837 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7839 assert_eq!(err, "Failed to find a path to the given destination");
7844 fn min_htlc_overpay_violates_max_htlc() {
7845 do_min_htlc_overpay_violates_max_htlc(true);
7846 do_min_htlc_overpay_violates_max_htlc(false);
7848 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7849 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7850 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7851 // to `targets` and build an invalid path with it, and subsequently hit a debug panic asserting
7852 // that the used liquidity for a hop was less than its available liquidity limit.
7853 let secp_ctx = Secp256k1::new();
7854 let logger = Arc::new(ln_test_utils::TestLogger::new());
7855 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7856 let scorer = ln_test_utils::TestScorer::new();
7857 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7858 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7859 let config = UserConfig::default();
7861 // Values are taken from the fuzz input that uncovered this panic.
7862 let amt_msat = 7_4009_8048;
7863 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7864 let first_hop_outbound_capacity = 2_7345_2000;
7865 let first_hops = vec![get_channel_details(
7866 Some(200), nodes[0], channelmanager::provided_init_features(&config),
7867 first_hop_outbound_capacity
7870 let base_fee = 1_6778_3453;
7871 let htlc_min = 2_5165_8240;
7872 let payment_params = if blinded_payee {
7873 let blinded_path = BlindedPath {
7874 introduction_node_id: nodes[0],
7875 blinding_point: ln_test_utils::pubkey(42),
7877 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7878 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7881 let blinded_payinfo = BlindedPayInfo {
7882 fee_base_msat: base_fee,
7883 fee_proportional_millionths: 0,
7884 htlc_minimum_msat: htlc_min,
7885 htlc_maximum_msat: htlc_min * 1000,
7886 cltv_expiry_delta: 0,
7887 features: BlindedHopFeatures::empty(),
7889 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7890 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
7891 .with_bolt12_features(bolt12_features.clone()).unwrap()
7893 let route_hint = RouteHint(vec![RouteHintHop {
7894 src_node_id: nodes[0],
7895 short_channel_id: 42,
7897 base_msat: base_fee,
7898 proportional_millionths: 0,
7900 cltv_expiry_delta: 10,
7901 htlc_minimum_msat: Some(htlc_min),
7902 htlc_maximum_msat: None,
7905 PaymentParameters::from_node_id(nodes[1], 42)
7906 .with_route_hints(vec![route_hint]).unwrap()
7907 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7910 let netgraph = network_graph.read_only();
7911 let route_params = RouteParameters::from_payment_params_and_value(
7912 payment_params, amt_msat);
7913 if let Err(LightningError { err, .. }) = get_route(
7914 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7915 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7917 assert_eq!(err, "Failed to find a path to the given destination");
7922 fn previously_used_liquidity_violates_max_htlc() {
7923 do_previously_used_liquidity_violates_max_htlc(true);
7924 do_previously_used_liquidity_violates_max_htlc(false);
7927 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
7928 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
7929 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
7930 // candidate. In this case, the candidate does not have enough due to a previous path taking up
7931 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
7932 // asserting that the used liquidity for a hop was less than its available liquidity limit.
7933 let secp_ctx = Secp256k1::new();
7934 let logger = Arc::new(ln_test_utils::TestLogger::new());
7935 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7936 let scorer = ln_test_utils::TestScorer::new();
7937 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7938 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7939 let config = UserConfig::default();
7941 // Values are taken from the fuzz input that uncovered this panic.
7942 let amt_msat = 52_4288;
7943 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7944 let first_hops = vec![get_channel_details(
7945 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
7946 ), get_channel_details(
7947 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
7950 let base_fees = [0, 425_9840, 0, 0];
7951 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
7952 let payment_params = if blinded_payee {
7953 let blinded_path = BlindedPath {
7954 introduction_node_id: nodes[0],
7955 blinding_point: ln_test_utils::pubkey(42),
7957 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7958 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7961 let mut blinded_hints = Vec::new();
7962 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
7963 blinded_hints.push((BlindedPayInfo {
7964 fee_base_msat: *base_fee,
7965 fee_proportional_millionths: 0,
7966 htlc_minimum_msat: *htlc_min,
7967 htlc_maximum_msat: htlc_min * 100,
7968 cltv_expiry_delta: 10,
7969 features: BlindedHopFeatures::empty(),
7970 }, blinded_path.clone()));
7972 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7973 PaymentParameters::blinded(blinded_hints.clone())
7974 .with_bolt12_features(bolt12_features.clone()).unwrap()
7976 let mut route_hints = Vec::new();
7977 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
7978 route_hints.push(RouteHint(vec![RouteHintHop {
7979 src_node_id: nodes[0],
7980 short_channel_id: 42 + idx as u64,
7982 base_msat: *base_fee,
7983 proportional_millionths: 0,
7985 cltv_expiry_delta: 10,
7986 htlc_minimum_msat: Some(*htlc_min),
7987 htlc_maximum_msat: Some(htlc_min * 100),
7990 PaymentParameters::from_node_id(nodes[1], 42)
7991 .with_route_hints(route_hints).unwrap()
7992 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7995 let netgraph = network_graph.read_only();
7996 let route_params = RouteParameters::from_payment_params_and_value(
7997 payment_params, amt_msat);
7999 let route = get_route(
8000 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8001 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8003 assert_eq!(route.paths.len(), 1);
8004 assert_eq!(route.get_total_amount(), amt_msat);
8008 fn candidate_path_min() {
8009 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
8010 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
8011 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
8012 // would add a connecting first_hop node that did not have enough contribution amount, leading
8013 // to a debug panic upon invalid path construction.
8014 let secp_ctx = Secp256k1::new();
8015 let logger = Arc::new(ln_test_utils::TestLogger::new());
8016 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8017 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
8018 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8019 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8020 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8021 let config = UserConfig::default();
8023 // Values are taken from the fuzz input that uncovered this panic.
8024 let amt_msat = 7_4009_8048;
8025 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
8026 let first_hops = vec![get_channel_details(
8027 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
8030 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
8031 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8032 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8033 short_channel_id: 6,
8036 cltv_expiry_delta: (6 << 4) | 0,
8037 htlc_minimum_msat: 0,
8038 htlc_maximum_msat: MAX_VALUE_MSAT,
8040 fee_proportional_millionths: 0,
8041 excess_data: Vec::new()
8043 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
8045 let htlc_min = 2_5165_8240;
8046 let blinded_hints = vec![
8048 fee_base_msat: 1_6778_3453,
8049 fee_proportional_millionths: 0,
8050 htlc_minimum_msat: htlc_min,
8051 htlc_maximum_msat: htlc_min * 100,
8052 cltv_expiry_delta: 10,
8053 features: BlindedHopFeatures::empty(),
8055 introduction_node_id: nodes[0],
8056 blinding_point: ln_test_utils::pubkey(42),
8058 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8059 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8063 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8064 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8065 .with_bolt12_features(bolt12_features.clone()).unwrap();
8066 let route_params = RouteParameters::from_payment_params_and_value(
8067 payment_params, amt_msat);
8068 let netgraph = network_graph.read_only();
8070 if let Err(LightningError { err, .. }) = get_route(
8071 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8072 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8075 assert_eq!(err, "Failed to find a path to the given destination");
8080 fn path_contribution_includes_min_htlc_overpay() {
8081 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
8082 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
8083 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
8084 // selection, both tested here.
8085 let secp_ctx = Secp256k1::new();
8086 let logger = Arc::new(ln_test_utils::TestLogger::new());
8087 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8088 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8089 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8090 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8091 let config = UserConfig::default();
8093 // Values are taken from the fuzz input that uncovered this panic.
8094 let amt_msat = 562_0000;
8095 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8096 let first_hops = vec![
8097 get_channel_details(
8098 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
8102 let htlc_mins = [49_0000, 1125_0000];
8103 let payment_params = {
8104 let blinded_path = BlindedPath {
8105 introduction_node_id: nodes[0],
8106 blinding_point: ln_test_utils::pubkey(42),
8108 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8109 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8112 let mut blinded_hints = Vec::new();
8113 for htlc_min in htlc_mins.iter() {
8114 blinded_hints.push((BlindedPayInfo {
8116 fee_proportional_millionths: 0,
8117 htlc_minimum_msat: *htlc_min,
8118 htlc_maximum_msat: *htlc_min * 100,
8119 cltv_expiry_delta: 10,
8120 features: BlindedHopFeatures::empty(),
8121 }, blinded_path.clone()));
8123 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8124 PaymentParameters::blinded(blinded_hints.clone())
8125 .with_bolt12_features(bolt12_features.clone()).unwrap()
8128 let netgraph = network_graph.read_only();
8129 let route_params = RouteParameters::from_payment_params_and_value(
8130 payment_params, amt_msat);
8131 let route = get_route(
8132 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8133 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8136 assert_eq!(route.paths.len(), 1);
8137 assert_eq!(route.get_total_amount(), amt_msat);
8141 fn first_hop_preferred_over_hint() {
8142 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
8143 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
8144 let secp_ctx = Secp256k1::new();
8145 let logger = Arc::new(ln_test_utils::TestLogger::new());
8146 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8147 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
8148 let scorer = ln_test_utils::TestScorer::new();
8149 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8150 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8151 let config = UserConfig::default();
8153 let amt_msat = 1_000_000;
8154 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
8156 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
8157 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
8158 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8159 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8160 short_channel_id: 1,
8163 cltv_expiry_delta: 42,
8164 htlc_minimum_msat: 1_000,
8165 htlc_maximum_msat: 10_000_000,
8167 fee_proportional_millionths: 0,
8168 excess_data: Vec::new()
8170 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8171 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8172 short_channel_id: 1,
8175 cltv_expiry_delta: 42,
8176 htlc_minimum_msat: 1_000,
8177 htlc_maximum_msat: 10_000_000,
8179 fee_proportional_millionths: 0,
8180 excess_data: Vec::new()
8183 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
8184 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
8185 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8186 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8187 short_channel_id: 2,
8190 cltv_expiry_delta: 42,
8191 htlc_minimum_msat: 1_000,
8192 htlc_maximum_msat: 10_000_000,
8194 fee_proportional_millionths: 0,
8195 excess_data: Vec::new()
8197 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8198 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8199 short_channel_id: 2,
8202 cltv_expiry_delta: 42,
8203 htlc_minimum_msat: 1_000,
8204 htlc_maximum_msat: 10_000_000,
8206 fee_proportional_millionths: 0,
8207 excess_data: Vec::new()
8210 let dest_node_id = nodes[2];
8212 let route_hint = RouteHint(vec![RouteHintHop {
8213 src_node_id: our_node_id,
8214 short_channel_id: 44,
8217 proportional_millionths: 0,
8219 cltv_expiry_delta: 10,
8220 htlc_minimum_msat: None,
8221 htlc_maximum_msat: Some(5_000_000),
8224 src_node_id: nodes[0],
8225 short_channel_id: 45,
8228 proportional_millionths: 0,
8230 cltv_expiry_delta: 10,
8231 htlc_minimum_msat: None,
8232 htlc_maximum_msat: None,
8235 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8236 .with_route_hints(vec![route_hint]).unwrap()
8237 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8238 let route_params = RouteParameters::from_payment_params_and_value(
8239 payment_params, amt_msat);
8241 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8243 let first_hop = get_channel_details(Some(1), nodes[0],
8244 channelmanager::provided_init_features(&config), 999_999);
8245 let first_hops = vec![first_hop];
8247 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8248 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8249 &Default::default(), &random_seed_bytes).unwrap();
8250 assert_eq!(route.paths.len(), 1);
8251 assert_eq!(route.get_total_amount(), amt_msat);
8252 assert_eq!(route.paths[0].hops.len(), 2);
8253 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8254 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8255 assert_eq!(route.get_total_fees(), 123);
8257 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8258 // for a first hop channel.
8259 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8260 first_hop.outbound_scid_alias = Some(44);
8261 let first_hops = vec![first_hop];
8263 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8264 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8265 &Default::default(), &random_seed_bytes);
8266 assert!(route_res.is_err());
8268 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8269 // use the cheaper second hop of the route hint.
8270 let mut first_hop = get_channel_details(Some(1), nodes[0],
8271 channelmanager::provided_init_features(&config), 10_000_000);
8272 first_hop.outbound_scid_alias = Some(44);
8273 let first_hops = vec![first_hop];
8275 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8276 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8277 &Default::default(), &random_seed_bytes).unwrap();
8278 assert_eq!(route.paths.len(), 1);
8279 assert_eq!(route.get_total_amount(), amt_msat);
8280 assert_eq!(route.paths[0].hops.len(), 2);
8281 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8282 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8283 assert_eq!(route.get_total_fees(), 123);
8287 fn allow_us_being_first_hint() {
8288 // Check that we consider a route hint even if we are the src of the first hop.
8289 let secp_ctx = Secp256k1::new();
8290 let logger = Arc::new(ln_test_utils::TestLogger::new());
8291 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8292 let scorer = ln_test_utils::TestScorer::new();
8293 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8294 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8295 let config = UserConfig::default();
8297 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8299 let amt_msat = 1_000_000;
8300 let dest_node_id = nodes[1];
8302 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8303 let first_hops = vec![first_hop];
8305 let route_hint = RouteHint(vec![RouteHintHop {
8306 src_node_id: our_node_id,
8307 short_channel_id: 44,
8310 proportional_millionths: 0,
8312 cltv_expiry_delta: 10,
8313 htlc_minimum_msat: None,
8314 htlc_maximum_msat: None,
8317 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8318 .with_route_hints(vec![route_hint]).unwrap()
8319 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8321 let route_params = RouteParameters::from_payment_params_and_value(
8322 payment_params, amt_msat);
8325 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8326 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8327 &Default::default(), &random_seed_bytes).unwrap();
8329 assert_eq!(route.paths.len(), 1);
8330 assert_eq!(route.get_total_amount(), amt_msat);
8331 assert_eq!(route.get_total_fees(), 0);
8332 assert_eq!(route.paths[0].hops.len(), 1);
8334 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8338 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
8339 pub(crate) mod bench_utils {
8342 use std::time::Duration;
8344 use bitcoin::hashes::Hash;
8345 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
8347 use crate::chain::transaction::OutPoint;
8348 use crate::routing::scoring::ScoreUpdate;
8349 use crate::sign::{EntropySource, KeysManager};
8350 use crate::ln::ChannelId;
8351 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
8352 use crate::ln::features::Bolt11InvoiceFeatures;
8353 use crate::routing::gossip::NetworkGraph;
8354 use crate::util::config::UserConfig;
8355 use crate::util::ser::ReadableArgs;
8356 use crate::util::test_utils::TestLogger;
8358 /// Tries to open a network graph file, or panics with a URL to fetch it.
8359 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
8360 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
8361 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
8362 .or_else(|_| { // Fall back to guessing based on the binary location
8363 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8364 let mut path = std::env::current_exe().unwrap();
8365 path.pop(); // lightning-...
8367 path.pop(); // debug
8368 path.pop(); // target
8369 path.push("lightning");
8370 path.push("net_graph-2023-01-18.bin");
8373 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8374 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8375 let mut path = std::env::current_exe().unwrap();
8376 path.pop(); // bench...
8378 path.pop(); // debug
8379 path.pop(); // target
8380 path.pop(); // bench
8381 path.push("lightning");
8382 path.push("net_graph-2023-01-18.bin");
8385 .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");
8386 #[cfg(require_route_graph_test)]
8387 return Ok(res.unwrap());
8388 #[cfg(not(require_route_graph_test))]
8392 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
8393 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
8396 pub(crate) fn payer_pubkey() -> PublicKey {
8397 let secp_ctx = Secp256k1::new();
8398 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8402 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8404 channel_id: ChannelId::new_zero(),
8405 counterparty: ChannelCounterparty {
8406 features: channelmanager::provided_init_features(&UserConfig::default()),
8408 unspendable_punishment_reserve: 0,
8409 forwarding_info: None,
8410 outbound_htlc_minimum_msat: None,
8411 outbound_htlc_maximum_msat: None,
8413 funding_txo: Some(OutPoint {
8414 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8417 short_channel_id: Some(1),
8418 inbound_scid_alias: None,
8419 outbound_scid_alias: None,
8420 channel_value_satoshis: 10_000_000_000,
8422 balance_msat: 10_000_000_000,
8423 outbound_capacity_msat: 10_000_000_000,
8424 next_outbound_htlc_minimum_msat: 0,
8425 next_outbound_htlc_limit_msat: 10_000_000_000,
8426 inbound_capacity_msat: 0,
8427 unspendable_punishment_reserve: None,
8428 confirmations_required: None,
8429 confirmations: None,
8430 force_close_spend_delay: None,
8432 is_channel_ready: true,
8435 inbound_htlc_minimum_msat: None,
8436 inbound_htlc_maximum_msat: None,
8438 feerate_sat_per_1000_weight: None,
8439 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
8443 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8444 score_params: &crate::routing::scoring::ProbabilisticScoringFeeParameters, features: Bolt11InvoiceFeatures, mut seed: u64,
8445 starting_amount: u64, route_count: usize,
8446 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8447 let payer = payer_pubkey();
8448 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8449 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8451 let nodes = graph.read_only().nodes().clone();
8452 let mut route_endpoints = Vec::new();
8453 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
8454 // with some routes we picked being un-routable.
8455 for _ in 0..route_count * 3 / 2 {
8457 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8458 let src = PublicKey::from_slice(nodes.unordered_keys()
8459 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8460 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8461 let dst = PublicKey::from_slice(nodes.unordered_keys()
8462 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8463 let params = PaymentParameters::from_node_id(dst, 42)
8464 .with_bolt11_features(features.clone()).unwrap();
8465 let first_hop = first_hop(src);
8466 let amt_msat = starting_amount + seed % 1_000_000;
8467 let route_params = RouteParameters::from_payment_params_and_value(
8468 params.clone(), amt_msat);
8470 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8471 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8473 // ...and seed the scorer with success and failure data...
8474 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8475 let mut score_amt = seed % 1_000_000_000;
8477 // Generate fail/success paths for a wider range of potential amounts with
8478 // MPP enabled to give us a chance to apply penalties for more potential
8480 let mpp_features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
8481 let params = PaymentParameters::from_node_id(dst, 42)
8482 .with_bolt11_features(mpp_features).unwrap();
8483 let route_params = RouteParameters::from_payment_params_and_value(
8484 params.clone(), score_amt);
8485 let route_res = get_route(&payer, &route_params, &graph.read_only(),
8486 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
8487 &random_seed_bytes);
8488 if let Ok(route) = route_res {
8489 for path in route.paths {
8490 if seed & 0x80 == 0 {
8491 scorer.payment_path_successful(&path, Duration::ZERO);
8493 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
8494 scorer.payment_path_failed(&path, short_channel_id, Duration::ZERO);
8496 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8500 // If we couldn't find a path with a higher amount, reduce and try again.
8504 route_endpoints.push((first_hop, params, amt_msat));
8510 // Because we've changed channel scores, it's possible we'll take different routes to the
8511 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
8512 // requires a too-high CLTV delta.
8513 route_endpoints.retain(|(first_hop, params, amt_msat)| {
8514 let route_params = RouteParameters::from_payment_params_and_value(
8515 params.clone(), *amt_msat);
8516 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8517 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
8519 route_endpoints.truncate(route_count);
8520 assert_eq!(route_endpoints.len(), route_count);
8528 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8529 use crate::sign::{EntropySource, KeysManager};
8530 use crate::ln::channelmanager;
8531 use crate::ln::features::Bolt11InvoiceFeatures;
8532 use crate::routing::gossip::NetworkGraph;
8533 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
8534 use crate::util::config::UserConfig;
8535 use crate::util::logger::{Logger, Record};
8536 use crate::util::test_utils::TestLogger;
8538 use criterion::Criterion;
8540 struct DummyLogger {}
8541 impl Logger for DummyLogger {
8542 fn log(&self, _record: Record) {}
8545 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8546 let logger = TestLogger::new();
8547 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8548 let scorer = FixedPenaltyScorer::with_penalty(0);
8549 generate_routes(bench, &network_graph, scorer, &Default::default(),
8550 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8553 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8554 let logger = TestLogger::new();
8555 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8556 let scorer = FixedPenaltyScorer::with_penalty(0);
8557 generate_routes(bench, &network_graph, scorer, &Default::default(),
8558 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8559 "generate_mpp_routes_with_zero_penalty_scorer");
8562 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8563 let logger = TestLogger::new();
8564 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8565 let params = ProbabilisticScoringFeeParameters::default();
8566 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8567 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8568 "generate_routes_with_probabilistic_scorer");
8571 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8572 let logger = TestLogger::new();
8573 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8574 let params = ProbabilisticScoringFeeParameters::default();
8575 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8576 generate_routes(bench, &network_graph, scorer, ¶ms,
8577 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8578 "generate_mpp_routes_with_probabilistic_scorer");
8581 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8582 let logger = TestLogger::new();
8583 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8584 let params = ProbabilisticScoringFeeParameters::default();
8585 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8586 generate_routes(bench, &network_graph, scorer, ¶ms,
8587 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8588 "generate_large_mpp_routes_with_probabilistic_scorer");
8591 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8592 let logger = TestLogger::new();
8593 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8594 let mut params = ProbabilisticScoringFeeParameters::default();
8595 params.linear_success_probability = false;
8596 let scorer = ProbabilisticScorer::new(
8597 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8598 generate_routes(bench, &network_graph, scorer, ¶ms,
8599 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8600 "generate_routes_with_nonlinear_probabilistic_scorer");
8603 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8604 let logger = TestLogger::new();
8605 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8606 let mut params = ProbabilisticScoringFeeParameters::default();
8607 params.linear_success_probability = false;
8608 let scorer = ProbabilisticScorer::new(
8609 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8610 generate_routes(bench, &network_graph, scorer, ¶ms,
8611 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8612 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8615 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8616 let logger = TestLogger::new();
8617 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8618 let mut params = ProbabilisticScoringFeeParameters::default();
8619 params.linear_success_probability = false;
8620 let scorer = ProbabilisticScorer::new(
8621 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8622 generate_routes(bench, &network_graph, scorer, ¶ms,
8623 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8624 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8627 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8628 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8629 score_params: &crate::routing::scoring::ProbabilisticScoringFeeParameters, features: Bolt11InvoiceFeatures, starting_amount: u64,
8630 bench_name: &'static str,
8632 let payer = bench_utils::payer_pubkey();
8633 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8634 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8636 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8637 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8639 // ...then benchmark finding paths between the nodes we learned.
8641 bench.bench_function(bench_name, |b| b.iter(|| {
8642 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8643 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8644 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8645 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());