1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The router finds paths within a [`NetworkGraph`] for a payment.
12 use bitcoin::secp256k1::{PublicKey, Secp256k1, self};
14 use crate::blinded_path::{BlindedHop, BlindedPath, Direction, IntroductionNode};
15 use crate::blinded_path::message;
16 use crate::blinded_path::payment::{ForwardTlvs, PaymentConstraints, PaymentRelay, ReceiveTlvs, self};
17 use crate::ln::{PaymentHash, PaymentPreimage};
18 use crate::ln::channel_state::ChannelDetails;
19 use crate::ln::channelmanager::{PaymentId, MIN_FINAL_CLTV_EXPIRY_DELTA, RecipientOnionFields};
20 use crate::ln::features::{BlindedHopFeatures, Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
21 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
22 use crate::ln::onion_utils;
23 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice};
24 use crate::onion_message::messenger::{DefaultMessageRouter, Destination, MessageRouter, OnionMessagePath};
25 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
26 use crate::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp};
27 use crate::sign::EntropySource;
28 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
29 use crate::util::logger::{Level, Logger};
30 use crate::crypto::chacha20::ChaCha20;
33 use crate::prelude::*;
34 use alloc::collections::BinaryHeap;
38 /// A [`Router`] implemented using [`find_route`].
42 /// Implements [`MessageRouter`] by delegating to [`DefaultMessageRouter`]. See those docs for
43 /// privacy implications.
44 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> where
46 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
47 ES::Target: EntropySource,
54 message_router: DefaultMessageRouter<G, L, ES>,
57 impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref + Clone, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> DefaultRouter<G, L, ES, S, SP, Sc> where
59 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
60 ES::Target: EntropySource,
62 /// Creates a new router.
63 pub fn new(network_graph: G, logger: L, entropy_source: ES, scorer: S, score_params: SP) -> Self {
64 let message_router = DefaultMessageRouter::new(network_graph.clone(), entropy_source.clone());
65 Self { network_graph, logger, entropy_source, scorer, score_params, message_router }
69 impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> Router for DefaultRouter<G, L, ES, S, SP, Sc> where
71 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
72 ES::Target: EntropySource,
77 params: &RouteParameters,
78 first_hops: Option<&[&ChannelDetails]>,
79 inflight_htlcs: InFlightHtlcs
80 ) -> Result<Route, LightningError> {
81 let random_seed_bytes = self.entropy_source.get_secure_random_bytes();
83 payer, params, &self.network_graph, first_hops, &*self.logger,
84 &ScorerAccountingForInFlightHtlcs::new(self.scorer.read_lock(), &inflight_htlcs),
90 fn create_blinded_payment_paths<
91 T: secp256k1::Signing + secp256k1::Verification
93 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
94 amount_msats: u64, secp_ctx: &Secp256k1<T>
95 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
96 // Limit the number of blinded paths that are computed.
97 const MAX_PAYMENT_PATHS: usize = 3;
99 // Ensure peers have at least three channels so that it is more difficult to infer the
100 // recipient's node_id.
101 const MIN_PEER_CHANNELS: usize = 3;
103 let has_one_peer = first_hops
105 .map(|details| details.counterparty.node_id)
106 .map(|node_id| first_hops
109 .all(|details| details.counterparty.node_id == node_id)
113 let network_graph = self.network_graph.deref().read_only();
114 let is_recipient_announced =
115 network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient));
117 let paths = first_hops.into_iter()
118 .filter(|details| details.counterparty.features.supports_route_blinding())
119 .filter(|details| amount_msats <= details.inbound_capacity_msat)
120 .filter(|details| amount_msats >= details.inbound_htlc_minimum_msat.unwrap_or(0))
121 .filter(|details| amount_msats <= details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX))
122 // Limit to peers with announced channels unless the recipient is unannounced.
123 .filter(|details| network_graph
124 .node(&NodeId::from_pubkey(&details.counterparty.node_id))
125 .map(|node| !is_recipient_announced || node.channels.len() >= MIN_PEER_CHANNELS)
126 // Allow payments directly with the only peer when unannounced.
127 .unwrap_or(!is_recipient_announced && has_one_peer)
129 .filter_map(|details| {
130 let short_channel_id = match details.get_inbound_payment_scid() {
131 Some(short_channel_id) => short_channel_id,
134 let payment_relay: PaymentRelay = match details.counterparty.forwarding_info {
135 Some(forwarding_info) => match forwarding_info.try_into() {
136 Ok(payment_relay) => payment_relay,
137 Err(()) => return None,
142 let cltv_expiry_delta = payment_relay.cltv_expiry_delta as u32;
143 let payment_constraints = PaymentConstraints {
144 max_cltv_expiry: tlvs.payment_constraints.max_cltv_expiry + cltv_expiry_delta,
145 htlc_minimum_msat: details.inbound_htlc_minimum_msat.unwrap_or(0),
147 Some(payment::ForwardNode {
152 features: BlindedHopFeatures::empty(),
154 node_id: details.counterparty.node_id,
155 htlc_maximum_msat: details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX),
158 .map(|forward_node| {
159 BlindedPath::new_for_payment(
160 &[forward_node], recipient, tlvs.clone(), u64::MAX, MIN_FINAL_CLTV_EXPIRY_DELTA,
161 &*self.entropy_source, secp_ctx
164 .take(MAX_PAYMENT_PATHS)
165 .collect::<Result<Vec<_>, _>>();
168 Ok(paths) if !paths.is_empty() => Ok(paths),
170 if network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient)) {
171 BlindedPath::one_hop_for_payment(
172 recipient, tlvs, MIN_FINAL_CLTV_EXPIRY_DELTA, &*self.entropy_source, secp_ctx
173 ).map(|path| vec![path])
182 impl< G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> MessageRouter for DefaultRouter<G, L, ES, S, SP, Sc> where
184 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
185 ES::Target: EntropySource,
188 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
189 ) -> Result<OnionMessagePath, ()> {
190 self.message_router.find_path(sender, peers, destination)
193 fn create_blinded_paths<
194 T: secp256k1::Signing + secp256k1::Verification
196 &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
197 ) -> Result<Vec<BlindedPath>, ()> {
198 self.message_router.create_blinded_paths(recipient, peers, secp_ctx)
201 fn create_compact_blinded_paths<
202 T: secp256k1::Signing + secp256k1::Verification
204 &self, recipient: PublicKey, peers: Vec<message::ForwardNode>, secp_ctx: &Secp256k1<T>,
205 ) -> Result<Vec<BlindedPath>, ()> {
206 self.message_router.create_compact_blinded_paths(recipient, peers, secp_ctx)
210 /// A trait defining behavior for routing a payment.
211 pub trait Router: MessageRouter {
212 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
214 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
215 /// and [`RouteParameters::final_value_msat`], respectively.
217 &self, payer: &PublicKey, route_params: &RouteParameters,
218 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
219 ) -> Result<Route, LightningError>;
221 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
223 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
224 /// and [`RouteParameters::final_value_msat`], respectively.
226 /// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
228 fn find_route_with_id(
229 &self, payer: &PublicKey, route_params: &RouteParameters,
230 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
231 _payment_hash: PaymentHash, _payment_id: PaymentId
232 ) -> Result<Route, LightningError> {
233 self.find_route(payer, route_params, first_hops, inflight_htlcs)
236 /// Creates [`BlindedPath`]s for payment to the `recipient` node. The channels in `first_hops`
237 /// are assumed to be with the `recipient`'s peers. The payment secret and any constraints are
239 fn create_blinded_payment_paths<
240 T: secp256k1::Signing + secp256k1::Verification
242 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
243 amount_msats: u64, secp_ctx: &Secp256k1<T>
244 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()>;
247 /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
249 /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
252 /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
253 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> where S::Target: ScoreLookUp {
255 // Maps a channel's short channel id and its direction to the liquidity used up.
256 inflight_htlcs: &'a InFlightHtlcs,
258 impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
259 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
260 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
261 ScorerAccountingForInFlightHtlcs {
268 impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
269 type ScoreParams = <S::Target as ScoreLookUp>::ScoreParams;
270 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
271 let target = match candidate.target() {
272 Some(target) => target,
273 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
275 let short_channel_id = match candidate.short_channel_id() {
276 Some(short_channel_id) => short_channel_id,
277 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
279 let source = candidate.source();
280 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
281 &source, &target, short_channel_id
283 let usage = ChannelUsage {
284 inflight_htlc_msat: usage.inflight_htlc_msat.saturating_add(used_liquidity),
288 self.scorer.channel_penalty_msat(candidate, usage, score_params)
290 self.scorer.channel_penalty_msat(candidate, usage, score_params)
295 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
296 /// in-use channel liquidity.
298 pub struct InFlightHtlcs(
299 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
300 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
301 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
303 HashMap<(u64, bool), u64>
307 /// Constructs an empty `InFlightHtlcs`.
308 pub fn new() -> Self { InFlightHtlcs(new_hash_map()) }
310 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
311 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
312 if path.hops.is_empty() { return };
314 let mut cumulative_msat = 0;
315 if let Some(tail) = &path.blinded_tail {
316 cumulative_msat += tail.final_value_msat;
319 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
320 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
321 // the router excludes the payer node. In the following lines, the payer's information is
322 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
323 // in our sliding window of two.
324 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
325 .map(|hop| hop.pubkey)
326 .chain(core::iter::once(payer_node_id));
328 // Taking the reversed vector from above, we zip it with just the reversed hops list to
329 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
330 // the total amount sent.
331 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
332 cumulative_msat += next_hop.fee_msat;
334 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
335 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
336 .or_insert(cumulative_msat);
340 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
342 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
344 .entry((channel_scid, source < target))
345 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
346 .or_insert(used_msat);
349 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
351 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
352 self.0.get(&(channel_scid, source < target)).map(|v| *v)
356 impl Writeable for InFlightHtlcs {
357 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
360 impl Readable for InFlightHtlcs {
361 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
362 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
363 Ok(Self(infight_map))
367 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
368 /// that leads to it.
369 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
370 pub struct RouteHop {
371 /// The node_id of the node at this hop.
372 pub pubkey: PublicKey,
373 /// The node_announcement features of the node at this hop. For the last hop, these may be
374 /// amended to match the features present in the invoice this node generated.
375 pub node_features: NodeFeatures,
376 /// The channel that should be used from the previous hop to reach this node.
377 pub short_channel_id: u64,
378 /// The channel_announcement features of the channel that should be used from the previous hop
379 /// to reach this node.
380 pub channel_features: ChannelFeatures,
381 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
382 /// If this is the last hop in [`Path::hops`]:
383 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
384 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
386 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
388 /// The CLTV delta added for this hop.
389 /// If this is the last hop in [`Path::hops`]:
390 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
391 /// * otherwise, this is the CLTV delta expected at the destination
393 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
394 pub cltv_expiry_delta: u32,
395 /// Indicates whether this hop is possibly announced in the public network graph.
397 /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
398 /// either know for sure it's announced in the public graph, or if any public channels exist
399 /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
400 /// the channel to be unannounced.
402 /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
403 pub maybe_announced_channel: bool,
406 impl_writeable_tlv_based!(RouteHop, {
407 (0, pubkey, required),
408 (1, maybe_announced_channel, (default_value, true)),
409 (2, node_features, required),
410 (4, short_channel_id, required),
411 (6, channel_features, required),
412 (8, fee_msat, required),
413 (10, cltv_expiry_delta, required),
416 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
417 /// their [`Bolt12Invoice`].
419 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
420 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
421 pub struct BlindedTail {
422 /// The hops of the [`BlindedPath`] provided by the recipient.
424 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
425 pub hops: Vec<BlindedHop>,
426 /// The blinding point of the [`BlindedPath`] provided by the recipient.
428 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
429 pub blinding_point: PublicKey,
430 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
431 /// inferring the destination. May be 0.
432 pub excess_final_cltv_expiry_delta: u32,
433 /// The total amount paid on this [`Path`], excluding the fees.
434 pub final_value_msat: u64,
437 impl_writeable_tlv_based!(BlindedTail, {
438 (0, hops, required_vec),
439 (2, blinding_point, required),
440 (4, excess_final_cltv_expiry_delta, required),
441 (6, final_value_msat, required),
444 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
445 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
446 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
448 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
449 pub hops: Vec<RouteHop>,
450 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
451 pub blinded_tail: Option<BlindedTail>,
455 /// Gets the fees for a given path, excluding any excess paid to the recipient.
456 pub fn fee_msat(&self) -> u64 {
457 match &self.blinded_tail {
458 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
460 // Do not count last hop of each path since that's the full value of the payment
461 self.hops.split_last().map_or(0,
462 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
467 /// Gets the total amount paid on this [`Path`], excluding the fees.
468 pub fn final_value_msat(&self) -> u64 {
469 match &self.blinded_tail {
470 Some(blinded_tail) => blinded_tail.final_value_msat,
471 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
475 /// Gets the final hop's CLTV expiry delta.
476 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
477 match &self.blinded_tail {
479 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
484 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
485 /// it can take multiple paths. Each path is composed of one or more hops through the network.
486 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
488 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
489 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
491 pub paths: Vec<Path>,
492 /// The `route_params` parameter passed to [`find_route`].
494 /// This is used by `ChannelManager` to track information which may be required for retries.
496 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
497 pub route_params: Option<RouteParameters>,
501 /// Returns the total amount of fees paid on this [`Route`].
503 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
504 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
505 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
507 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
508 pub fn get_total_fees(&self) -> u64 {
509 let overpaid_value_msat = self.route_params.as_ref()
510 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
511 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
514 /// Returns the total amount paid on this [`Route`], excluding the fees.
516 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
517 /// we had to reach the [`htlc_minimum_msat`] limits.
519 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
520 pub fn get_total_amount(&self) -> u64 {
521 self.paths.iter().map(|path| path.final_value_msat()).sum()
525 impl fmt::Display for Route {
526 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
527 log_route!(self).fmt(f)
531 const SERIALIZATION_VERSION: u8 = 1;
532 const MIN_SERIALIZATION_VERSION: u8 = 1;
534 impl Writeable for Route {
535 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
536 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
537 (self.paths.len() as u64).write(writer)?;
538 let mut blinded_tails = Vec::new();
539 for (idx, path) in self.paths.iter().enumerate() {
540 (path.hops.len() as u8).write(writer)?;
541 for hop in path.hops.iter() {
544 if let Some(blinded_tail) = &path.blinded_tail {
545 if blinded_tails.is_empty() {
546 blinded_tails = Vec::with_capacity(path.hops.len());
548 blinded_tails.push(None);
551 blinded_tails.push(Some(blinded_tail));
552 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
554 write_tlv_fields!(writer, {
555 // For compatibility with LDK versions prior to 0.0.117, we take the individual
556 // RouteParameters' fields and reconstruct them on read.
557 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
558 (2, blinded_tails, optional_vec),
559 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
560 (5, self.route_params.as_ref().and_then(|p| p.max_total_routing_fee_msat), option),
566 impl Readable for Route {
567 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
568 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
569 let path_count: u64 = Readable::read(reader)?;
570 if path_count == 0 { return Err(DecodeError::InvalidValue); }
571 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
572 let mut min_final_cltv_expiry_delta = u32::max_value();
573 for _ in 0..path_count {
574 let hop_count: u8 = Readable::read(reader)?;
575 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
576 for _ in 0..hop_count {
577 hops.push(Readable::read(reader)?);
579 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
580 min_final_cltv_expiry_delta =
581 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
582 paths.push(Path { hops, blinded_tail: None });
584 _init_and_read_len_prefixed_tlv_fields!(reader, {
585 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
586 (2, blinded_tails, optional_vec),
587 (3, final_value_msat, option),
588 (5, max_total_routing_fee_msat, option)
590 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
591 if blinded_tails.len() != 0 {
592 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
593 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
594 path.blinded_tail = blinded_tail_opt;
598 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
599 let route_params = match (payment_params, final_value_msat) {
600 (Some(payment_params), Some(final_value_msat)) => {
601 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
606 Ok(Route { paths, route_params })
610 /// Parameters needed to find a [`Route`].
612 /// Passed to [`find_route`] and [`build_route_from_hops`].
613 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
614 pub struct RouteParameters {
615 /// The parameters of the failed payment path.
616 pub payment_params: PaymentParameters,
618 /// The amount in msats sent on the failed payment path.
619 pub final_value_msat: u64,
621 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
623 /// This limit also applies to the total fees that may arise while retrying failed payment
626 /// Note that values below a few sats may result in some paths being spuriously ignored.
627 pub max_total_routing_fee_msat: Option<u64>,
630 impl RouteParameters {
631 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
633 /// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
634 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
635 Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
638 /// Sets the maximum number of hops that can be included in a payment path, based on the provided
639 /// [`RecipientOnionFields`] and blinded paths.
640 pub fn set_max_path_length(
641 &mut self, recipient_onion: &RecipientOnionFields, is_keysend: bool, best_block_height: u32
642 ) -> Result<(), ()> {
643 let keysend_preimage_opt = is_keysend.then(|| PaymentPreimage([42; 32]));
644 onion_utils::set_max_path_length(
645 self, recipient_onion, keysend_preimage_opt, best_block_height
650 impl Writeable for RouteParameters {
651 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
652 write_tlv_fields!(writer, {
653 (0, self.payment_params, required),
654 (1, self.max_total_routing_fee_msat, option),
655 (2, self.final_value_msat, required),
656 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
657 // `RouteParameters` directly. For compatibility, we write it here.
658 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
664 impl Readable for RouteParameters {
665 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
666 _init_and_read_len_prefixed_tlv_fields!(reader, {
667 (0, payment_params, (required: ReadableArgs, 0)),
668 (1, max_total_routing_fee_msat, option),
669 (2, final_value_msat, required),
670 (4, final_cltv_delta, option),
672 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
673 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
674 if final_cltv_expiry_delta == &0 {
675 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
680 final_value_msat: final_value_msat.0.unwrap(),
681 max_total_routing_fee_msat,
686 /// Maximum total CTLV difference we allow for a full payment path.
687 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
689 /// Maximum number of paths we allow an (MPP) payment to have.
690 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
691 // limits, but for now more than 10 paths likely carries too much one-path failure.
692 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
694 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
696 // The median hop CLTV expiry delta currently seen in the network.
697 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
699 /// Estimated maximum number of hops that can be included in a payment path. May be inaccurate if
700 /// payment metadata, custom TLVs, or blinded paths are included in the payment.
701 // During routing, we only consider paths shorter than our maximum length estimate.
702 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
703 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
704 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
706 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
707 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
708 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
709 // (payment_secret and total_msat) = 93 bytes for the final hop.
710 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
711 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
712 pub const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
714 /// Information used to route a payment.
715 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
716 pub struct PaymentParameters {
717 /// Information about the payee, such as their features and route hints for their channels.
720 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
721 pub expiry_time: Option<u64>,
723 /// The maximum total CLTV delta we accept for the route.
724 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
725 pub max_total_cltv_expiry_delta: u32,
727 /// The maximum number of paths that may be used by (MPP) payments.
728 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
729 pub max_path_count: u8,
731 /// The maximum number of [`Path::hops`] in any returned path.
732 /// Defaults to [`MAX_PATH_LENGTH_ESTIMATE`].
733 pub max_path_length: u8,
735 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
736 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
737 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
738 /// increasing failure probability for those paths.
740 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
741 /// restriction have been found. While paths which meet this criteria will be searched for, it
742 /// is ultimately up to the scorer to select them over other paths.
744 /// A value of 0 will allow payments up to and including a channel's total announced usable
745 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
748 pub max_channel_saturation_power_of_half: u8,
750 /// A list of SCIDs which this payment was previously attempted over and which caused the
751 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
753 pub previously_failed_channels: Vec<u64>,
755 /// A list of indices corresponding to blinded paths in [`Payee::Blinded::route_hints`] which this
756 /// payment was previously attempted over and which caused the payment to fail. Future attempts
757 /// for the same payment shouldn't be relayed through any of these blinded paths.
758 pub previously_failed_blinded_path_idxs: Vec<u64>,
761 impl Writeable for PaymentParameters {
762 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
763 let mut clear_hints = &vec![];
764 let mut blinded_hints = &vec![];
766 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
767 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
769 write_tlv_fields!(writer, {
770 (0, self.payee.node_id(), option),
771 (1, self.max_total_cltv_expiry_delta, required),
772 (2, self.payee.features(), option),
773 (3, self.max_path_count, required),
774 (4, *clear_hints, required_vec),
775 (5, self.max_channel_saturation_power_of_half, required),
776 (6, self.expiry_time, option),
777 (7, self.previously_failed_channels, required_vec),
778 (8, *blinded_hints, optional_vec),
779 (9, self.payee.final_cltv_expiry_delta(), option),
780 (11, self.previously_failed_blinded_path_idxs, required_vec),
781 (13, self.max_path_length, required),
787 impl ReadableArgs<u32> for PaymentParameters {
788 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
789 _init_and_read_len_prefixed_tlv_fields!(reader, {
790 (0, payee_pubkey, option),
791 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
792 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
793 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
794 (4, clear_route_hints, required_vec),
795 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
796 (6, expiry_time, option),
797 (7, previously_failed_channels, optional_vec),
798 (8, blinded_route_hints, optional_vec),
799 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
800 (11, previously_failed_blinded_path_idxs, optional_vec),
801 (13, max_path_length, (default_value, MAX_PATH_LENGTH_ESTIMATE)),
803 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
804 let payee = if blinded_route_hints.len() != 0 {
805 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
807 route_hints: blinded_route_hints,
808 features: features.and_then(|f: Features| f.bolt12()),
812 route_hints: clear_route_hints,
813 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
814 features: features.and_then(|f| f.bolt11()),
815 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
819 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
820 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
822 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
824 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
825 previously_failed_blinded_path_idxs: previously_failed_blinded_path_idxs.unwrap_or(Vec::new()),
826 max_path_length: _init_tlv_based_struct_field!(max_path_length, (default_value, unused)),
832 impl PaymentParameters {
833 /// Creates a payee with the node id of the given `pubkey`.
835 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
837 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
839 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
841 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
842 max_path_count: DEFAULT_MAX_PATH_COUNT,
843 max_path_length: MAX_PATH_LENGTH_ESTIMATE,
844 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
845 previously_failed_channels: Vec::new(),
846 previously_failed_blinded_path_idxs: Vec::new(),
850 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
852 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
855 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
856 /// whether your router will be allowed to find a multi-part route for this payment. If you
857 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
858 /// [`RecipientOnionFields::secret_only`].
860 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
861 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
862 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
863 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
864 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
867 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
868 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
869 /// [`PaymentParameters::expiry_time`].
870 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
871 Self::blinded(invoice.payment_paths().to_vec())
872 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
873 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
876 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
877 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
879 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
881 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
882 max_path_count: DEFAULT_MAX_PATH_COUNT,
883 max_path_length: MAX_PATH_LENGTH_ESTIMATE,
884 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
885 previously_failed_channels: Vec::new(),
886 previously_failed_blinded_path_idxs: Vec::new(),
890 /// Includes the payee's features. Errors if the parameters were not initialized with
891 /// [`PaymentParameters::from_bolt12_invoice`].
893 /// This is not exported to bindings users since bindings don't support move semantics
894 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
896 Payee::Clear { .. } => Err(()),
897 Payee::Blinded { route_hints, .. } =>
898 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
902 /// Includes the payee's features. Errors if the parameters were initialized with
903 /// [`PaymentParameters::from_bolt12_invoice`].
905 /// This is not exported to bindings users since bindings don't support move semantics
906 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
908 Payee::Blinded { .. } => Err(()),
909 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
911 payee: Payee::Clear {
912 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
918 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
919 /// [`PaymentParameters::from_bolt12_invoice`].
921 /// This is not exported to bindings users since bindings don't support move semantics
922 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
924 Payee::Blinded { .. } => Err(()),
925 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
927 payee: Payee::Clear {
928 route_hints, node_id, features, final_cltv_expiry_delta,
934 /// Includes a payment expiration in seconds relative to the UNIX epoch.
936 /// This is not exported to bindings users since bindings don't support move semantics
937 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
938 Self { expiry_time: Some(expiry_time), ..self }
941 /// Includes a limit for the total CLTV expiry delta which is considered during routing
943 /// This is not exported to bindings users since bindings don't support move semantics
944 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
945 Self { max_total_cltv_expiry_delta, ..self }
948 /// Includes a limit for the maximum number of payment paths that may be used.
950 /// This is not exported to bindings users since bindings don't support move semantics
951 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
952 Self { max_path_count, ..self }
955 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
956 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
958 /// This is not exported to bindings users since bindings don't support move semantics
959 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
960 Self { max_channel_saturation_power_of_half, ..self }
963 pub(crate) fn insert_previously_failed_blinded_path(&mut self, failed_blinded_tail: &BlindedTail) {
964 let mut found_blinded_tail = false;
965 for (idx, (_, path)) in self.payee.blinded_route_hints().iter().enumerate() {
966 if failed_blinded_tail.hops == path.blinded_hops &&
967 failed_blinded_tail.blinding_point == path.blinding_point
969 self.previously_failed_blinded_path_idxs.push(idx as u64);
970 found_blinded_tail = true;
973 debug_assert!(found_blinded_tail);
977 /// The recipient of a payment, differing based on whether they've hidden their identity with route
979 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
981 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
982 /// will be included in the final [`Route`].
984 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
986 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
987 /// Features supported by the payee.
989 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
991 features: Option<Bolt12InvoiceFeatures>,
993 /// The recipient included these route hints in their BOLT11 invoice.
995 /// The node id of the payee.
997 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
998 route_hints: Vec<RouteHint>,
999 /// Features supported by the payee.
1001 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
1002 /// does not contain any features.
1004 /// [`for_keysend`]: PaymentParameters::for_keysend
1005 features: Option<Bolt11InvoiceFeatures>,
1006 /// The minimum CLTV delta at the end of the route. This value must not be zero.
1007 final_cltv_expiry_delta: u32,
1012 fn node_id(&self) -> Option<PublicKey> {
1014 Self::Clear { node_id, .. } => Some(*node_id),
1018 fn node_features(&self) -> Option<NodeFeatures> {
1020 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
1021 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
1024 fn supports_basic_mpp(&self) -> bool {
1026 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
1027 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
1030 fn features(&self) -> Option<FeaturesRef> {
1032 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
1033 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
1036 fn final_cltv_expiry_delta(&self) -> Option<u32> {
1038 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
1042 pub(crate) fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
1044 Self::Blinded { route_hints, .. } => &route_hints[..],
1045 Self::Clear { .. } => &[]
1049 pub(crate) fn blinded_route_hints_mut(&mut self) -> &mut [(BlindedPayInfo, BlindedPath)] {
1051 Self::Blinded { route_hints, .. } => &mut route_hints[..],
1052 Self::Clear { .. } => &mut []
1056 fn unblinded_route_hints(&self) -> &[RouteHint] {
1058 Self::Blinded { .. } => &[],
1059 Self::Clear { route_hints, .. } => &route_hints[..]
1064 enum FeaturesRef<'a> {
1065 Bolt11(&'a Bolt11InvoiceFeatures),
1066 Bolt12(&'a Bolt12InvoiceFeatures),
1069 Bolt11(Bolt11InvoiceFeatures),
1070 Bolt12(Bolt12InvoiceFeatures),
1074 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
1076 Self::Bolt12(f) => Some(f),
1080 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
1082 Self::Bolt11(f) => Some(f),
1088 impl<'a> Writeable for FeaturesRef<'a> {
1089 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1091 Self::Bolt11(f) => Ok(f.write(w)?),
1092 Self::Bolt12(f) => Ok(f.write(w)?),
1097 impl ReadableArgs<bool> for Features {
1098 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
1099 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
1100 Ok(Self::Bolt12(Readable::read(reader)?))
1104 /// A list of hops along a payment path terminating with a channel to the recipient.
1105 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1106 pub struct RouteHint(pub Vec<RouteHintHop>);
1108 impl Writeable for RouteHint {
1109 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1110 (self.0.len() as u64).write(writer)?;
1111 for hop in self.0.iter() {
1118 impl Readable for RouteHint {
1119 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1120 let hop_count: u64 = Readable::read(reader)?;
1121 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
1122 for _ in 0..hop_count {
1123 hops.push(Readable::read(reader)?);
1129 /// A channel descriptor for a hop along a payment path.
1131 /// While this generally comes from BOLT 11's `r` field, this struct includes more fields than are
1132 /// available in BOLT 11. Thus, encoding and decoding this via `lightning-invoice` is lossy, as
1133 /// fields not supported in BOLT 11 will be stripped.
1134 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1135 pub struct RouteHintHop {
1136 /// The node_id of the non-target end of the route
1137 pub src_node_id: PublicKey,
1138 /// The short_channel_id of this channel
1139 pub short_channel_id: u64,
1140 /// The fees which must be paid to use this channel
1141 pub fees: RoutingFees,
1142 /// The difference in CLTV values between this node and the next node.
1143 pub cltv_expiry_delta: u16,
1144 /// The minimum value, in msat, which must be relayed to the next hop.
1145 pub htlc_minimum_msat: Option<u64>,
1146 /// The maximum value in msat available for routing with a single HTLC.
1147 pub htlc_maximum_msat: Option<u64>,
1150 impl_writeable_tlv_based!(RouteHintHop, {
1151 (0, src_node_id, required),
1152 (1, htlc_minimum_msat, option),
1153 (2, short_channel_id, required),
1154 (3, htlc_maximum_msat, option),
1155 (4, fees, required),
1156 (6, cltv_expiry_delta, required),
1159 #[derive(Eq, PartialEq)]
1160 #[repr(align(64))] // Force the size to 64 bytes
1161 struct RouteGraphNode {
1164 // The maximum value a yet-to-be-constructed payment path might flow through this node.
1165 // This value is upper-bounded by us by:
1166 // - how much is needed for a path being constructed
1167 // - how much value can channels following this node (up to the destination) can contribute,
1168 // considering their capacity and fees
1169 value_contribution_msat: u64,
1170 total_cltv_delta: u32,
1171 /// The number of hops walked up to this node.
1172 path_length_to_node: u8,
1175 impl cmp::Ord for RouteGraphNode {
1176 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
1177 other.score.cmp(&self.score).then_with(|| other.node_id.cmp(&self.node_id))
1181 impl cmp::PartialOrd for RouteGraphNode {
1182 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
1183 Some(self.cmp(other))
1187 // While RouteGraphNode can be laid out with fewer bytes, performance appears to be improved
1188 // substantially when it is laid out at exactly 64 bytes.
1190 // Thus, we use `#[repr(C)]` on the struct to force a suboptimal layout and check that it stays 64
1192 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1193 const _GRAPH_NODE_SMALL: usize = 64 - core::mem::size_of::<RouteGraphNode>();
1194 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1195 const _GRAPH_NODE_FIXED_SIZE: usize = core::mem::size_of::<RouteGraphNode>() - 64;
1197 /// A [`CandidateRouteHop::FirstHop`] entry.
1198 #[derive(Clone, Debug)]
1199 pub struct FirstHopCandidate<'a> {
1200 /// Channel details of the first hop
1202 /// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1203 /// has been funded and is able to pay), and accessor methods may panic otherwise.
1205 /// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1207 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1208 pub details: &'a ChannelDetails,
1209 /// The node id of the payer, which is also the source side of this candidate route hop.
1211 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1212 pub payer_node_id: &'a NodeId,
1215 /// A [`CandidateRouteHop::PublicHop`] entry.
1216 #[derive(Clone, Debug)]
1217 pub struct PublicHopCandidate<'a> {
1218 /// Information about the channel, including potentially its capacity and
1219 /// direction-specific information.
1221 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1222 pub info: DirectedChannelInfo<'a>,
1223 /// The short channel ID of the channel, i.e. the identifier by which we refer to this
1225 pub short_channel_id: u64,
1228 /// A [`CandidateRouteHop::PrivateHop`] entry.
1229 #[derive(Clone, Debug)]
1230 pub struct PrivateHopCandidate<'a> {
1231 /// Information about the private hop communicated via BOLT 11.
1233 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1234 pub hint: &'a RouteHintHop,
1235 /// Node id of the next hop in BOLT 11 route hint.
1237 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1238 pub target_node_id: &'a NodeId
1241 /// A [`CandidateRouteHop::Blinded`] entry.
1242 #[derive(Clone, Debug)]
1243 pub struct BlindedPathCandidate<'a> {
1244 /// The node id of the introduction node, resolved from either the [`NetworkGraph`] or first
1247 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1248 pub source_node_id: &'a NodeId,
1249 /// Information about the blinded path including the fee, HTLC amount limits, and
1250 /// cryptographic material required to build an HTLC through the given path.
1252 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1253 pub hint: &'a (BlindedPayInfo, BlindedPath),
1254 /// Index of the hint in the original list of blinded hints.
1256 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1257 /// a short channel ID for this hop.
1261 /// A [`CandidateRouteHop::OneHopBlinded`] entry.
1262 #[derive(Clone, Debug)]
1263 pub struct OneHopBlindedPathCandidate<'a> {
1264 /// The node id of the introduction node, resolved from either the [`NetworkGraph`] or first
1267 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1268 pub source_node_id: &'a NodeId,
1269 /// Information about the blinded path including the fee, HTLC amount limits, and
1270 /// cryptographic material required to build an HTLC terminating with the given path.
1272 /// Note that the [`BlindedPayInfo`] is ignored here.
1274 /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1275 pub hint: &'a (BlindedPayInfo, BlindedPath),
1276 /// Index of the hint in the original list of blinded hints.
1278 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1279 /// a short channel ID for this hop.
1283 /// A wrapper around the various hop representations.
1285 /// Can be used to examine the properties of a hop,
1286 /// potentially to decide whether to include it in a route.
1287 #[derive(Clone, Debug)]
1288 pub enum CandidateRouteHop<'a> {
1289 /// A hop from the payer, where the outbound liquidity is known.
1290 FirstHop(FirstHopCandidate<'a>),
1291 /// A hop found in the [`ReadOnlyNetworkGraph`].
1292 PublicHop(PublicHopCandidate<'a>),
1293 /// A private hop communicated by the payee, generally via a BOLT 11 invoice.
1295 /// Because BOLT 11 route hints can take multiple hops to get to the destination, this may not
1296 /// terminate at the payee.
1297 PrivateHop(PrivateHopCandidate<'a>),
1298 /// A blinded path which starts with an introduction point and ultimately terminates with the
1301 /// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1302 /// `None` in this state.
1304 /// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1305 /// path, the full path is treated as a single [`CandidateRouteHop`].
1306 Blinded(BlindedPathCandidate<'a>),
1307 /// Similar to [`Self::Blinded`], but the path here only has one hop.
1309 /// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1310 /// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1311 /// payee's identity - it's the introduction point!
1313 /// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1314 /// to the hops *between* the introduction node and the destination.
1316 /// This primarily exists to track that we need to included a blinded path at the end of our
1317 /// [`Route`], even though it doesn't actually add an additional hop in the payment.
1318 OneHopBlinded(OneHopBlindedPathCandidate<'a>),
1321 impl<'a> CandidateRouteHop<'a> {
1322 /// Returns the short channel ID for this hop, if one is known.
1324 /// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1325 /// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1327 /// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1328 /// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1329 /// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1330 /// (which is always true for channels which are funded and ready for use).
1332 /// In other words, this should always return `Some` as long as the candidate hop is not a
1333 /// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1335 /// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1336 /// define a global namespace.
1338 fn short_channel_id(&self) -> Option<u64> {
1340 CandidateRouteHop::FirstHop(hop) => hop.details.get_outbound_payment_scid(),
1341 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1342 CandidateRouteHop::PrivateHop(hop) => Some(hop.hint.short_channel_id),
1343 CandidateRouteHop::Blinded(_) => None,
1344 CandidateRouteHop::OneHopBlinded(_) => None,
1348 /// Returns the globally unique short channel ID for this hop, if one is known.
1350 /// This only returns `Some` if the channel is public (either our own, or one we've learned
1351 /// from the public network graph), and thus the short channel ID we have for this channel is
1352 /// globally unique and identifies this channel in a global namespace.
1354 pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1356 CandidateRouteHop::FirstHop(hop) => if hop.details.is_public { hop.details.short_channel_id } else { None },
1357 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1358 CandidateRouteHop::PrivateHop(_) => None,
1359 CandidateRouteHop::Blinded(_) => None,
1360 CandidateRouteHop::OneHopBlinded(_) => None,
1364 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1365 fn features(&self) -> ChannelFeatures {
1367 CandidateRouteHop::FirstHop(hop) => hop.details.counterparty.features.to_context(),
1368 CandidateRouteHop::PublicHop(hop) => hop.info.channel().features.clone(),
1369 CandidateRouteHop::PrivateHop(_) => ChannelFeatures::empty(),
1370 CandidateRouteHop::Blinded(_) => ChannelFeatures::empty(),
1371 CandidateRouteHop::OneHopBlinded(_) => ChannelFeatures::empty(),
1375 /// Returns the required difference in HTLC CLTV expiry between the [`Self::source`] and the
1376 /// next-hop for an HTLC taking this hop.
1378 /// This is the time that the node(s) in this hop have to claim the HTLC on-chain if the
1379 /// next-hop goes on chain with a payment preimage.
1381 pub fn cltv_expiry_delta(&self) -> u32 {
1383 CandidateRouteHop::FirstHop(_) => 0,
1384 CandidateRouteHop::PublicHop(hop) => hop.info.direction().cltv_expiry_delta as u32,
1385 CandidateRouteHop::PrivateHop(hop) => hop.hint.cltv_expiry_delta as u32,
1386 CandidateRouteHop::Blinded(hop) => hop.hint.0.cltv_expiry_delta as u32,
1387 CandidateRouteHop::OneHopBlinded(_) => 0,
1391 /// Returns the minimum amount that can be sent over this hop, in millisatoshis.
1393 pub fn htlc_minimum_msat(&self) -> u64 {
1395 CandidateRouteHop::FirstHop(hop) => hop.details.next_outbound_htlc_minimum_msat,
1396 CandidateRouteHop::PublicHop(hop) => hop.info.direction().htlc_minimum_msat,
1397 CandidateRouteHop::PrivateHop(hop) => hop.hint.htlc_minimum_msat.unwrap_or(0),
1398 CandidateRouteHop::Blinded(hop) => hop.hint.0.htlc_minimum_msat,
1399 CandidateRouteHop::OneHopBlinded { .. } => 0,
1403 /// Returns the fees that must be paid to route an HTLC over this channel.
1405 pub fn fees(&self) -> RoutingFees {
1407 CandidateRouteHop::FirstHop(_) => RoutingFees {
1408 base_msat: 0, proportional_millionths: 0,
1410 CandidateRouteHop::PublicHop(hop) => hop.info.direction().fees,
1411 CandidateRouteHop::PrivateHop(hop) => hop.hint.fees,
1412 CandidateRouteHop::Blinded(hop) => {
1414 base_msat: hop.hint.0.fee_base_msat,
1415 proportional_millionths: hop.hint.0.fee_proportional_millionths
1418 CandidateRouteHop::OneHopBlinded(_) =>
1419 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1423 /// Fetch the effective capacity of this hop.
1425 /// Note that this may be somewhat expensive, so calls to this should be limited and results
1427 fn effective_capacity(&self) -> EffectiveCapacity {
1429 CandidateRouteHop::FirstHop(hop) => EffectiveCapacity::ExactLiquidity {
1430 liquidity_msat: hop.details.next_outbound_htlc_limit_msat,
1432 CandidateRouteHop::PublicHop(hop) => hop.info.effective_capacity(),
1433 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. }) =>
1434 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1435 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. }) =>
1436 EffectiveCapacity::Infinite,
1437 CandidateRouteHop::Blinded(hop) =>
1438 EffectiveCapacity::HintMaxHTLC { amount_msat: hop.hint.0.htlc_maximum_msat },
1439 CandidateRouteHop::OneHopBlinded(_) => EffectiveCapacity::Infinite,
1443 /// Returns an ID describing the given hop.
1445 /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1447 fn id(&self) -> CandidateHopId {
1449 CandidateRouteHop::Blinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1450 CandidateRouteHop::OneHopBlinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1451 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1454 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1456 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1462 fn blinded_hint_idx(&self) -> Option<usize> {
1464 Self::Blinded(BlindedPathCandidate { hint_idx, .. }) |
1465 Self::OneHopBlinded(OneHopBlindedPathCandidate { hint_idx, .. }) => {
1471 /// Returns the source node id of current hop.
1473 /// Source node id refers to the node forwarding the HTLC through this hop.
1475 /// For [`Self::FirstHop`] we return payer's node id.
1477 pub fn source(&self) -> NodeId {
1479 CandidateRouteHop::FirstHop(hop) => *hop.payer_node_id,
1480 CandidateRouteHop::PublicHop(hop) => *hop.info.source(),
1481 CandidateRouteHop::PrivateHop(hop) => hop.hint.src_node_id.into(),
1482 CandidateRouteHop::Blinded(hop) => *hop.source_node_id,
1483 CandidateRouteHop::OneHopBlinded(hop) => *hop.source_node_id,
1486 /// Returns the target node id of this hop, if known.
1488 /// Target node id refers to the node receiving the HTLC after this hop.
1490 /// For [`Self::Blinded`] we return `None` because the ultimate destination after the blinded
1491 /// path is unknown.
1493 /// For [`Self::OneHopBlinded`] we return `None` because the target is the same as the source,
1494 /// and such a return value would be somewhat nonsensical.
1496 pub fn target(&self) -> Option<NodeId> {
1498 CandidateRouteHop::FirstHop(hop) => Some(hop.details.counterparty.node_id.into()),
1499 CandidateRouteHop::PublicHop(hop) => Some(*hop.info.target()),
1500 CandidateRouteHop::PrivateHop(hop) => Some(*hop.target_node_id),
1501 CandidateRouteHop::Blinded(_) => None,
1502 CandidateRouteHop::OneHopBlinded(_) => None,
1507 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1509 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1511 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1512 /// isn't guaranteed to be unique at all.
1514 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1515 /// difficult-to-use API.
1516 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1517 enum CandidateHopId {
1518 /// Contains (scid, src_node_id < target_node_id)
1520 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1525 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1526 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1528 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1529 EffectiveCapacity::Infinite => u64::max_value(),
1530 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1531 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1532 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1533 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1534 // expected to have been generated from up-to-date capacity information.
1535 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1536 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1537 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1541 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1542 -> bool where I1::Item: PartialEq<I2::Item> {
1544 let a = iter_a.next();
1545 let b = iter_b.next();
1546 if a.is_none() && b.is_none() { return true; }
1547 if a.is_none() || b.is_none() { return false; }
1548 if a.unwrap().ne(&b.unwrap()) { return false; }
1552 /// It's useful to keep track of the hops associated with the fees required to use them,
1553 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1554 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1555 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1557 #[repr(C)] // Force fields to appear in the order we define them.
1558 struct PathBuildingHop<'a> {
1559 candidate: CandidateRouteHop<'a>,
1560 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1561 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1562 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1563 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1564 /// avoid processing them again.
1565 was_processed: bool,
1566 /// Used to compare channels when choosing the for routing.
1567 /// Includes paying for the use of a hop and the following hops, as well as
1568 /// an estimated cost of reaching this hop.
1569 /// Might get stale when fees are recomputed. Primarily for internal use.
1570 total_fee_msat: u64,
1571 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1572 /// walk and may be invalid thereafter.
1573 path_htlc_minimum_msat: u64,
1574 /// All penalties incurred from this channel on the way to the destination, as calculated using
1575 /// channel scoring.
1576 path_penalty_msat: u64,
1578 // The last 16 bytes are on the next cache line by default in glibc's malloc. Thus, we should
1579 // only place fields which are not hot there. Luckily, the next three fields are only read if
1580 // we end up on the selected path, and only in the final path layout phase, so we don't care
1581 // too much if reading them is slow.
1585 /// All the fees paid *after* this channel on the way to the destination
1586 next_hops_fee_msat: u64,
1587 /// Fee paid for the use of the current channel (see candidate.fees()).
1588 /// The value will be actually deducted from the counterparty balance on the previous link.
1589 hop_use_fee_msat: u64,
1591 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1592 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1593 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1594 // value_contribution_msat, which requires tracking it here. See comments below where it is
1595 // used for more info.
1596 value_contribution_msat: u64,
1599 // Checks that the entries in the `find_route` `dist` map fit in (exactly) two standard x86-64
1600 // cache lines. Sadly, they're not guaranteed to actually lie on a cache line (and in fact,
1601 // generally won't, because at least glibc's malloc will align to a nice, big, round
1602 // boundary...plus 16), but at least it will reduce the amount of data we'll need to load.
1604 // Note that these assertions only pass on somewhat recent rustc, and thus are gated on the
1607 const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::<(NodeId, PathBuildingHop)>();
1609 const _NODE_MAP_SIZE_EXACTLY_CACHE_LINES: usize = core::mem::size_of::<(NodeId, PathBuildingHop)>() - 128;
1611 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1612 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1613 let mut debug_struct = f.debug_struct("PathBuildingHop");
1615 .field("node_id", &self.candidate.target())
1616 .field("short_channel_id", &self.candidate.short_channel_id())
1617 .field("total_fee_msat", &self.total_fee_msat)
1618 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1619 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1620 .field("total_fee_msat - (next_hops_fee_msat + hop_use_fee_msat)", &(&self.total_fee_msat - (&self.next_hops_fee_msat + &self.hop_use_fee_msat)))
1621 .field("path_penalty_msat", &self.path_penalty_msat)
1622 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1623 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1624 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1625 let debug_struct = debug_struct
1626 .field("value_contribution_msat", &self.value_contribution_msat);
1627 debug_struct.finish()
1631 // Instantiated with a list of hops with correct data in them collected during path finding,
1632 // an instance of this struct should be further modified only via given methods.
1634 struct PaymentPath<'a> {
1635 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1638 impl<'a> PaymentPath<'a> {
1639 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1640 fn get_value_msat(&self) -> u64 {
1641 self.hops.last().unwrap().0.fee_msat
1644 fn get_path_penalty_msat(&self) -> u64 {
1645 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1648 fn get_total_fee_paid_msat(&self) -> u64 {
1649 if self.hops.len() < 1 {
1653 // Can't use next_hops_fee_msat because it gets outdated.
1654 for (i, (hop, _)) in self.hops.iter().enumerate() {
1655 if i != self.hops.len() - 1 {
1656 result += hop.fee_msat;
1662 fn get_cost_msat(&self) -> u64 {
1663 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1666 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1667 // to change fees may result in an inconsistency.
1669 // Sometimes we call this function right after constructing a path which is inconsistent in
1670 // that it the value being transferred has decreased while we were doing path finding, leading
1671 // to the fees being paid not lining up with the actual limits.
1673 // Note that this function is not aware of the available_liquidity limit, and thus does not
1674 // support increasing the value being transferred beyond what was selected during the initial
1677 // Returns the amount that this path contributes to the total payment value, which may be greater
1678 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1679 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1680 let mut extra_contribution_msat = 0;
1681 let mut total_fee_paid_msat = 0 as u64;
1682 for i in (0..self.hops.len()).rev() {
1683 let last_hop = i == self.hops.len() - 1;
1685 // For non-last-hop, this value will represent the fees paid on the current hop. It
1686 // will consist of the fees for the use of the next hop, and extra fees to match
1687 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1688 let mut cur_hop_fees_msat = 0;
1690 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1693 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1694 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1695 cur_hop.path_penalty_msat += extra_contribution_msat;
1696 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1697 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1698 // set it too high just to maliciously take more fees by exploiting this
1699 // match htlc_minimum_msat logic.
1700 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1701 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1702 // Note that there is a risk that *previous hops* (those closer to us, as we go
1703 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1705 // This might make us end up with a broken route, although this should be super-rare
1706 // in practice, both because of how healthy channels look like, and how we pick
1707 // channels in add_entry.
1708 // Also, this can't be exploited more heavily than *announce a free path and fail
1710 cur_hop_transferred_amount_msat += extra_fees_msat;
1712 // We remember and return the extra fees on the final hop to allow accounting for
1713 // them in the path's value contribution.
1715 extra_contribution_msat = extra_fees_msat;
1717 total_fee_paid_msat += extra_fees_msat;
1718 cur_hop_fees_msat += extra_fees_msat;
1723 // Final hop is a special case: it usually has just value_msat (by design), but also
1724 // it still could overpay for the htlc_minimum_msat.
1725 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1727 // Propagate updated fees for the use of the channels to one hop back, where they
1728 // will be actually paid (fee_msat). The last hop is handled above separately.
1729 cur_hop.fee_msat = cur_hop_fees_msat;
1732 // Fee for the use of the current hop which will be deducted on the previous hop.
1733 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1734 // this channel is free for us.
1736 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1737 cur_hop.hop_use_fee_msat = new_fee;
1738 total_fee_paid_msat += new_fee;
1740 // It should not be possible because this function is called only to reduce the
1741 // value. In that case, compute_fee was already called with the same fees for
1742 // larger amount and there was no overflow.
1747 value_msat + extra_contribution_msat
1752 /// Calculate the fees required to route the given amount over a channel with the given fees.
1753 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1754 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1755 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1759 /// Calculate the fees required to route the given amount over a channel with the given fees,
1760 /// saturating to [`u64::max_value`].
1761 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1762 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1763 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1764 .saturating_add(channel_fees.base_msat as u64)
1767 /// The default `features` we assume for a node in a route, when no `features` are known about that
1770 /// Default features are:
1771 /// * variable_length_onion_optional
1772 fn default_node_features() -> NodeFeatures {
1773 let mut features = NodeFeatures::empty();
1774 features.set_variable_length_onion_optional();
1778 struct LoggedPayeePubkey(Option<PublicKey>);
1779 impl fmt::Display for LoggedPayeePubkey {
1780 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1783 "payee node id ".fmt(f)?;
1787 "blinded payee".fmt(f)
1793 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1794 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1795 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1797 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1798 "blinded route hint with introduction node ".fmt(f)?;
1799 match &hint.1.introduction_node {
1800 IntroductionNode::NodeId(pubkey) => write!(f, "id {}", pubkey)?,
1801 IntroductionNode::DirectedShortChannelId(direction, scid) => {
1803 Direction::NodeOne => {
1804 write!(f, "one on channel with SCID {}", scid)?;
1806 Direction::NodeTwo => {
1807 write!(f, "two on channel with SCID {}", scid)?;
1812 " and blinding point ".fmt(f)?;
1813 hint.1.blinding_point.fmt(f)
1815 CandidateRouteHop::FirstHop(_) => {
1816 "first hop with SCID ".fmt(f)?;
1817 self.0.short_channel_id().unwrap().fmt(f)
1819 CandidateRouteHop::PrivateHop(_) => {
1820 "route hint with SCID ".fmt(f)?;
1821 self.0.short_channel_id().unwrap().fmt(f)
1825 self.0.short_channel_id().unwrap().fmt(f)
1832 fn sort_first_hop_channels(
1833 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1834 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1836 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1837 // most like to use.
1839 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1840 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1843 // Second, because simply always sorting in descending order would always use our largest
1844 // available outbound capacity, needlessly fragmenting our available channel capacities,
1845 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1846 // which have enough, but not too much, capacity for the payment.
1848 // Available outbound balances factor in liquidity already reserved for previously found paths.
1849 channels.sort_unstable_by(|chan_a, chan_b| {
1850 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1851 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1852 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1853 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1854 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1855 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1856 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1857 // Sort in descending order
1858 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1860 // Sort in ascending order
1861 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1866 /// Finds a route from us (payer) to the given target node (payee).
1868 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1869 /// in the given [`RouteParameters::payment_params`].
1870 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1872 /// Private routing paths between a public node and the target may be included in the `payee` field
1873 /// of [`RouteParameters::payment_params`].
1875 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1876 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1877 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1879 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1880 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1881 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1885 /// Panics if first_hops contains channels without `short_channel_id`s;
1886 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1888 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1889 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1890 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1891 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1892 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1893 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1894 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1895 ) -> Result<Route, LightningError>
1896 where L::Target: Logger, GL::Target: Logger {
1897 let graph_lock = network_graph.read_only();
1898 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1899 scorer, score_params, random_seed_bytes)?;
1900 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1904 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1905 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1906 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1907 _random_seed_bytes: &[u8; 32]
1908 ) -> Result<Route, LightningError>
1909 where L::Target: Logger {
1911 let payment_params = &route_params.payment_params;
1912 let max_path_length = core::cmp::min(payment_params.max_path_length, MAX_PATH_LENGTH_ESTIMATE);
1913 let final_value_msat = route_params.final_value_msat;
1914 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1915 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1916 // so use a dummy id for this in the blinded case.
1917 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1918 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1919 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1920 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1921 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1923 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1924 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1926 if our_node_id == maybe_dummy_payee_node_id {
1927 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1930 if final_value_msat > MAX_VALUE_MSAT {
1931 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1934 if final_value_msat == 0 {
1935 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1938 let introduction_node_id_cache = payment_params.payee.blinded_route_hints().iter()
1939 .map(|(_, path)| path.public_introduction_node_id(network_graph))
1940 .collect::<Vec<_>>();
1941 match &payment_params.payee {
1942 Payee::Clear { route_hints, node_id, .. } => {
1943 for route in route_hints.iter() {
1944 for hop in &route.0 {
1945 if hop.src_node_id == *node_id {
1946 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1951 Payee::Blinded { route_hints, .. } => {
1952 if introduction_node_id_cache.iter().all(|introduction_node_id| *introduction_node_id == Some(&our_node_id)) {
1953 return Err(LightningError{err: "Cannot generate a route to blinded paths if we are the introduction node to all of them".to_owned(), action: ErrorAction::IgnoreError});
1955 for ((_, blinded_path), introduction_node_id) in route_hints.iter().zip(introduction_node_id_cache.iter()) {
1956 if blinded_path.blinded_hops.len() == 0 {
1957 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1958 } else if *introduction_node_id == Some(&our_node_id) {
1959 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1960 } else if blinded_path.blinded_hops.len() == 1 &&
1962 .iter().zip(introduction_node_id_cache.iter())
1963 .filter(|((_, p), _)| p.blinded_hops.len() == 1)
1964 .any(|(_, p_introduction_node_id)| p_introduction_node_id != introduction_node_id)
1966 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1971 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1972 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1973 return Err(LightningError{err: "Can't find a route where the maximum total CLTV expiry delta is below the final CLTV expiry.".to_owned(), action: ErrorAction::IgnoreError});
1976 // The general routing idea is the following:
1977 // 1. Fill first/last hops communicated by the caller.
1978 // 2. Attempt to construct a path from payer to payee for transferring
1979 // any ~sufficient (described later) value.
1980 // If succeed, remember which channels were used and how much liquidity they have available,
1981 // so that future paths don't rely on the same liquidity.
1982 // 3. Proceed to the next step if:
1983 // - we hit the recommended target value;
1984 // - OR if we could not construct a new path. Any next attempt will fail too.
1985 // Otherwise, repeat step 2.
1986 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1987 // (not recommended value).
1988 // 5. If yes, proceed. If not, fail routing.
1989 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1990 // transferred up to the transfer target value.
1991 // 7. Reduce the value of the last path until we are sending only the target value.
1992 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1993 // them so that we're not sending two HTLCs along the same path.
1995 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1996 // distance from the payee
1998 // We are not a faithful Dijkstra's implementation because we can change values which impact
1999 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
2000 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
2001 // the value we are currently attempting to send over a path, we simply reduce the value being
2002 // sent along the path for any hops after that channel. This may imply that later fees (which
2003 // we've already tabulated) are lower because a smaller value is passing through the channels
2004 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
2005 // channels which were selected earlier (and which may still be used for other paths without a
2006 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
2009 // One potentially problematic case for this algorithm would be if there are many
2010 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
2011 // graph walking), we may never find a path which is not liquidity-limited and has lower
2012 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
2013 // Because we only consider paths with at least 5% of the total value being sent, the damage
2014 // from such a case should be limited, however this could be further reduced in the future by
2015 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
2016 // limits for the purposes of fee calculation.
2018 // Alternatively, we could store more detailed path information in the heap (targets, below)
2019 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
2020 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
2021 // and practically (as we would need to store dynamically-allocated path information in heap
2022 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
2023 // results of such an algorithm would likely be biased towards lower-value paths.
2025 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
2026 // outside of our current search value, running a path search more times to gather candidate
2027 // paths at different values. While this may be acceptable, further path searches may increase
2028 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
2029 // graph for candidate paths, calculating the maximum value which can realistically be sent at
2030 // the same time, remaining generic across different payment values.
2032 let network_channels = network_graph.channels();
2033 let network_nodes = network_graph.nodes();
2035 if payment_params.max_path_count == 0 {
2036 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
2039 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
2040 // it. If the payee supports it they're supposed to include it in the invoice, so that should
2042 let allow_mpp = if payment_params.max_path_count == 1 {
2044 } else if payment_params.payee.supports_basic_mpp() {
2046 } else if let Some(payee) = payee_node_id_opt {
2047 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
2048 |info| info.features().supports_basic_mpp()))
2051 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
2053 let first_hop_count = first_hops.map(|hops| hops.len()).unwrap_or(0);
2054 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph of {} nodes and {} channels with a fee limit of {} msat",
2055 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
2056 if allow_mpp { "with" } else { "without" },
2057 first_hop_count, if first_hops.is_some() { "" } else { "not " },
2058 network_graph.nodes().len(), network_graph.channels().len(),
2059 max_total_routing_fee_msat);
2061 if first_hop_count < 10 {
2062 if let Some(hops) = first_hops {
2066 " First hop through {}/{} can send between {}msat and {}msat (inclusive).",
2067 hop.counterparty.node_id,
2068 hop.get_outbound_payment_scid().unwrap_or(0),
2069 hop.next_outbound_htlc_minimum_msat,
2070 hop.next_outbound_htlc_limit_msat
2077 // Prepare the data we'll use for payee-to-payer search by
2078 // inserting first hops suggested by the caller as targets.
2079 // Our search will then attempt to reach them while traversing from the payee node.
2080 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
2081 hash_map_with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
2082 if let Some(hops) = first_hops {
2084 if chan.get_outbound_payment_scid().is_none() {
2085 panic!("first_hops should be filled in with usable channels, not pending ones");
2087 if chan.counterparty.node_id == *our_node_pubkey {
2088 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
2091 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
2092 .or_insert(Vec::new())
2095 if first_hop_targets.is_empty() {
2096 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
2100 let mut private_hop_key_cache = hash_map_with_capacity(
2101 payment_params.payee.unblinded_route_hints().iter().map(|path| path.0.len()).sum()
2104 // Because we store references to private hop node_ids in `dist`, below, we need them to exist
2105 // (as `NodeId`, not `PublicKey`) for the lifetime of `dist`. Thus, we calculate all the keys
2106 // we'll need here and simply fetch them when routing.
2107 private_hop_key_cache.insert(maybe_dummy_payee_pk, NodeId::from_pubkey(&maybe_dummy_payee_pk));
2108 for route in payment_params.payee.unblinded_route_hints().iter() {
2109 for hop in route.0.iter() {
2110 private_hop_key_cache.insert(hop.src_node_id, NodeId::from_pubkey(&hop.src_node_id));
2114 // The main heap containing all candidate next-hops sorted by their score (max(fee,
2115 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
2116 // adding duplicate entries when we find a better path to a given node.
2117 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
2119 // Map from node_id to information about the best current path to that node, including feerate
2121 let mut dist: HashMap<NodeId, PathBuildingHop> = hash_map_with_capacity(network_nodes.len());
2123 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
2124 // indicating that we may wish to try again with a higher value, potentially paying to meet an
2125 // htlc_minimum with extra fees while still finding a cheaper path.
2126 let mut hit_minimum_limit;
2128 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
2129 // We start with a path_value of the exact amount we want, and if that generates a route we may
2130 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
2131 // amount we want in total across paths, selecting the best subset at the end.
2132 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
2133 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
2134 let mut path_value_msat = final_value_msat;
2136 // Routing Fragmentation Mitigation heuristic:
2138 // Routing fragmentation across many payment paths increases the overall routing
2139 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
2140 // Taking too many smaller paths also increases the chance of payment failure.
2141 // Thus to avoid this effect, we require from our collected links to provide
2142 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
2143 // This requirement is currently set to be 1/max_path_count of the payment
2144 // value to ensure we only ever return routes that do not violate this limit.
2145 let minimal_value_contribution_msat: u64 = if allow_mpp {
2146 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
2151 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
2152 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
2153 // drop the requirement by setting this to 0.
2154 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
2156 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
2157 // determine if the channel can be used by additional MPP paths or to inform path finding
2158 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
2159 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
2161 let mut used_liquidities: HashMap<CandidateHopId, u64> =
2162 hash_map_with_capacity(network_nodes.len());
2164 // Keeping track of how much value we already collected across other paths. Helps to decide
2165 // when we want to stop looking for new paths.
2166 let mut already_collected_value_msat = 0;
2168 for (_, channels) in first_hop_targets.iter_mut() {
2169 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
2173 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
2174 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
2176 // Remember how many candidates we ignored to allow for some logging afterwards.
2177 let mut num_ignored_value_contribution: u32 = 0;
2178 let mut num_ignored_path_length_limit: u32 = 0;
2179 let mut num_ignored_cltv_delta_limit: u32 = 0;
2180 let mut num_ignored_previously_failed: u32 = 0;
2181 let mut num_ignored_total_fee_limit: u32 = 0;
2182 let mut num_ignored_avoid_overpayment: u32 = 0;
2183 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
2185 macro_rules! add_entry {
2186 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
2187 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
2188 // since that value has to be transferred over this channel.
2189 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
2190 ( $candidate: expr, $next_hops_fee_msat: expr,
2191 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
2192 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
2193 // We "return" whether we updated the path at the end, and how much we can route via
2194 // this channel, via this:
2195 let mut hop_contribution_amt_msat = None;
2196 // Channels to self should not be used. This is more of belt-and-suspenders, because in
2197 // practice these cases should be caught earlier:
2198 // - for regular channels at channel announcement (TODO)
2199 // - for first and last hops early in get_route
2200 let src_node_id = $candidate.source();
2201 if Some(src_node_id) != $candidate.target() {
2202 let scid_opt = $candidate.short_channel_id();
2203 let effective_capacity = $candidate.effective_capacity();
2204 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
2206 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
2207 // It may be misleading because we might later choose to reduce the value transferred
2208 // over these channels, and the channel which was insufficient might become sufficient.
2209 // Worst case: we drop a good channel here because it can't cover the high following
2210 // fees caused by one expensive channel, but then this channel could have been used
2211 // if the amount being transferred over this path is lower.
2212 // We do this for now, but this is a subject for removal.
2213 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
2214 let used_liquidity_msat = used_liquidities
2215 .get(&$candidate.id())
2216 .map_or(0, |used_liquidity_msat| {
2217 available_value_contribution_msat = available_value_contribution_msat
2218 .saturating_sub(*used_liquidity_msat);
2219 *used_liquidity_msat
2222 // Verify the liquidity offered by this channel complies to the minimal contribution.
2223 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
2224 // Do not consider candidate hops that would exceed the maximum path length.
2225 let path_length_to_node = $next_hops_path_length
2226 + if $candidate.blinded_hint_idx().is_some() { 0 } else { 1 };
2227 let exceeds_max_path_length = path_length_to_node > max_path_length;
2229 // Do not consider candidates that exceed the maximum total cltv expiry limit.
2230 // In order to already account for some of the privacy enhancing random CLTV
2231 // expiry delta offset we add on top later, we subtract a rough estimate
2232 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
2233 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
2234 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
2235 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
2236 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
2237 .saturating_add($candidate.cltv_expiry_delta());
2238 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
2240 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
2241 // Includes paying fees for the use of the following channels.
2242 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
2243 Some(result) => result,
2244 // Can't overflow due to how the values were computed right above.
2245 None => unreachable!(),
2247 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2248 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
2249 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
2251 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2252 let may_overpay_to_meet_path_minimum_msat =
2253 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
2254 recommended_value_msat >= $candidate.htlc_minimum_msat()) ||
2255 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
2256 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
2258 let payment_failed_on_this_channel = match scid_opt {
2259 Some(scid) => payment_params.previously_failed_channels.contains(&scid),
2260 None => match $candidate.blinded_hint_idx() {
2262 payment_params.previously_failed_blinded_path_idxs.contains(&(idx as u64))
2268 let (should_log_candidate, first_hop_details) = match $candidate {
2269 CandidateRouteHop::FirstHop(hop) => (true, Some(hop.details)),
2270 CandidateRouteHop::PrivateHop(_) => (true, None),
2271 CandidateRouteHop::Blinded(_) => (true, None),
2272 CandidateRouteHop::OneHopBlinded(_) => (true, None),
2276 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
2277 // bother considering this channel. If retrying with recommended_value_msat may
2278 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
2279 // around again with a higher amount.
2280 if !contributes_sufficient_value {
2281 if should_log_candidate {
2282 log_trace!(logger, "Ignoring {} due to insufficient value contribution (channel max {:?}).",
2283 LoggedCandidateHop(&$candidate),
2284 effective_capacity);
2286 num_ignored_value_contribution += 1;
2287 } else if exceeds_max_path_length {
2288 if should_log_candidate {
2289 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
2291 num_ignored_path_length_limit += 1;
2292 } else if exceeds_cltv_delta_limit {
2293 if should_log_candidate {
2294 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
2296 if let Some(_) = first_hop_details {
2298 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
2299 hop_total_cltv_delta,
2300 max_total_cltv_expiry_delta,
2304 num_ignored_cltv_delta_limit += 1;
2305 } else if payment_failed_on_this_channel {
2306 if should_log_candidate {
2307 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
2309 num_ignored_previously_failed += 1;
2310 } else if may_overpay_to_meet_path_minimum_msat {
2311 if should_log_candidate {
2313 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit ({}).",
2314 LoggedCandidateHop(&$candidate), $candidate.htlc_minimum_msat());
2316 num_ignored_avoid_overpayment += 1;
2317 hit_minimum_limit = true;
2318 } else if over_path_minimum_msat {
2319 // Note that low contribution here (limited by available_liquidity_msat)
2320 // might violate htlc_minimum_msat on the hops which are next along the
2321 // payment path (upstream to the payee). To avoid that, we recompute
2322 // path fees knowing the final path contribution after constructing it.
2323 let curr_min = cmp::max(
2324 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
2326 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
2327 .saturating_add(curr_min);
2328 let hm_entry = dist.entry(src_node_id);
2329 let old_entry = hm_entry.or_insert_with(|| {
2330 // If there was previously no known way to access the source node
2331 // (recall it goes payee-to-payer) of short_channel_id, first add a
2332 // semi-dummy record just to compute the fees to reach the source node.
2333 // This will affect our decision on selecting short_channel_id
2334 // as a way to reach the $candidate.target() node.
2336 candidate: $candidate.clone(),
2338 next_hops_fee_msat: u64::max_value(),
2339 hop_use_fee_msat: u64::max_value(),
2340 total_fee_msat: u64::max_value(),
2341 path_htlc_minimum_msat,
2342 path_penalty_msat: u64::max_value(),
2343 was_processed: false,
2344 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2345 value_contribution_msat,
2349 #[allow(unused_mut)] // We only use the mut in cfg(test)
2350 let mut should_process = !old_entry.was_processed;
2351 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2353 // In test/fuzzing builds, we do extra checks to make sure the skipping
2354 // of already-seen nodes only happens in cases we expect (see below).
2355 if !should_process { should_process = true; }
2359 let mut hop_use_fee_msat = 0;
2360 let mut total_fee_msat: u64 = $next_hops_fee_msat;
2362 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2363 // will have the same effective-fee
2364 if src_node_id != our_node_id {
2365 // Note that `u64::max_value` means we'll always fail the
2366 // `old_entry.total_fee_msat > total_fee_msat` check below
2367 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
2368 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2371 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2372 if total_fee_msat > max_total_routing_fee_msat {
2373 if should_log_candidate {
2374 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2376 if let Some(_) = first_hop_details {
2378 "First hop candidate routing fee: {}. Limit: {}",
2380 max_total_routing_fee_msat,
2384 num_ignored_total_fee_limit += 1;
2386 let channel_usage = ChannelUsage {
2387 amount_msat: amount_to_transfer_over_msat,
2388 inflight_htlc_msat: used_liquidity_msat,
2391 let channel_penalty_msat =
2392 scorer.channel_penalty_msat($candidate,
2395 let path_penalty_msat = $next_hops_path_penalty_msat
2396 .saturating_add(channel_penalty_msat);
2398 // Update the way of reaching $candidate.source()
2399 // with the given short_channel_id (from $candidate.target()),
2400 // if this way is cheaper than the already known
2401 // (considering the cost to "reach" this channel from the route destination,
2402 // the cost of using this channel,
2403 // and the cost of routing to the source node of this channel).
2404 // Also, consider that htlc_minimum_msat_difference, because we might end up
2405 // paying it. Consider the following exploit:
2406 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2407 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2408 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2409 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2411 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2412 // but it may require additional tracking - we don't want to double-count
2413 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2414 // can't use something that may decrease on future hops.
2415 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2416 .saturating_add(old_entry.path_penalty_msat);
2417 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2418 .saturating_add(path_penalty_msat);
2420 if !old_entry.was_processed && new_cost < old_cost {
2421 let new_graph_node = RouteGraphNode {
2422 node_id: src_node_id,
2423 score: cmp::max(total_fee_msat, path_htlc_minimum_msat).saturating_add(path_penalty_msat),
2424 total_cltv_delta: hop_total_cltv_delta,
2425 value_contribution_msat,
2426 path_length_to_node,
2428 targets.push(new_graph_node);
2429 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2430 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2431 old_entry.total_fee_msat = total_fee_msat;
2432 old_entry.candidate = $candidate.clone();
2433 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2434 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2435 old_entry.path_penalty_msat = path_penalty_msat;
2436 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2438 old_entry.value_contribution_msat = value_contribution_msat;
2440 hop_contribution_amt_msat = Some(value_contribution_msat);
2441 } else if old_entry.was_processed && new_cost < old_cost {
2442 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2444 // If we're skipping processing a node which was previously
2445 // processed even though we found another path to it with a
2446 // cheaper fee, check that it was because the second path we
2447 // found (which we are processing now) has a lower value
2448 // contribution due to an HTLC minimum limit.
2450 // e.g. take a graph with two paths from node 1 to node 2, one
2451 // through channel A, and one through channel B. Channel A and
2452 // B are both in the to-process heap, with their scores set by
2453 // a higher htlc_minimum than fee.
2454 // Channel A is processed first, and the channels onwards from
2455 // node 1 are added to the to-process heap. Thereafter, we pop
2456 // Channel B off of the heap, note that it has a much more
2457 // restrictive htlc_maximum_msat, and recalculate the fees for
2458 // all of node 1's channels using the new, reduced, amount.
2460 // This would be bogus - we'd be selecting a higher-fee path
2461 // with a lower htlc_maximum_msat instead of the one we'd
2462 // already decided to use.
2463 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2465 value_contribution_msat + path_penalty_msat <
2466 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2473 if should_log_candidate {
2475 "Ignoring {} due to its htlc_minimum_msat limit.",
2476 LoggedCandidateHop(&$candidate));
2478 if let Some(details) = first_hop_details {
2480 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2481 details.next_outbound_htlc_minimum_msat,
2485 num_ignored_htlc_minimum_msat_limit += 1;
2489 hop_contribution_amt_msat
2493 let default_node_features = default_node_features();
2495 // Find ways (channels with destination) to reach a given node and store them
2496 // in the corresponding data structures (routing graph etc).
2497 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2498 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2499 // This data can later be helpful to optimize routing (pay lower fees).
2500 macro_rules! add_entries_to_cheapest_to_target_node {
2501 ( $node: expr, $node_id: expr, $next_hops_value_contribution: expr,
2502 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2503 let fee_to_target_msat;
2504 let next_hops_path_htlc_minimum_msat;
2505 let next_hops_path_penalty_msat;
2506 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
2507 let was_processed = elem.was_processed;
2508 elem.was_processed = true;
2509 fee_to_target_msat = elem.total_fee_msat;
2510 next_hops_path_htlc_minimum_msat = elem.path_htlc_minimum_msat;
2511 next_hops_path_penalty_msat = elem.path_penalty_msat;
2514 // Entries are added to dist in add_entry!() when there is a channel from a node.
2515 // Because there are no channels from payee, it will not have a dist entry at this point.
2516 // If we're processing any other node, it is always be the result of a channel from it.
2517 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2518 fee_to_target_msat = 0;
2519 next_hops_path_htlc_minimum_msat = 0;
2520 next_hops_path_penalty_msat = 0;
2525 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
2526 for details in first_channels {
2527 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2528 details, payer_node_id: &our_node_id,
2530 add_entry!(&candidate, fee_to_target_msat,
2531 $next_hops_value_contribution,
2532 next_hops_path_htlc_minimum_msat, next_hops_path_penalty_msat,
2533 $next_hops_cltv_delta, $next_hops_path_length);
2537 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2538 &node_info.features()
2540 &default_node_features
2543 if !features.requires_unknown_bits() {
2544 for chan_id in $node.channels.iter() {
2545 let chan = network_channels.get(chan_id).unwrap();
2546 if !chan.features.requires_unknown_bits() {
2547 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2548 if first_hops.is_none() || *source != our_node_id {
2549 if directed_channel.direction().enabled {
2550 let candidate = CandidateRouteHop::PublicHop(PublicHopCandidate {
2551 info: directed_channel,
2552 short_channel_id: *chan_id,
2554 add_entry!(&candidate,
2556 $next_hops_value_contribution,
2557 next_hops_path_htlc_minimum_msat,
2558 next_hops_path_penalty_msat,
2559 $next_hops_cltv_delta, $next_hops_path_length);
2570 let mut payment_paths = Vec::<PaymentPath>::new();
2572 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2573 'paths_collection: loop {
2574 // For every new path, start from scratch, except for used_liquidities, which
2575 // helps to avoid reusing previously selected paths in future iterations.
2578 hit_minimum_limit = false;
2580 // If first hop is a private channel and the only way to reach the payee, this is the only
2581 // place where it could be added.
2582 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2583 for details in first_channels {
2584 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2585 details, payer_node_id: &our_node_id,
2587 let added = add_entry!(&candidate, 0, path_value_msat,
2588 0, 0u64, 0, 0).is_some();
2589 log_trace!(logger, "{} direct route to payee via {}",
2590 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2594 // Add the payee as a target, so that the payee-to-payer
2595 // search algorithm knows what to start with.
2596 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2597 // The payee is not in our network graph, so nothing to add here.
2598 // There is still a chance of reaching them via last_hops though,
2599 // so don't yet fail the payment here.
2600 // If not, targets.pop() will not even let us enter the loop in step 2.
2603 add_entries_to_cheapest_to_target_node!(node, payee, path_value_msat, 0, 0);
2608 // If a caller provided us with last hops, add them to routing targets. Since this happens
2609 // earlier than general path finding, they will be somewhat prioritized, although currently
2610 // it matters only if the fees are exactly the same.
2611 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2612 // Only add the hops in this route to our candidate set if either
2613 // we have a direct channel to the first hop or the first hop is
2614 // in the regular network graph.
2615 let source_node_id = match introduction_node_id_cache[hint_idx] {
2616 Some(node_id) => node_id,
2617 None => match &hint.1.introduction_node {
2618 IntroductionNode::NodeId(pubkey) => {
2619 let node_id = NodeId::from_pubkey(&pubkey);
2620 match first_hop_targets.get_key_value(&node_id).map(|(key, _)| key) {
2621 Some(node_id) => node_id,
2625 IntroductionNode::DirectedShortChannelId(direction, scid) => {
2626 let first_hop = first_hop_targets.iter().find(|(_, channels)|
2629 .any(|details| Some(*scid) == details.get_outbound_payment_scid())
2632 Some((counterparty_node_id, _)) => {
2633 direction.select_node_id(&our_node_id, counterparty_node_id)
2640 if our_node_id == *source_node_id { continue }
2641 let candidate = if hint.1.blinded_hops.len() == 1 {
2642 CandidateRouteHop::OneHopBlinded(
2643 OneHopBlindedPathCandidate { source_node_id, hint, hint_idx }
2646 CandidateRouteHop::Blinded(BlindedPathCandidate { source_node_id, hint, hint_idx })
2648 let mut path_contribution_msat = path_value_msat;
2649 if let Some(hop_used_msat) = add_entry!(&candidate,
2650 0, path_contribution_msat, 0, 0_u64, 0, 0)
2652 path_contribution_msat = hop_used_msat;
2654 if let Some(first_channels) = first_hop_targets.get(source_node_id) {
2655 let mut first_channels = first_channels.clone();
2656 sort_first_hop_channels(
2657 &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2659 for details in first_channels {
2660 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2661 details, payer_node_id: &our_node_id,
2663 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2667 let path_min = candidate.htlc_minimum_msat().saturating_add(
2668 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2669 add_entry!(&first_hop_candidate, blinded_path_fee, path_contribution_msat, path_min,
2670 0_u64, candidate.cltv_expiry_delta(), 0);
2674 for route in payment_params.payee.unblinded_route_hints().iter()
2675 .filter(|route| !route.0.is_empty())
2677 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2678 let first_hop_src_is_reachable =
2679 // Only add the hops in this route to our candidate set if either we are part of
2680 // the first hop, we have a direct channel to the first hop, or the first hop is in
2681 // the regular network graph.
2682 our_node_id == first_hop_src_id ||
2683 first_hop_targets.get(&first_hop_src_id).is_some() ||
2684 network_nodes.get(&first_hop_src_id).is_some();
2685 if first_hop_src_is_reachable {
2686 // We start building the path from reverse, i.e., from payee
2687 // to the first RouteHintHop in the path.
2688 let hop_iter = route.0.iter().rev();
2689 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2690 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2691 let mut hop_used = true;
2692 let mut aggregate_next_hops_fee_msat: u64 = 0;
2693 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2694 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2695 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2696 let mut aggregate_next_hops_path_length: u8 = 0;
2697 let mut aggregate_path_contribution_msat = path_value_msat;
2699 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2700 let target = private_hop_key_cache.get(prev_hop_id).unwrap();
2702 if let Some(first_channels) = first_hop_targets.get(target) {
2703 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2704 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2705 hop.short_channel_id);
2710 let candidate = network_channels
2711 .get(&hop.short_channel_id)
2712 .and_then(|channel| channel.as_directed_to(target))
2713 .map(|(info, _)| CandidateRouteHop::PublicHop(PublicHopCandidate {
2715 short_channel_id: hop.short_channel_id,
2717 .unwrap_or_else(|| CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: hop, target_node_id: target }));
2719 if let Some(hop_used_msat) = add_entry!(&candidate,
2720 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2721 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2722 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2724 aggregate_path_contribution_msat = hop_used_msat;
2726 // If this hop was not used then there is no use checking the preceding
2727 // hops in the RouteHint. We can break by just searching for a direct
2728 // channel between last checked hop and first_hop_targets.
2732 let used_liquidity_msat = used_liquidities
2733 .get(&candidate.id()).copied()
2735 let channel_usage = ChannelUsage {
2736 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2737 inflight_htlc_msat: used_liquidity_msat,
2738 effective_capacity: candidate.effective_capacity(),
2740 let channel_penalty_msat = scorer.channel_penalty_msat(
2741 &candidate, channel_usage, score_params
2743 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2744 .saturating_add(channel_penalty_msat);
2746 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2747 .saturating_add(hop.cltv_expiry_delta as u32);
2749 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2752 // Searching for a direct channel between last checked hop and first_hop_targets
2753 if let Some(first_channels) = first_hop_targets.get(target) {
2754 let mut first_channels = first_channels.clone();
2755 sort_first_hop_channels(
2756 &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2758 for details in first_channels {
2759 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2760 details, payer_node_id: &our_node_id,
2762 add_entry!(&first_hop_candidate,
2763 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2764 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2765 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2773 // In the next values of the iterator, the aggregate fees already reflects
2774 // the sum of value sent from payer (final_value_msat) and routing fees
2775 // for the last node in the RouteHint. We need to just add the fees to
2776 // route through the current node so that the preceding node (next iteration)
2778 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2779 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2780 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2782 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2783 // this route hint's source node to forward said min over this channel.
2784 aggregate_next_hops_path_htlc_minimum_msat = {
2785 let curr_htlc_min = cmp::max(
2786 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2788 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2789 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2792 if idx == route.0.len() - 1 {
2793 // The last hop in this iterator is the first hop in
2794 // overall RouteHint.
2795 // If this hop connects to a node with which we have a direct channel,
2796 // ignore the network graph and, if the last hop was added, add our
2797 // direct channel to the candidate set.
2799 // Note that we *must* check if the last hop was added as `add_entry`
2800 // always assumes that the third argument is a node to which we have a
2802 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
2803 let mut first_channels = first_channels.clone();
2804 sort_first_hop_channels(
2805 &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2807 for details in first_channels {
2808 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2809 details, payer_node_id: &our_node_id,
2811 add_entry!(&first_hop_candidate,
2812 aggregate_next_hops_fee_msat,
2813 aggregate_path_contribution_msat,
2814 aggregate_next_hops_path_htlc_minimum_msat,
2815 aggregate_next_hops_path_penalty_msat,
2816 aggregate_next_hops_cltv_delta,
2817 aggregate_next_hops_path_length);
2825 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2827 // At this point, targets are filled with the data from first and
2828 // last hops communicated by the caller, and the payment receiver.
2829 let mut found_new_path = false;
2832 // If this loop terminates due the exhaustion of targets, two situations are possible:
2833 // - not enough outgoing liquidity:
2834 // 0 < already_collected_value_msat < final_value_msat
2835 // - enough outgoing liquidity:
2836 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2837 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2838 // paths_collection will be stopped because found_new_path==false.
2839 // This is not necessarily a routing failure.
2840 'path_construction: while let Some(RouteGraphNode { node_id, total_cltv_delta, mut value_contribution_msat, path_length_to_node, .. }) = targets.pop() {
2842 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2843 // traversing the graph and arrange the path out of what we found.
2844 if node_id == our_node_id {
2845 let mut new_entry = dist.remove(&our_node_id).unwrap();
2846 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2849 let mut features_set = false;
2850 let target = ordered_hops.last().unwrap().0.candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2851 if let Some(first_channels) = first_hop_targets.get(&target) {
2852 for details in first_channels {
2853 if let CandidateRouteHop::FirstHop(FirstHopCandidate { details: last_hop_details, .. })
2854 = ordered_hops.last().unwrap().0.candidate
2856 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2857 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2858 features_set = true;
2865 if let Some(node) = network_nodes.get(&target) {
2866 if let Some(node_info) = node.announcement_info.as_ref() {
2867 ordered_hops.last_mut().unwrap().1 = node_info.features().clone();
2869 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2872 // We can fill in features for everything except hops which were
2873 // provided via the invoice we're paying. We could guess based on the
2874 // recipient's features but for now we simply avoid guessing at all.
2878 // Means we successfully traversed from the payer to the payee, now
2879 // save this path for the payment route. Also, update the liquidity
2880 // remaining on the used hops, so that we take them into account
2881 // while looking for more paths.
2882 if target == maybe_dummy_payee_node_id {
2886 new_entry = match dist.remove(&target) {
2887 Some(payment_hop) => payment_hop,
2888 // We can't arrive at None because, if we ever add an entry to targets,
2889 // we also fill in the entry in dist (see add_entry!).
2890 None => unreachable!(),
2892 // We "propagate" the fees one hop backward (topologically) here,
2893 // so that fees paid for a HTLC forwarding on the current channel are
2894 // associated with the previous channel (where they will be subtracted).
2895 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2896 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2898 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2899 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2901 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2902 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2904 let mut payment_path = PaymentPath {hops: ordered_hops};
2906 // We could have possibly constructed a slightly inconsistent path: since we reduce
2907 // value being transferred along the way, we could have violated htlc_minimum_msat
2908 // on some channels we already passed (assuming dest->source direction). Here, we
2909 // recompute the fees again, so that if that's the case, we match the currently
2910 // underpaid htlc_minimum_msat with fees.
2911 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2912 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2913 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2915 // Since a path allows to transfer as much value as
2916 // the smallest channel it has ("bottleneck"), we should recompute
2917 // the fees so sender HTLC don't overpay fees when traversing
2918 // larger channels than the bottleneck. This may happen because
2919 // when we were selecting those channels we were not aware how much value
2920 // this path will transfer, and the relative fee for them
2921 // might have been computed considering a larger value.
2922 // Remember that we used these channels so that we don't rely
2923 // on the same liquidity in future paths.
2924 let mut prevented_redundant_path_selection = false;
2925 for (hop, _) in payment_path.hops.iter() {
2926 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2927 let used_liquidity_msat = used_liquidities
2928 .entry(hop.candidate.id())
2929 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2930 .or_insert(spent_on_hop_msat);
2931 let hop_capacity = hop.candidate.effective_capacity();
2932 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2933 if *used_liquidity_msat == hop_max_msat {
2934 // If this path used all of this channel's available liquidity, we know
2935 // this path will not be selected again in the next loop iteration.
2936 prevented_redundant_path_selection = true;
2938 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2940 if !prevented_redundant_path_selection {
2941 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2942 // we'll probably end up picking the same path again on the next iteration.
2943 // Decrease the available liquidity of a hop in the middle of the path.
2944 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2945 let exhausted = u64::max_value();
2947 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2948 LoggedCandidateHop(victim_candidate));
2949 if let Some(scid) = victim_candidate.short_channel_id() {
2950 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2951 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2955 // Track the total amount all our collected paths allow to send so that we know
2956 // when to stop looking for more paths
2957 already_collected_value_msat += value_contribution_msat;
2959 payment_paths.push(payment_path);
2960 found_new_path = true;
2961 break 'path_construction;
2964 // If we found a path back to the payee, we shouldn't try to process it again. This is
2965 // the equivalent of the `elem.was_processed` check in
2966 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2967 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2969 // Otherwise, since the current target node is not us,
2970 // keep "unrolling" the payment graph from payee to payer by
2971 // finding a way to reach the current target from the payer side.
2972 match network_nodes.get(&node_id) {
2975 add_entries_to_cheapest_to_target_node!(node, node_id,
2976 value_contribution_msat,
2977 total_cltv_delta, path_length_to_node);
2983 if !found_new_path && channel_saturation_pow_half != 0 {
2984 channel_saturation_pow_half = 0;
2985 continue 'paths_collection;
2987 // If we don't support MPP, no use trying to gather more value ever.
2988 break 'paths_collection;
2992 // Stop either when the recommended value is reached or if no new path was found in this
2994 // In the latter case, making another path finding attempt won't help,
2995 // because we deterministically terminated the search due to low liquidity.
2996 if !found_new_path && channel_saturation_pow_half != 0 {
2997 channel_saturation_pow_half = 0;
2998 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2999 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
3000 path_value_msat = recommended_value_msat;
3001 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
3002 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
3003 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
3004 break 'paths_collection;
3005 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
3006 // Further, if this was our first walk of the graph, and we weren't limited by an
3007 // htlc_minimum_msat, return immediately because this path should suffice. If we were
3008 // limited by an htlc_minimum_msat value, find another path with a higher value,
3009 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
3010 // still keeping a lower total fee than this path.
3011 if !hit_minimum_limit {
3012 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
3013 break 'paths_collection;
3015 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher value to meet htlc_minimum_msat limit.");
3016 path_value_msat = recommended_value_msat;
3020 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
3021 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
3022 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
3023 num_ignored_total_fee_limit;
3024 if num_ignored_total > 0 {
3026 "Ignored {} candidate hops due to insufficient value contribution, {} due to path length limit, {} due to CLTV delta limit, {} due to previous payment failure, {} due to htlc_minimum_msat limit, {} to avoid overpaying, {} due to maximum total fee limit. Total: {} ignored candidates.",
3027 num_ignored_value_contribution, num_ignored_path_length_limit,
3028 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
3029 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
3030 num_ignored_total_fee_limit, num_ignored_total);
3034 if payment_paths.len() == 0 {
3035 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
3038 if already_collected_value_msat < final_value_msat {
3039 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
3043 let mut selected_route = payment_paths;
3045 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
3046 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
3048 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
3049 // the value they contribute towards the payment amount.
3050 // We sort in descending order as we will remove from the front in `retain`, next.
3051 selected_route.sort_unstable_by(|a, b|
3052 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
3053 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
3056 // We should make sure that at least 1 path left.
3057 let mut paths_left = selected_route.len();
3058 selected_route.retain(|path| {
3059 if paths_left == 1 {
3062 let path_value_msat = path.get_value_msat();
3063 if path_value_msat <= overpaid_value_msat {
3064 overpaid_value_msat -= path_value_msat;
3070 debug_assert!(selected_route.len() > 0);
3072 if overpaid_value_msat != 0 {
3074 // Now, subtract the remaining overpaid value from the most-expensive path.
3075 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
3076 // so that the sender pays less fees overall. And also htlc_minimum_msat.
3077 selected_route.sort_unstable_by(|a, b| {
3078 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3079 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3080 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
3082 let expensive_payment_path = selected_route.first_mut().unwrap();
3084 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
3085 // can't go negative.
3086 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
3087 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
3091 // Sort by the path itself and combine redundant paths.
3092 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
3093 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
3095 selected_route.sort_unstable_by_key(|path| {
3096 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
3097 debug_assert!(path.hops.len() <= key.len());
3098 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
3103 for idx in 0..(selected_route.len() - 1) {
3104 if idx + 1 >= selected_route.len() { break; }
3105 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
3106 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
3107 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
3108 selected_route[idx].update_value_and_recompute_fees(new_value);
3109 selected_route.remove(idx + 1);
3113 let mut paths = Vec::new();
3114 for payment_path in selected_route {
3115 let mut hops = Vec::with_capacity(payment_path.hops.len());
3116 for (hop, node_features) in payment_path.hops.iter()
3117 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
3119 let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
3120 let maybe_announced_channel = if let CandidateRouteHop::PublicHop(_) = hop.candidate {
3121 // If we sourced the hop from the graph we're sure the target node is announced.
3123 } else if let CandidateRouteHop::FirstHop(first_hop) = &hop.candidate {
3124 // If this is a first hop we also know if it's announced.
3125 first_hop.details.is_public
3127 // If we sourced it any other way, we double-check the network graph to see if
3128 // there are announced channels between the endpoints. If so, the hop might be
3129 // referring to any of the announced channels, as its `short_channel_id` might be
3130 // an alias, in which case we don't take any chances here.
3131 network_graph.node(&target).map_or(false, |hop_node|
3132 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
3133 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
3137 hops.push(RouteHop {
3138 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
3139 node_features: node_features.clone(),
3140 short_channel_id: hop.candidate.short_channel_id().unwrap(),
3141 channel_features: hop.candidate.features(),
3142 fee_msat: hop.fee_msat,
3143 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
3144 maybe_announced_channel,
3147 let mut final_cltv_delta = final_cltv_expiry_delta;
3148 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
3149 if let Some(blinded_path) = h.candidate.blinded_path() {
3150 final_cltv_delta = h.candidate.cltv_expiry_delta();
3152 hops: blinded_path.blinded_hops.clone(),
3153 blinding_point: blinded_path.blinding_point,
3154 excess_final_cltv_expiry_delta: 0,
3155 final_value_msat: h.fee_msat,
3159 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
3160 // applicable for the previous hop.
3161 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
3162 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
3165 paths.push(Path { hops, blinded_tail });
3167 // Make sure we would never create a route with more paths than we allow.
3168 debug_assert!(paths.len() <= payment_params.max_path_count.into());
3170 if let Some(node_features) = payment_params.payee.node_features() {
3171 for path in paths.iter_mut() {
3172 path.hops.last_mut().unwrap().node_features = node_features.clone();
3176 let route = Route { paths, route_params: Some(route_params.clone()) };
3178 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
3179 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
3180 if route.get_total_fees() > max_total_routing_fee_msat {
3181 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
3182 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
3186 log_info!(logger, "Got route: {}", log_route!(route));
3190 // When an adversarial intermediary node observes a payment, it may be able to infer its
3191 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
3192 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
3193 // payment path by adding a randomized 'shadow route' offset to the final hop.
3194 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
3195 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
3197 let network_channels = network_graph.channels();
3198 let network_nodes = network_graph.nodes();
3200 for path in route.paths.iter_mut() {
3201 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
3203 // Remember the last three nodes of the random walk and avoid looping back on them.
3204 // Init with the last three nodes from the actual path, if possible.
3205 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
3206 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
3207 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
3209 // Choose the last publicly known node as the starting point for the random walk.
3210 let mut cur_hop: Option<NodeId> = None;
3211 let mut path_nonce = [0u8; 12];
3212 if let Some(starting_hop) = path.hops.iter().rev()
3213 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
3214 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
3215 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
3218 // Init PRNG with the path-dependant nonce, which is static for private paths.
3219 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
3220 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
3222 // Pick a random path length in [1 .. 3]
3223 prng.process_in_place(&mut random_path_bytes);
3224 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
3226 for random_hop in 0..random_walk_length {
3227 // If we don't find a suitable offset in the public network graph, we default to
3228 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3229 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
3231 if let Some(cur_node_id) = cur_hop {
3232 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
3233 // Randomly choose the next unvisited hop.
3234 prng.process_in_place(&mut random_path_bytes);
3235 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
3236 .checked_rem(cur_node.channels.len())
3237 .and_then(|index| cur_node.channels.get(index))
3238 .and_then(|id| network_channels.get(id)) {
3239 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
3240 if !nodes_to_avoid.iter().any(|x| x == next_id) {
3241 nodes_to_avoid[random_hop] = *next_id;
3242 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
3243 cur_hop = Some(*next_id);
3250 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
3251 .checked_add(random_hop_offset)
3252 .unwrap_or(shadow_ctlv_expiry_delta_offset);
3255 // Limit the total offset to reduce the worst-case locked liquidity timevalue
3256 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
3257 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
3259 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
3260 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3261 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
3262 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
3263 max_path_offset = cmp::max(
3264 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
3265 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
3266 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
3268 // Add 'shadow' CLTV offset to the final hop
3269 if let Some(tail) = path.blinded_tail.as_mut() {
3270 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
3271 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
3273 if let Some(last_hop) = path.hops.last_mut() {
3274 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
3275 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
3280 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
3281 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
3283 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
3284 pub fn build_route_from_hops<L: Deref, GL: Deref>(
3285 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3286 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
3287 ) -> Result<Route, LightningError>
3288 where L::Target: Logger, GL::Target: Logger {
3289 let graph_lock = network_graph.read_only();
3290 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
3291 &graph_lock, logger, random_seed_bytes)?;
3292 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
3296 fn build_route_from_hops_internal<L: Deref>(
3297 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3298 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
3299 ) -> Result<Route, LightningError> where L::Target: Logger {
3302 our_node_id: NodeId,
3303 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
3306 impl ScoreLookUp for HopScorer {
3307 type ScoreParams = ();
3308 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
3309 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
3311 let mut cur_id = self.our_node_id;
3312 for i in 0..self.hop_ids.len() {
3313 if let Some(next_id) = self.hop_ids[i] {
3314 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
3326 impl<'a> Writeable for HopScorer {
3328 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
3333 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
3334 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
3337 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
3338 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
3339 for i in 0..hops.len() {
3340 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
3343 let scorer = HopScorer { our_node_id, hop_ids };
3345 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
3350 use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode};
3351 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
3352 use crate::routing::utxo::UtxoResult;
3353 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
3354 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
3355 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop, PublicHopCandidate};
3356 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
3357 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
3358 use crate::chain::transaction::OutPoint;
3359 use crate::ln::channel_state::{ChannelCounterparty, ChannelDetails, ChannelShutdownState};
3360 use crate::ln::types::ChannelId;
3361 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
3362 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
3363 use crate::ln::channelmanager;
3364 use crate::offers::invoice::BlindedPayInfo;
3365 use crate::util::config::UserConfig;
3366 use crate::util::test_utils as ln_test_utils;
3367 use crate::crypto::chacha20::ChaCha20;
3368 use crate::util::ser::{Readable, Writeable};
3370 use crate::util::ser::Writer;
3372 use bitcoin::amount::Amount;
3373 use bitcoin::hashes::Hash;
3374 use bitcoin::network::Network;
3375 use bitcoin::blockdata::constants::ChainHash;
3376 use bitcoin::blockdata::script::Builder;
3377 use bitcoin::blockdata::opcodes;
3378 use bitcoin::blockdata::transaction::TxOut;
3379 use bitcoin::hashes::hex::FromHex;
3380 use bitcoin::secp256k1::{PublicKey,SecretKey};
3381 use bitcoin::secp256k1::Secp256k1;
3383 use crate::io::Cursor;
3384 use crate::prelude::*;
3385 use crate::sync::Arc;
3387 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3388 features: InitFeatures, outbound_capacity_msat: u64) -> ChannelDetails {
3390 channel_id: ChannelId::new_zero(),
3391 counterparty: ChannelCounterparty {
3394 unspendable_punishment_reserve: 0,
3395 forwarding_info: None,
3396 outbound_htlc_minimum_msat: None,
3397 outbound_htlc_maximum_msat: None,
3399 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3402 outbound_scid_alias: None,
3403 inbound_scid_alias: None,
3404 channel_value_satoshis: 0,
3407 outbound_capacity_msat,
3408 next_outbound_htlc_limit_msat: outbound_capacity_msat,
3409 next_outbound_htlc_minimum_msat: 0,
3410 inbound_capacity_msat: 42,
3411 unspendable_punishment_reserve: None,
3412 confirmations_required: None,
3413 confirmations: None,
3414 force_close_spend_delay: None,
3415 is_outbound: true, is_channel_ready: true,
3416 is_usable: true, is_public: true,
3417 inbound_htlc_minimum_msat: None,
3418 inbound_htlc_maximum_msat: None,
3420 feerate_sat_per_1000_weight: None,
3421 channel_shutdown_state: Some(ChannelShutdownState::NotShuttingDown),
3422 pending_inbound_htlcs: Vec::new(),
3423 pending_outbound_htlcs: Vec::new(),
3428 fn simple_route_test() {
3429 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3430 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3431 let mut payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3432 let scorer = ln_test_utils::TestScorer::new();
3433 let random_seed_bytes = [42; 32];
3435 // Simple route to 2 via 1
3437 let route_params = RouteParameters::from_payment_params_and_value(
3438 payment_params.clone(), 0);
3439 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3440 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3441 &Default::default(), &random_seed_bytes) {
3442 assert_eq!(err, "Cannot send a payment of 0 msat");
3443 } else { panic!(); }
3445 payment_params.max_path_length = 2;
3446 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3447 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3448 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3449 assert_eq!(route.paths[0].hops.len(), 2);
3451 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3452 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3453 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3454 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3455 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3456 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3458 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3459 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3460 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3461 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3462 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3463 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3465 route_params.payment_params.max_path_length = 1;
3466 get_route(&our_id, &route_params, &network_graph.read_only(), None,
3467 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap_err();
3471 fn invalid_first_hop_test() {
3472 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3473 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3474 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3475 let scorer = ln_test_utils::TestScorer::new();
3476 let random_seed_bytes = [42; 32];
3478 // Simple route to 2 via 1
3480 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3482 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3483 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3484 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3485 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3486 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3487 } else { panic!(); }
3489 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3490 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3491 assert_eq!(route.paths[0].hops.len(), 2);
3495 fn htlc_minimum_test() {
3496 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3497 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3498 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3499 let scorer = ln_test_utils::TestScorer::new();
3500 let random_seed_bytes = [42; 32];
3502 // Simple route to 2 via 1
3504 // Disable other paths
3505 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3506 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3507 short_channel_id: 12,
3509 message_flags: 1, // Only must_be_one
3510 channel_flags: 2, // to disable
3511 cltv_expiry_delta: 0,
3512 htlc_minimum_msat: 0,
3513 htlc_maximum_msat: MAX_VALUE_MSAT,
3515 fee_proportional_millionths: 0,
3516 excess_data: Vec::new()
3518 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3519 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3520 short_channel_id: 3,
3522 message_flags: 1, // Only must_be_one
3523 channel_flags: 2, // to disable
3524 cltv_expiry_delta: 0,
3525 htlc_minimum_msat: 0,
3526 htlc_maximum_msat: MAX_VALUE_MSAT,
3528 fee_proportional_millionths: 0,
3529 excess_data: Vec::new()
3531 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3532 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3533 short_channel_id: 13,
3535 message_flags: 1, // Only must_be_one
3536 channel_flags: 2, // to disable
3537 cltv_expiry_delta: 0,
3538 htlc_minimum_msat: 0,
3539 htlc_maximum_msat: MAX_VALUE_MSAT,
3541 fee_proportional_millionths: 0,
3542 excess_data: Vec::new()
3544 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3545 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3546 short_channel_id: 6,
3548 message_flags: 1, // Only must_be_one
3549 channel_flags: 2, // to disable
3550 cltv_expiry_delta: 0,
3551 htlc_minimum_msat: 0,
3552 htlc_maximum_msat: MAX_VALUE_MSAT,
3554 fee_proportional_millionths: 0,
3555 excess_data: Vec::new()
3557 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3558 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3559 short_channel_id: 7,
3561 message_flags: 1, // Only must_be_one
3562 channel_flags: 2, // to disable
3563 cltv_expiry_delta: 0,
3564 htlc_minimum_msat: 0,
3565 htlc_maximum_msat: MAX_VALUE_MSAT,
3567 fee_proportional_millionths: 0,
3568 excess_data: Vec::new()
3571 // Check against amount_to_transfer_over_msat.
3572 // Set minimal HTLC of 200_000_000 msat.
3573 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3574 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3575 short_channel_id: 2,
3577 message_flags: 1, // Only must_be_one
3579 cltv_expiry_delta: 0,
3580 htlc_minimum_msat: 200_000_000,
3581 htlc_maximum_msat: MAX_VALUE_MSAT,
3583 fee_proportional_millionths: 0,
3584 excess_data: Vec::new()
3587 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3589 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3590 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3591 short_channel_id: 4,
3593 message_flags: 1, // Only must_be_one
3595 cltv_expiry_delta: 0,
3596 htlc_minimum_msat: 0,
3597 htlc_maximum_msat: 199_999_999,
3599 fee_proportional_millionths: 0,
3600 excess_data: Vec::new()
3603 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3604 let route_params = RouteParameters::from_payment_params_and_value(
3605 payment_params, 199_999_999);
3606 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3607 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3608 &Default::default(), &random_seed_bytes) {
3609 assert_eq!(err, "Failed to find a path to the given destination");
3610 } else { panic!(); }
3612 // Lift the restriction on the first hop.
3613 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3614 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3615 short_channel_id: 2,
3617 message_flags: 1, // Only must_be_one
3619 cltv_expiry_delta: 0,
3620 htlc_minimum_msat: 0,
3621 htlc_maximum_msat: MAX_VALUE_MSAT,
3623 fee_proportional_millionths: 0,
3624 excess_data: Vec::new()
3627 // A payment above the minimum should pass
3628 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3629 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3630 assert_eq!(route.paths[0].hops.len(), 2);
3634 fn htlc_minimum_overpay_test() {
3635 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3636 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3637 let config = UserConfig::default();
3638 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3639 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3641 let scorer = ln_test_utils::TestScorer::new();
3642 let random_seed_bytes = [42; 32];
3644 // A route to node#2 via two paths.
3645 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3646 // Thus, they can't send 60 without overpaying.
3647 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3648 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3649 short_channel_id: 2,
3651 message_flags: 1, // Only must_be_one
3653 cltv_expiry_delta: 0,
3654 htlc_minimum_msat: 35_000,
3655 htlc_maximum_msat: 40_000,
3657 fee_proportional_millionths: 0,
3658 excess_data: Vec::new()
3660 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3661 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3662 short_channel_id: 12,
3664 message_flags: 1, // Only must_be_one
3666 cltv_expiry_delta: 0,
3667 htlc_minimum_msat: 35_000,
3668 htlc_maximum_msat: 40_000,
3670 fee_proportional_millionths: 0,
3671 excess_data: Vec::new()
3675 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3676 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3677 short_channel_id: 13,
3679 message_flags: 1, // Only must_be_one
3681 cltv_expiry_delta: 0,
3682 htlc_minimum_msat: 0,
3683 htlc_maximum_msat: MAX_VALUE_MSAT,
3685 fee_proportional_millionths: 0,
3686 excess_data: Vec::new()
3688 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3689 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3690 short_channel_id: 4,
3692 message_flags: 1, // Only must_be_one
3694 cltv_expiry_delta: 0,
3695 htlc_minimum_msat: 0,
3696 htlc_maximum_msat: MAX_VALUE_MSAT,
3698 fee_proportional_millionths: 0,
3699 excess_data: Vec::new()
3702 // Disable other paths
3703 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3704 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3705 short_channel_id: 1,
3707 message_flags: 1, // Only must_be_one
3708 channel_flags: 2, // to disable
3709 cltv_expiry_delta: 0,
3710 htlc_minimum_msat: 0,
3711 htlc_maximum_msat: MAX_VALUE_MSAT,
3713 fee_proportional_millionths: 0,
3714 excess_data: Vec::new()
3717 let mut route_params = RouteParameters::from_payment_params_and_value(
3718 payment_params.clone(), 60_000);
3719 route_params.max_total_routing_fee_msat = Some(15_000);
3720 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3721 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3722 // Overpay fees to hit htlc_minimum_msat.
3723 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3724 // TODO: this could be better balanced to overpay 10k and not 15k.
3725 assert_eq!(overpaid_fees, 15_000);
3727 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3728 // while taking even more fee to match htlc_minimum_msat.
3729 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3730 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3731 short_channel_id: 12,
3733 message_flags: 1, // Only must_be_one
3735 cltv_expiry_delta: 0,
3736 htlc_minimum_msat: 65_000,
3737 htlc_maximum_msat: 80_000,
3739 fee_proportional_millionths: 0,
3740 excess_data: Vec::new()
3742 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3743 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3744 short_channel_id: 2,
3746 message_flags: 1, // Only must_be_one
3748 cltv_expiry_delta: 0,
3749 htlc_minimum_msat: 0,
3750 htlc_maximum_msat: MAX_VALUE_MSAT,
3752 fee_proportional_millionths: 0,
3753 excess_data: Vec::new()
3755 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3756 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3757 short_channel_id: 4,
3759 message_flags: 1, // Only must_be_one
3761 cltv_expiry_delta: 0,
3762 htlc_minimum_msat: 0,
3763 htlc_maximum_msat: MAX_VALUE_MSAT,
3765 fee_proportional_millionths: 100_000,
3766 excess_data: Vec::new()
3769 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3770 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3771 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3772 assert_eq!(route.paths.len(), 1);
3773 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3774 let fees = route.paths[0].hops[0].fee_msat;
3775 assert_eq!(fees, 5_000);
3777 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3778 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3779 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3780 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3781 // the other channel.
3782 assert_eq!(route.paths.len(), 1);
3783 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3784 let fees = route.paths[0].hops[0].fee_msat;
3785 assert_eq!(fees, 5_000);
3789 fn htlc_minimum_recipient_overpay_test() {
3790 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3791 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3792 let config = UserConfig::default();
3793 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3794 let scorer = ln_test_utils::TestScorer::new();
3795 let random_seed_bytes = [42; 32];
3797 // Route to node2 over a single path which requires overpaying the recipient themselves.
3799 // First disable all paths except the us -> node1 -> node2 path
3800 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3801 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3802 short_channel_id: 13,
3804 message_flags: 1, // Only must_be_one
3806 cltv_expiry_delta: 0,
3807 htlc_minimum_msat: 0,
3808 htlc_maximum_msat: 0,
3810 fee_proportional_millionths: 0,
3811 excess_data: Vec::new()
3814 // Set channel 4 to free but with a high htlc_minimum_msat
3815 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3816 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3817 short_channel_id: 4,
3819 message_flags: 1, // Only must_be_one
3821 cltv_expiry_delta: 0,
3822 htlc_minimum_msat: 15_000,
3823 htlc_maximum_msat: MAX_VALUE_MSAT,
3825 fee_proportional_millionths: 0,
3826 excess_data: Vec::new()
3829 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3830 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3831 // what we try to find a route for, so this test only just happens to work out to exactly
3833 let mut route_params = RouteParameters::from_payment_params_and_value(
3834 payment_params.clone(), 5_000);
3835 route_params.max_total_routing_fee_msat = Some(9_999);
3836 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3837 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3838 &Default::default(), &random_seed_bytes) {
3839 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3840 } else { panic!(); }
3842 let mut route_params = RouteParameters::from_payment_params_and_value(
3843 payment_params.clone(), 5_000);
3844 route_params.max_total_routing_fee_msat = Some(10_000);
3845 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3846 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3847 assert_eq!(route.get_total_fees(), 10_000);
3851 fn disable_channels_test() {
3852 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3853 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3854 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3855 let scorer = ln_test_utils::TestScorer::new();
3856 let random_seed_bytes = [42; 32];
3858 // // Disable channels 4 and 12 by flags=2
3859 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3860 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3861 short_channel_id: 4,
3863 message_flags: 1, // Only must_be_one
3864 channel_flags: 2, // to disable
3865 cltv_expiry_delta: 0,
3866 htlc_minimum_msat: 0,
3867 htlc_maximum_msat: MAX_VALUE_MSAT,
3869 fee_proportional_millionths: 0,
3870 excess_data: Vec::new()
3872 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3873 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3874 short_channel_id: 12,
3876 message_flags: 1, // Only must_be_one
3877 channel_flags: 2, // to disable
3878 cltv_expiry_delta: 0,
3879 htlc_minimum_msat: 0,
3880 htlc_maximum_msat: MAX_VALUE_MSAT,
3882 fee_proportional_millionths: 0,
3883 excess_data: Vec::new()
3886 // If all the channels require some features we don't understand, route should fail
3887 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3888 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3889 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3890 &Default::default(), &random_seed_bytes) {
3891 assert_eq!(err, "Failed to find a path to the given destination");
3892 } else { panic!(); }
3894 // If we specify a channel to node7, that overrides our local channel view and that gets used
3895 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3896 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3897 route_params.payment_params.max_path_length = 2;
3898 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3899 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3900 &Default::default(), &random_seed_bytes).unwrap();
3901 assert_eq!(route.paths[0].hops.len(), 2);
3903 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3904 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3905 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3906 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3907 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3908 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3910 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3911 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3912 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3913 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3914 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3915 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3919 fn disable_node_test() {
3920 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3921 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3922 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3923 let scorer = ln_test_utils::TestScorer::new();
3924 let random_seed_bytes = [42; 32];
3926 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3927 let mut unknown_features = NodeFeatures::empty();
3928 unknown_features.set_unknown_feature_required();
3929 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3930 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3931 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3933 // If all nodes require some features we don't understand, route should fail
3934 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3935 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3936 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3937 &Default::default(), &random_seed_bytes) {
3938 assert_eq!(err, "Failed to find a path to the given destination");
3939 } else { panic!(); }
3941 // If we specify a channel to node7, that overrides our local channel view and that gets used
3942 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3943 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3944 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3945 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3946 &Default::default(), &random_seed_bytes).unwrap();
3947 assert_eq!(route.paths[0].hops.len(), 2);
3949 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3950 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3951 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3952 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3953 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3954 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3956 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3957 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3958 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3959 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3960 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3961 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3963 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3964 // naively) assume that the user checked the feature bits on the invoice, which override
3965 // the node_announcement.
3969 fn our_chans_test() {
3970 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3971 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3972 let scorer = ln_test_utils::TestScorer::new();
3973 let random_seed_bytes = [42; 32];
3975 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3976 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3977 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3978 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3979 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3980 assert_eq!(route.paths[0].hops.len(), 3);
3982 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3983 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3984 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3985 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3986 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3987 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3989 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3990 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3991 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3992 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3993 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3994 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3996 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3997 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3998 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3999 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
4000 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
4001 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
4003 // If we specify a channel to node7, that overrides our local channel view and that gets used
4004 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4005 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4006 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
4007 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4008 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4009 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4010 &Default::default(), &random_seed_bytes).unwrap();
4011 assert_eq!(route.paths[0].hops.len(), 2);
4013 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
4014 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4015 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4016 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
4017 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4018 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4020 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4021 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
4022 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4023 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4024 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4025 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
4028 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4029 let zero_fees = RoutingFees {
4031 proportional_millionths: 0,
4033 vec![RouteHint(vec![RouteHintHop {
4034 src_node_id: nodes[3],
4035 short_channel_id: 8,
4037 cltv_expiry_delta: (8 << 4) | 1,
4038 htlc_minimum_msat: None,
4039 htlc_maximum_msat: None,
4041 ]), RouteHint(vec![RouteHintHop {
4042 src_node_id: nodes[4],
4043 short_channel_id: 9,
4046 proportional_millionths: 0,
4048 cltv_expiry_delta: (9 << 4) | 1,
4049 htlc_minimum_msat: None,
4050 htlc_maximum_msat: None,
4051 }]), RouteHint(vec![RouteHintHop {
4052 src_node_id: nodes[5],
4053 short_channel_id: 10,
4055 cltv_expiry_delta: (10 << 4) | 1,
4056 htlc_minimum_msat: None,
4057 htlc_maximum_msat: None,
4061 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4062 let zero_fees = RoutingFees {
4064 proportional_millionths: 0,
4066 vec![RouteHint(vec![RouteHintHop {
4067 src_node_id: nodes[2],
4068 short_channel_id: 5,
4071 proportional_millionths: 0,
4073 cltv_expiry_delta: (5 << 4) | 1,
4074 htlc_minimum_msat: None,
4075 htlc_maximum_msat: None,
4077 src_node_id: nodes[3],
4078 short_channel_id: 8,
4080 cltv_expiry_delta: (8 << 4) | 1,
4081 htlc_minimum_msat: None,
4082 htlc_maximum_msat: None,
4084 ]), RouteHint(vec![RouteHintHop {
4085 src_node_id: nodes[4],
4086 short_channel_id: 9,
4089 proportional_millionths: 0,
4091 cltv_expiry_delta: (9 << 4) | 1,
4092 htlc_minimum_msat: None,
4093 htlc_maximum_msat: None,
4094 }]), RouteHint(vec![RouteHintHop {
4095 src_node_id: nodes[5],
4096 short_channel_id: 10,
4098 cltv_expiry_delta: (10 << 4) | 1,
4099 htlc_minimum_msat: None,
4100 htlc_maximum_msat: None,
4105 fn partial_route_hint_test() {
4106 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4107 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4108 let scorer = ln_test_utils::TestScorer::new();
4109 let random_seed_bytes = [42; 32];
4111 // Simple test across 2, 3, 5, and 4 via a last_hop channel
4112 // Tests the behaviour when the RouteHint contains a suboptimal hop.
4113 // RouteHint may be partially used by the algo to build the best path.
4115 // First check that last hop can't have its source as the payee.
4116 let invalid_last_hop = RouteHint(vec![RouteHintHop {
4117 src_node_id: nodes[6],
4118 short_channel_id: 8,
4121 proportional_millionths: 0,
4123 cltv_expiry_delta: (8 << 4) | 1,
4124 htlc_minimum_msat: None,
4125 htlc_maximum_msat: None,
4128 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
4129 invalid_last_hops.push(invalid_last_hop);
4131 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4132 .with_route_hints(invalid_last_hops).unwrap();
4133 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4134 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
4135 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
4136 &Default::default(), &random_seed_bytes) {
4137 assert_eq!(err, "Route hint cannot have the payee as the source.");
4138 } else { panic!(); }
4141 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4142 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
4143 payment_params.max_path_length = 5;
4144 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4145 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4146 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4147 assert_eq!(route.paths[0].hops.len(), 5);
4149 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4150 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4151 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4152 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4153 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4154 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4156 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4157 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4158 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4159 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4160 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4161 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4163 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4164 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4165 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4166 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4167 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4168 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4170 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4171 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4172 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4173 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4174 // If we have a peer in the node map, we'll use their features here since we don't have
4175 // a way of figuring out their features from the invoice:
4176 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4177 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4179 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4180 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4181 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4182 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4183 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4184 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4187 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4188 let zero_fees = RoutingFees {
4190 proportional_millionths: 0,
4192 vec![RouteHint(vec![RouteHintHop {
4193 src_node_id: nodes[3],
4194 short_channel_id: 8,
4196 cltv_expiry_delta: (8 << 4) | 1,
4197 htlc_minimum_msat: None,
4198 htlc_maximum_msat: None,
4199 }]), RouteHint(vec![
4201 ]), RouteHint(vec![RouteHintHop {
4202 src_node_id: nodes[5],
4203 short_channel_id: 10,
4205 cltv_expiry_delta: (10 << 4) | 1,
4206 htlc_minimum_msat: None,
4207 htlc_maximum_msat: None,
4212 fn ignores_empty_last_hops_test() {
4213 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4214 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4215 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
4216 let scorer = ln_test_utils::TestScorer::new();
4217 let random_seed_bytes = [42; 32];
4219 // Test handling of an empty RouteHint passed in Invoice.
4220 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4221 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4222 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4223 assert_eq!(route.paths[0].hops.len(), 5);
4225 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4226 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4227 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4228 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4229 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4230 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4232 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4233 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4234 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4235 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4236 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4237 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4239 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4240 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4241 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4242 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4243 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4244 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4246 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4247 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4248 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4249 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4250 // If we have a peer in the node map, we'll use their features here since we don't have
4251 // a way of figuring out their features from the invoice:
4252 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4253 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4255 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4256 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4257 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4258 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4259 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4260 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4263 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
4265 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
4266 let zero_fees = RoutingFees {
4268 proportional_millionths: 0,
4270 vec![RouteHint(vec![RouteHintHop {
4271 src_node_id: hint_hops[0],
4272 short_channel_id: 0xff00,
4275 proportional_millionths: 0,
4277 cltv_expiry_delta: (5 << 4) | 1,
4278 htlc_minimum_msat: None,
4279 htlc_maximum_msat: None,
4281 src_node_id: hint_hops[1],
4282 short_channel_id: 0xff01,
4284 cltv_expiry_delta: (8 << 4) | 1,
4285 htlc_minimum_msat: None,
4286 htlc_maximum_msat: None,
4291 fn multi_hint_last_hops_test() {
4292 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4293 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4294 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
4295 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4296 let scorer = ln_test_utils::TestScorer::new();
4297 let random_seed_bytes = [42; 32];
4299 // Test through channels 2, 3, 0xff00, 0xff01.
4300 // Test shows that multi-hop route hints are considered and factored correctly into the
4303 // Disabling channels 6 & 7 by flags=2
4304 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4305 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4306 short_channel_id: 6,
4308 message_flags: 1, // Only must_be_one
4309 channel_flags: 2, // to disable
4310 cltv_expiry_delta: 0,
4311 htlc_minimum_msat: 0,
4312 htlc_maximum_msat: MAX_VALUE_MSAT,
4314 fee_proportional_millionths: 0,
4315 excess_data: Vec::new()
4317 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4318 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4319 short_channel_id: 7,
4321 message_flags: 1, // Only must_be_one
4322 channel_flags: 2, // to disable
4323 cltv_expiry_delta: 0,
4324 htlc_minimum_msat: 0,
4325 htlc_maximum_msat: MAX_VALUE_MSAT,
4327 fee_proportional_millionths: 0,
4328 excess_data: Vec::new()
4331 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4332 route_params.payment_params.max_path_length = 4;
4333 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4334 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4335 assert_eq!(route.paths[0].hops.len(), 4);
4337 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4338 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4339 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4340 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4341 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4342 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4344 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4345 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4346 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4347 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4348 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4349 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4351 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4352 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4353 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4354 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4355 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4356 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4358 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4359 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4360 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4361 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4362 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4363 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4364 route_params.payment_params.max_path_length = 3;
4365 get_route(&our_id, &route_params, &network_graph.read_only(), None,
4366 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap_err();
4370 fn private_multi_hint_last_hops_test() {
4371 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4372 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4374 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4375 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4377 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4378 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4379 let scorer = ln_test_utils::TestScorer::new();
4380 // Test through channels 2, 3, 0xff00, 0xff01.
4381 // Test shows that multiple hop hints are considered.
4383 // Disabling channels 6 & 7 by flags=2
4384 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4385 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4386 short_channel_id: 6,
4388 message_flags: 1, // Only must_be_one
4389 channel_flags: 2, // to disable
4390 cltv_expiry_delta: 0,
4391 htlc_minimum_msat: 0,
4392 htlc_maximum_msat: MAX_VALUE_MSAT,
4394 fee_proportional_millionths: 0,
4395 excess_data: Vec::new()
4397 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4398 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4399 short_channel_id: 7,
4401 message_flags: 1, // Only must_be_one
4402 channel_flags: 2, // to disable
4403 cltv_expiry_delta: 0,
4404 htlc_minimum_msat: 0,
4405 htlc_maximum_msat: MAX_VALUE_MSAT,
4407 fee_proportional_millionths: 0,
4408 excess_data: Vec::new()
4411 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4412 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4413 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4414 assert_eq!(route.paths[0].hops.len(), 4);
4416 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4417 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4418 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4419 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4420 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4421 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4423 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4424 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4425 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4426 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4427 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4428 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4430 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4431 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4432 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4433 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4434 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4435 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4437 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4438 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4439 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4440 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4441 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4442 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4445 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4446 let zero_fees = RoutingFees {
4448 proportional_millionths: 0,
4450 vec![RouteHint(vec![RouteHintHop {
4451 src_node_id: nodes[4],
4452 short_channel_id: 11,
4454 cltv_expiry_delta: (11 << 4) | 1,
4455 htlc_minimum_msat: None,
4456 htlc_maximum_msat: None,
4458 src_node_id: nodes[3],
4459 short_channel_id: 8,
4461 cltv_expiry_delta: (8 << 4) | 1,
4462 htlc_minimum_msat: None,
4463 htlc_maximum_msat: None,
4464 }]), RouteHint(vec![RouteHintHop {
4465 src_node_id: nodes[4],
4466 short_channel_id: 9,
4469 proportional_millionths: 0,
4471 cltv_expiry_delta: (9 << 4) | 1,
4472 htlc_minimum_msat: None,
4473 htlc_maximum_msat: None,
4474 }]), RouteHint(vec![RouteHintHop {
4475 src_node_id: nodes[5],
4476 short_channel_id: 10,
4478 cltv_expiry_delta: (10 << 4) | 1,
4479 htlc_minimum_msat: None,
4480 htlc_maximum_msat: None,
4485 fn last_hops_with_public_channel_test() {
4486 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4487 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4488 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4489 let scorer = ln_test_utils::TestScorer::new();
4490 let random_seed_bytes = [42; 32];
4492 // This test shows that public routes can be present in the invoice
4493 // which would be handled in the same manner.
4495 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4496 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4497 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4498 assert_eq!(route.paths[0].hops.len(), 5);
4500 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4501 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4502 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4503 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4504 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4505 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4507 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4508 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4509 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4510 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4511 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4512 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4514 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4515 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4516 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4517 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4518 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4519 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4521 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4522 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4523 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4524 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4525 // If we have a peer in the node map, we'll use their features here since we don't have
4526 // a way of figuring out their features from the invoice:
4527 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4528 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4530 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4531 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4532 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4533 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4534 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4535 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4539 fn our_chans_last_hop_connect_test() {
4540 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4541 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4542 let scorer = ln_test_utils::TestScorer::new();
4543 let random_seed_bytes = [42; 32];
4545 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4546 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4547 let mut last_hops = last_hops(&nodes);
4548 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4549 .with_route_hints(last_hops.clone()).unwrap();
4550 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4551 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4552 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4553 &Default::default(), &random_seed_bytes).unwrap();
4554 assert_eq!(route.paths[0].hops.len(), 2);
4556 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4557 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4558 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4559 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4560 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4561 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4563 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4564 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4565 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4566 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4567 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4568 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4570 last_hops[0].0[0].fees.base_msat = 1000;
4572 // Revert to via 6 as the fee on 8 goes up
4573 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4574 .with_route_hints(last_hops).unwrap();
4575 let route_params = RouteParameters::from_payment_params_and_value(
4576 payment_params.clone(), 100);
4577 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4578 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4579 assert_eq!(route.paths[0].hops.len(), 4);
4581 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4582 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4583 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4584 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4585 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4586 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4588 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4589 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4590 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4591 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4592 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4593 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4595 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4596 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4597 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4598 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4599 // If we have a peer in the node map, we'll use their features here since we don't have
4600 // a way of figuring out their features from the invoice:
4601 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4602 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4604 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4605 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4606 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4607 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4608 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4609 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4611 // ...but still use 8 for larger payments as 6 has a variable feerate
4612 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4613 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4614 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4615 assert_eq!(route.paths[0].hops.len(), 5);
4617 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4618 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4619 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4620 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4621 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4622 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4624 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4625 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4626 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4627 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4628 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4629 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4631 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4632 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4633 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4634 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4635 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4636 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4638 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4639 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4640 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4641 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4642 // If we have a peer in the node map, we'll use their features here since we don't have
4643 // a way of figuring out their features from the invoice:
4644 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4645 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4647 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4648 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4649 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4650 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4651 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4652 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4655 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> {
4656 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4657 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4658 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4660 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4661 let last_hops = RouteHint(vec![RouteHintHop {
4662 src_node_id: middle_node_id,
4663 short_channel_id: 8,
4666 proportional_millionths: last_hop_fee_prop,
4668 cltv_expiry_delta: (8 << 4) | 1,
4669 htlc_minimum_msat: None,
4670 htlc_maximum_msat: last_hop_htlc_max,
4672 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4673 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4674 let scorer = ln_test_utils::TestScorer::new();
4675 let random_seed_bytes = [42; 32];
4676 let logger = ln_test_utils::TestLogger::new();
4677 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4678 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4679 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4680 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4681 &random_seed_bytes);
4686 fn unannounced_path_test() {
4687 // We should be able to send a payment to a destination without any help of a routing graph
4688 // if we have a channel with a common counterparty that appears in the first and last hop
4690 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4692 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4693 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4694 assert_eq!(route.paths[0].hops.len(), 2);
4696 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4697 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4698 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4699 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4700 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4701 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4703 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4704 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4705 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4706 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4707 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4708 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4712 fn overflow_unannounced_path_test_liquidity_underflow() {
4713 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4714 // the last-hop had a fee which overflowed a u64, we'd panic.
4715 // This was due to us adding the first-hop from us unconditionally, causing us to think
4716 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4717 // In this test, we previously hit a subtraction underflow due to having less available
4718 // liquidity at the last hop than 0.
4719 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());
4723 fn overflow_unannounced_path_test_feerate_overflow() {
4724 // This tests for the same case as above, except instead of hitting a subtraction
4725 // underflow, we hit a case where the fee charged at a hop overflowed.
4726 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());
4730 fn available_amount_while_routing_test() {
4731 // Tests whether we choose the correct available channel amount while routing.
4733 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4734 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4735 let scorer = ln_test_utils::TestScorer::new();
4736 let random_seed_bytes = [42; 32];
4737 let config = UserConfig::default();
4738 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4739 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4742 // We will use a simple single-path route from
4743 // our node to node2 via node0: channels {1, 3}.
4745 // First disable all other paths.
4746 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4747 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4748 short_channel_id: 2,
4750 message_flags: 1, // Only must_be_one
4752 cltv_expiry_delta: 0,
4753 htlc_minimum_msat: 0,
4754 htlc_maximum_msat: 100_000,
4756 fee_proportional_millionths: 0,
4757 excess_data: Vec::new()
4759 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4760 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4761 short_channel_id: 12,
4763 message_flags: 1, // Only must_be_one
4765 cltv_expiry_delta: 0,
4766 htlc_minimum_msat: 0,
4767 htlc_maximum_msat: 100_000,
4769 fee_proportional_millionths: 0,
4770 excess_data: Vec::new()
4773 // Make the first channel (#1) very permissive,
4774 // and we will be testing all limits on the second channel.
4775 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4776 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4777 short_channel_id: 1,
4779 message_flags: 1, // Only must_be_one
4781 cltv_expiry_delta: 0,
4782 htlc_minimum_msat: 0,
4783 htlc_maximum_msat: 1_000_000_000,
4785 fee_proportional_millionths: 0,
4786 excess_data: Vec::new()
4789 // First, let's see if routing works if we have absolutely no idea about the available amount.
4790 // In this case, it should be set to 250_000 sats.
4791 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4792 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4793 short_channel_id: 3,
4795 message_flags: 1, // Only must_be_one
4797 cltv_expiry_delta: 0,
4798 htlc_minimum_msat: 0,
4799 htlc_maximum_msat: 250_000_000,
4801 fee_proportional_millionths: 0,
4802 excess_data: Vec::new()
4806 // Attempt to route more than available results in a failure.
4807 let route_params = RouteParameters::from_payment_params_and_value(
4808 payment_params.clone(), 250_000_001);
4809 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4810 &our_id, &route_params, &network_graph.read_only(), None,
4811 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4812 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4813 } else { panic!(); }
4817 // Now, attempt to route an exact amount we have should be fine.
4818 let route_params = RouteParameters::from_payment_params_and_value(
4819 payment_params.clone(), 250_000_000);
4820 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4821 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4822 assert_eq!(route.paths.len(), 1);
4823 let path = route.paths.last().unwrap();
4824 assert_eq!(path.hops.len(), 2);
4825 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4826 assert_eq!(path.final_value_msat(), 250_000_000);
4829 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4830 // Disable channel #1 and use another first hop.
4831 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4832 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4833 short_channel_id: 1,
4835 message_flags: 1, // Only must_be_one
4837 cltv_expiry_delta: 0,
4838 htlc_minimum_msat: 0,
4839 htlc_maximum_msat: 1_000_000_000,
4841 fee_proportional_millionths: 0,
4842 excess_data: Vec::new()
4845 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4846 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4849 // Attempt to route more than available results in a failure.
4850 let route_params = RouteParameters::from_payment_params_and_value(
4851 payment_params.clone(), 200_000_001);
4852 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4853 &our_id, &route_params, &network_graph.read_only(),
4854 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4855 &Default::default(), &random_seed_bytes) {
4856 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4857 } else { panic!(); }
4861 // Now, attempt to route an exact amount we have should be fine.
4862 let route_params = RouteParameters::from_payment_params_and_value(
4863 payment_params.clone(), 200_000_000);
4864 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4865 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4866 &Default::default(), &random_seed_bytes).unwrap();
4867 assert_eq!(route.paths.len(), 1);
4868 let path = route.paths.last().unwrap();
4869 assert_eq!(path.hops.len(), 2);
4870 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4871 assert_eq!(path.final_value_msat(), 200_000_000);
4874 // Enable channel #1 back.
4875 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4876 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4877 short_channel_id: 1,
4879 message_flags: 1, // Only must_be_one
4881 cltv_expiry_delta: 0,
4882 htlc_minimum_msat: 0,
4883 htlc_maximum_msat: 1_000_000_000,
4885 fee_proportional_millionths: 0,
4886 excess_data: Vec::new()
4890 // Now let's see if routing works if we know only htlc_maximum_msat.
4891 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4892 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4893 short_channel_id: 3,
4895 message_flags: 1, // Only must_be_one
4897 cltv_expiry_delta: 0,
4898 htlc_minimum_msat: 0,
4899 htlc_maximum_msat: 15_000,
4901 fee_proportional_millionths: 0,
4902 excess_data: Vec::new()
4906 // Attempt to route more than available results in a failure.
4907 let route_params = RouteParameters::from_payment_params_and_value(
4908 payment_params.clone(), 15_001);
4909 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4910 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4911 &scorer, &Default::default(), &random_seed_bytes) {
4912 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4913 } else { panic!(); }
4917 // Now, attempt to route an exact amount we have should be fine.
4918 let route_params = RouteParameters::from_payment_params_and_value(
4919 payment_params.clone(), 15_000);
4920 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4921 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4922 assert_eq!(route.paths.len(), 1);
4923 let path = route.paths.last().unwrap();
4924 assert_eq!(path.hops.len(), 2);
4925 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4926 assert_eq!(path.final_value_msat(), 15_000);
4929 // Now let's see if routing works if we know only capacity from the UTXO.
4931 // We can't change UTXO capacity on the fly, so we'll disable
4932 // the existing channel and add another one with the capacity we need.
4933 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4934 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4935 short_channel_id: 3,
4937 message_flags: 1, // Only must_be_one
4939 cltv_expiry_delta: 0,
4940 htlc_minimum_msat: 0,
4941 htlc_maximum_msat: MAX_VALUE_MSAT,
4943 fee_proportional_millionths: 0,
4944 excess_data: Vec::new()
4947 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4948 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4949 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4950 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4951 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_p2wsh();
4953 *chain_monitor.utxo_ret.lock().unwrap() =
4954 UtxoResult::Sync(Ok(TxOut { value: Amount::from_sat(15), script_pubkey: good_script.clone() }));
4955 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4957 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4958 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4959 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4960 short_channel_id: 333,
4962 message_flags: 1, // Only must_be_one
4964 cltv_expiry_delta: (3 << 4) | 1,
4965 htlc_minimum_msat: 0,
4966 htlc_maximum_msat: 15_000,
4968 fee_proportional_millionths: 0,
4969 excess_data: Vec::new()
4971 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4972 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4973 short_channel_id: 333,
4975 message_flags: 1, // Only must_be_one
4977 cltv_expiry_delta: (3 << 4) | 2,
4978 htlc_minimum_msat: 0,
4979 htlc_maximum_msat: 15_000,
4981 fee_proportional_millionths: 0,
4982 excess_data: Vec::new()
4986 // Attempt to route more than available results in a failure.
4987 let route_params = RouteParameters::from_payment_params_and_value(
4988 payment_params.clone(), 15_001);
4989 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4990 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4991 &scorer, &Default::default(), &random_seed_bytes) {
4992 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4993 } else { panic!(); }
4997 // Now, attempt to route an exact amount we have should be fine.
4998 let route_params = RouteParameters::from_payment_params_and_value(
4999 payment_params.clone(), 15_000);
5000 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5001 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5002 assert_eq!(route.paths.len(), 1);
5003 let path = route.paths.last().unwrap();
5004 assert_eq!(path.hops.len(), 2);
5005 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5006 assert_eq!(path.final_value_msat(), 15_000);
5009 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
5010 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5011 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5012 short_channel_id: 333,
5014 message_flags: 1, // Only must_be_one
5016 cltv_expiry_delta: 0,
5017 htlc_minimum_msat: 0,
5018 htlc_maximum_msat: 10_000,
5020 fee_proportional_millionths: 0,
5021 excess_data: Vec::new()
5025 // Attempt to route more than available results in a failure.
5026 let route_params = RouteParameters::from_payment_params_and_value(
5027 payment_params.clone(), 10_001);
5028 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5029 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5030 &scorer, &Default::default(), &random_seed_bytes) {
5031 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5032 } else { panic!(); }
5036 // Now, attempt to route an exact amount we have should be fine.
5037 let route_params = RouteParameters::from_payment_params_and_value(
5038 payment_params.clone(), 10_000);
5039 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5040 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5041 assert_eq!(route.paths.len(), 1);
5042 let path = route.paths.last().unwrap();
5043 assert_eq!(path.hops.len(), 2);
5044 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5045 assert_eq!(path.final_value_msat(), 10_000);
5050 fn available_liquidity_last_hop_test() {
5051 // Check that available liquidity properly limits the path even when only
5052 // one of the latter hops is limited.
5053 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5054 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5055 let scorer = ln_test_utils::TestScorer::new();
5056 let random_seed_bytes = [42; 32];
5057 let config = UserConfig::default();
5058 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5059 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5062 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5063 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
5064 // Total capacity: 50 sats.
5066 // Disable other potential paths.
5067 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5068 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5069 short_channel_id: 2,
5071 message_flags: 1, // Only must_be_one
5073 cltv_expiry_delta: 0,
5074 htlc_minimum_msat: 0,
5075 htlc_maximum_msat: 100_000,
5077 fee_proportional_millionths: 0,
5078 excess_data: Vec::new()
5080 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5081 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5082 short_channel_id: 7,
5084 message_flags: 1, // Only must_be_one
5086 cltv_expiry_delta: 0,
5087 htlc_minimum_msat: 0,
5088 htlc_maximum_msat: 100_000,
5090 fee_proportional_millionths: 0,
5091 excess_data: Vec::new()
5096 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5097 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5098 short_channel_id: 12,
5100 message_flags: 1, // Only must_be_one
5102 cltv_expiry_delta: 0,
5103 htlc_minimum_msat: 0,
5104 htlc_maximum_msat: 100_000,
5106 fee_proportional_millionths: 0,
5107 excess_data: Vec::new()
5109 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5110 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5111 short_channel_id: 13,
5113 message_flags: 1, // Only must_be_one
5115 cltv_expiry_delta: 0,
5116 htlc_minimum_msat: 0,
5117 htlc_maximum_msat: 100_000,
5119 fee_proportional_millionths: 0,
5120 excess_data: Vec::new()
5123 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5124 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5125 short_channel_id: 6,
5127 message_flags: 1, // Only must_be_one
5129 cltv_expiry_delta: 0,
5130 htlc_minimum_msat: 0,
5131 htlc_maximum_msat: 50_000,
5133 fee_proportional_millionths: 0,
5134 excess_data: Vec::new()
5136 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5137 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5138 short_channel_id: 11,
5140 message_flags: 1, // Only must_be_one
5142 cltv_expiry_delta: 0,
5143 htlc_minimum_msat: 0,
5144 htlc_maximum_msat: 100_000,
5146 fee_proportional_millionths: 0,
5147 excess_data: Vec::new()
5150 // Attempt to route more than available results in a failure.
5151 let route_params = RouteParameters::from_payment_params_and_value(
5152 payment_params.clone(), 60_000);
5153 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5154 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5155 &scorer, &Default::default(), &random_seed_bytes) {
5156 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5157 } else { panic!(); }
5161 // Now, attempt to route 49 sats (just a bit below the capacity).
5162 let route_params = RouteParameters::from_payment_params_and_value(
5163 payment_params.clone(), 49_000);
5164 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5165 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5166 assert_eq!(route.paths.len(), 1);
5167 let mut total_amount_paid_msat = 0;
5168 for path in &route.paths {
5169 assert_eq!(path.hops.len(), 4);
5170 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5171 total_amount_paid_msat += path.final_value_msat();
5173 assert_eq!(total_amount_paid_msat, 49_000);
5177 // Attempt to route an exact amount is also fine
5178 let route_params = RouteParameters::from_payment_params_and_value(
5179 payment_params, 50_000);
5180 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5181 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5182 assert_eq!(route.paths.len(), 1);
5183 let mut total_amount_paid_msat = 0;
5184 for path in &route.paths {
5185 assert_eq!(path.hops.len(), 4);
5186 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5187 total_amount_paid_msat += path.final_value_msat();
5189 assert_eq!(total_amount_paid_msat, 50_000);
5194 fn ignore_fee_first_hop_test() {
5195 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5196 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5197 let scorer = ln_test_utils::TestScorer::new();
5198 let random_seed_bytes = [42; 32];
5199 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5201 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5202 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5203 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5204 short_channel_id: 1,
5206 message_flags: 1, // Only must_be_one
5208 cltv_expiry_delta: 0,
5209 htlc_minimum_msat: 0,
5210 htlc_maximum_msat: 100_000,
5211 fee_base_msat: 1_000_000,
5212 fee_proportional_millionths: 0,
5213 excess_data: Vec::new()
5215 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5216 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5217 short_channel_id: 3,
5219 message_flags: 1, // Only must_be_one
5221 cltv_expiry_delta: 0,
5222 htlc_minimum_msat: 0,
5223 htlc_maximum_msat: 50_000,
5225 fee_proportional_millionths: 0,
5226 excess_data: Vec::new()
5230 let route_params = RouteParameters::from_payment_params_and_value(
5231 payment_params, 50_000);
5232 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5233 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5234 assert_eq!(route.paths.len(), 1);
5235 let mut total_amount_paid_msat = 0;
5236 for path in &route.paths {
5237 assert_eq!(path.hops.len(), 2);
5238 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5239 total_amount_paid_msat += path.final_value_msat();
5241 assert_eq!(total_amount_paid_msat, 50_000);
5246 fn simple_mpp_route_test() {
5247 let (secp_ctx, _, _, _, _) = build_graph();
5248 let (_, _, _, nodes) = get_nodes(&secp_ctx);
5249 let config = UserConfig::default();
5250 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5251 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5253 do_simple_mpp_route_test(clear_payment_params);
5255 // MPP to a 1-hop blinded path for nodes[2]
5256 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
5257 let blinded_path = BlindedPath {
5258 introduction_node: IntroductionNode::NodeId(nodes[2]),
5259 blinding_point: ln_test_utils::pubkey(42),
5260 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
5262 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
5264 fee_proportional_millionths: 0,
5265 htlc_minimum_msat: 0,
5266 htlc_maximum_msat: 0,
5267 cltv_expiry_delta: 0,
5268 features: BlindedHopFeatures::empty(),
5270 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
5271 .with_bolt12_features(bolt12_features.clone()).unwrap();
5272 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
5274 // MPP to 3 2-hop blinded paths
5275 let mut blinded_path_node_0 = blinded_path.clone();
5276 blinded_path_node_0.introduction_node = IntroductionNode::NodeId(nodes[0]);
5277 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
5278 let mut node_0_payinfo = blinded_payinfo.clone();
5279 node_0_payinfo.htlc_maximum_msat = 50_000;
5281 let mut blinded_path_node_7 = blinded_path_node_0.clone();
5282 blinded_path_node_7.introduction_node = IntroductionNode::NodeId(nodes[7]);
5283 let mut node_7_payinfo = blinded_payinfo.clone();
5284 node_7_payinfo.htlc_maximum_msat = 60_000;
5286 let mut blinded_path_node_1 = blinded_path_node_0.clone();
5287 blinded_path_node_1.introduction_node = IntroductionNode::NodeId(nodes[1]);
5288 let mut node_1_payinfo = blinded_payinfo.clone();
5289 node_1_payinfo.htlc_maximum_msat = 180_000;
5291 let two_hop_blinded_payment_params = PaymentParameters::blinded(
5293 (node_0_payinfo, blinded_path_node_0),
5294 (node_7_payinfo, blinded_path_node_7),
5295 (node_1_payinfo, blinded_path_node_1)
5297 .with_bolt12_features(bolt12_features).unwrap();
5298 do_simple_mpp_route_test(two_hop_blinded_payment_params);
5302 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
5303 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5304 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5305 let scorer = ln_test_utils::TestScorer::new();
5306 let random_seed_bytes = [42; 32];
5308 // We need a route consisting of 3 paths:
5309 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5310 // To achieve this, the amount being transferred should be around
5311 // the total capacity of these 3 paths.
5313 // First, we set limits on these (previously unlimited) channels.
5314 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
5316 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5317 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5318 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5319 short_channel_id: 1,
5321 message_flags: 1, // Only must_be_one
5323 cltv_expiry_delta: 0,
5324 htlc_minimum_msat: 0,
5325 htlc_maximum_msat: 100_000,
5327 fee_proportional_millionths: 0,
5328 excess_data: Vec::new()
5330 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5331 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5332 short_channel_id: 3,
5334 message_flags: 1, // Only must_be_one
5336 cltv_expiry_delta: 0,
5337 htlc_minimum_msat: 0,
5338 htlc_maximum_msat: 50_000,
5340 fee_proportional_millionths: 0,
5341 excess_data: Vec::new()
5344 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
5345 // (total limit 60).
5346 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5347 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5348 short_channel_id: 12,
5350 message_flags: 1, // Only must_be_one
5352 cltv_expiry_delta: 0,
5353 htlc_minimum_msat: 0,
5354 htlc_maximum_msat: 60_000,
5356 fee_proportional_millionths: 0,
5357 excess_data: Vec::new()
5359 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5360 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5361 short_channel_id: 13,
5363 message_flags: 1, // Only must_be_one
5365 cltv_expiry_delta: 0,
5366 htlc_minimum_msat: 0,
5367 htlc_maximum_msat: 60_000,
5369 fee_proportional_millionths: 0,
5370 excess_data: Vec::new()
5373 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5374 // (total capacity 180 sats).
5375 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5376 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5377 short_channel_id: 2,
5379 message_flags: 1, // Only must_be_one
5381 cltv_expiry_delta: 0,
5382 htlc_minimum_msat: 0,
5383 htlc_maximum_msat: 200_000,
5385 fee_proportional_millionths: 0,
5386 excess_data: Vec::new()
5388 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5389 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5390 short_channel_id: 4,
5392 message_flags: 1, // Only must_be_one
5394 cltv_expiry_delta: 0,
5395 htlc_minimum_msat: 0,
5396 htlc_maximum_msat: 180_000,
5398 fee_proportional_millionths: 0,
5399 excess_data: Vec::new()
5403 // Attempt to route more than available results in a failure.
5404 let route_params = RouteParameters::from_payment_params_and_value(
5405 payment_params.clone(), 300_000);
5406 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5407 &our_id, &route_params, &network_graph.read_only(), None,
5408 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5409 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5410 } else { panic!(); }
5414 // Attempt to route while setting max_path_count to 0 results in a failure.
5415 let zero_payment_params = payment_params.clone().with_max_path_count(0);
5416 let route_params = RouteParameters::from_payment_params_and_value(
5417 zero_payment_params, 100);
5418 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5419 &our_id, &route_params, &network_graph.read_only(), None,
5420 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5421 assert_eq!(err, "Can't find a route with no paths allowed.");
5422 } else { panic!(); }
5426 // Attempt to route while setting max_path_count to 3 results in a failure.
5427 // This is the case because the minimal_value_contribution_msat would require each path
5428 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5429 let fail_payment_params = payment_params.clone().with_max_path_count(3);
5430 let route_params = RouteParameters::from_payment_params_and_value(
5431 fail_payment_params, 250_000);
5432 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5433 &our_id, &route_params, &network_graph.read_only(), None,
5434 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5435 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5436 } else { panic!(); }
5440 // Now, attempt to route 250 sats (just a bit below the capacity).
5441 // Our algorithm should provide us with these 3 paths.
5442 let route_params = RouteParameters::from_payment_params_and_value(
5443 payment_params.clone(), 250_000);
5444 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5445 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5446 assert_eq!(route.paths.len(), 3);
5447 let mut total_amount_paid_msat = 0;
5448 for path in &route.paths {
5449 if let Some(bt) = &path.blinded_tail {
5450 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5452 assert_eq!(path.hops.len(), 2);
5453 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5455 total_amount_paid_msat += path.final_value_msat();
5457 assert_eq!(total_amount_paid_msat, 250_000);
5461 // Attempt to route an exact amount is also fine
5462 let route_params = RouteParameters::from_payment_params_and_value(
5463 payment_params.clone(), 290_000);
5464 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5465 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5466 assert_eq!(route.paths.len(), 3);
5467 let mut total_amount_paid_msat = 0;
5468 for path in &route.paths {
5469 if payment_params.payee.blinded_route_hints().len() != 0 {
5470 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5471 if let Some(bt) = &path.blinded_tail {
5472 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5473 if bt.hops.len() > 1 {
5474 let network_graph = network_graph.read_only();
5476 NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
5477 payment_params.payee.blinded_route_hints().iter()
5478 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5479 .and_then(|(_, p)| p.public_introduction_node_id(&network_graph))
5484 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5487 assert_eq!(path.hops.len(), 2);
5488 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5490 total_amount_paid_msat += path.final_value_msat();
5492 assert_eq!(total_amount_paid_msat, 290_000);
5497 fn long_mpp_route_test() {
5498 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5499 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5500 let scorer = ln_test_utils::TestScorer::new();
5501 let random_seed_bytes = [42; 32];
5502 let config = UserConfig::default();
5503 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5504 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5507 // We need a route consisting of 3 paths:
5508 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5509 // Note that these paths overlap (channels 5, 12, 13).
5510 // We will route 300 sats.
5511 // Each path will have 100 sats capacity, those channels which
5512 // are used twice will have 200 sats capacity.
5514 // Disable other potential paths.
5515 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5516 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5517 short_channel_id: 2,
5519 message_flags: 1, // Only must_be_one
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,
5532 message_flags: 1, // Only must_be_one
5534 cltv_expiry_delta: 0,
5535 htlc_minimum_msat: 0,
5536 htlc_maximum_msat: 100_000,
5538 fee_proportional_millionths: 0,
5539 excess_data: Vec::new()
5542 // Path via {node0, node2} is channels {1, 3, 5}.
5543 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5544 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5545 short_channel_id: 1,
5547 message_flags: 1, // Only must_be_one
5549 cltv_expiry_delta: 0,
5550 htlc_minimum_msat: 0,
5551 htlc_maximum_msat: 100_000,
5553 fee_proportional_millionths: 0,
5554 excess_data: Vec::new()
5556 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5557 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5558 short_channel_id: 3,
5560 message_flags: 1, // Only must_be_one
5562 cltv_expiry_delta: 0,
5563 htlc_minimum_msat: 0,
5564 htlc_maximum_msat: 100_000,
5566 fee_proportional_millionths: 0,
5567 excess_data: Vec::new()
5570 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5571 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5572 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5573 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5574 short_channel_id: 5,
5576 message_flags: 1, // Only must_be_one
5578 cltv_expiry_delta: 0,
5579 htlc_minimum_msat: 0,
5580 htlc_maximum_msat: 200_000,
5582 fee_proportional_millionths: 0,
5583 excess_data: Vec::new()
5585 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5586 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5587 short_channel_id: 5,
5589 message_flags: 1, // Only must_be_one
5590 channel_flags: 3, // disable direction 1
5591 cltv_expiry_delta: 0,
5592 htlc_minimum_msat: 0,
5593 htlc_maximum_msat: 200_000,
5595 fee_proportional_millionths: 0,
5596 excess_data: Vec::new()
5599 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5600 // Add 100 sats to the capacities of {12, 13}, because these channels
5601 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5602 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5603 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5604 short_channel_id: 12,
5606 message_flags: 1, // Only must_be_one
5608 cltv_expiry_delta: 0,
5609 htlc_minimum_msat: 0,
5610 htlc_maximum_msat: 200_000,
5612 fee_proportional_millionths: 0,
5613 excess_data: Vec::new()
5615 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5616 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5617 short_channel_id: 13,
5619 message_flags: 1, // Only must_be_one
5621 cltv_expiry_delta: 0,
5622 htlc_minimum_msat: 0,
5623 htlc_maximum_msat: 200_000,
5625 fee_proportional_millionths: 0,
5626 excess_data: Vec::new()
5629 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5630 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5631 short_channel_id: 6,
5633 message_flags: 1, // Only must_be_one
5635 cltv_expiry_delta: 0,
5636 htlc_minimum_msat: 0,
5637 htlc_maximum_msat: 100_000,
5639 fee_proportional_millionths: 0,
5640 excess_data: Vec::new()
5642 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5643 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5644 short_channel_id: 11,
5646 message_flags: 1, // Only must_be_one
5648 cltv_expiry_delta: 0,
5649 htlc_minimum_msat: 0,
5650 htlc_maximum_msat: 100_000,
5652 fee_proportional_millionths: 0,
5653 excess_data: Vec::new()
5656 // Path via {node7, node2} is channels {12, 13, 5}.
5657 // We already limited them to 200 sats (they are used twice for 100 sats).
5658 // Nothing to do here.
5661 // Attempt to route more than available results in a failure.
5662 let route_params = RouteParameters::from_payment_params_and_value(
5663 payment_params.clone(), 350_000);
5664 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5665 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5666 &scorer, &Default::default(), &random_seed_bytes) {
5667 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5668 } else { panic!(); }
5672 // Now, attempt to route 300 sats (exact amount we can route).
5673 // Our algorithm should provide us with these 3 paths, 100 sats each.
5674 let route_params = RouteParameters::from_payment_params_and_value(
5675 payment_params, 300_000);
5676 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5677 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5678 assert_eq!(route.paths.len(), 3);
5680 let mut total_amount_paid_msat = 0;
5681 for path in &route.paths {
5682 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5683 total_amount_paid_msat += path.final_value_msat();
5685 assert_eq!(total_amount_paid_msat, 300_000);
5691 fn mpp_cheaper_route_test() {
5692 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5693 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5694 let scorer = ln_test_utils::TestScorer::new();
5695 let random_seed_bytes = [42; 32];
5696 let config = UserConfig::default();
5697 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5698 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5701 // This test checks that if we have two cheaper paths and one more expensive path,
5702 // so that liquidity-wise any 2 of 3 combination is sufficient,
5703 // two cheaper paths will be taken.
5704 // These paths have equal available liquidity.
5706 // We need a combination of 3 paths:
5707 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5708 // Note that these paths overlap (channels 5, 12, 13).
5709 // Each path will have 100 sats capacity, those channels which
5710 // are used twice will have 200 sats capacity.
5712 // Disable other potential paths.
5713 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5714 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5715 short_channel_id: 2,
5717 message_flags: 1, // Only must_be_one
5719 cltv_expiry_delta: 0,
5720 htlc_minimum_msat: 0,
5721 htlc_maximum_msat: 100_000,
5723 fee_proportional_millionths: 0,
5724 excess_data: Vec::new()
5726 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5727 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5728 short_channel_id: 7,
5730 message_flags: 1, // Only must_be_one
5732 cltv_expiry_delta: 0,
5733 htlc_minimum_msat: 0,
5734 htlc_maximum_msat: 100_000,
5736 fee_proportional_millionths: 0,
5737 excess_data: Vec::new()
5740 // Path via {node0, node2} is channels {1, 3, 5}.
5741 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5742 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5743 short_channel_id: 1,
5745 message_flags: 1, // Only must_be_one
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()
5754 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5755 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5756 short_channel_id: 3,
5758 message_flags: 1, // Only must_be_one
5760 cltv_expiry_delta: 0,
5761 htlc_minimum_msat: 0,
5762 htlc_maximum_msat: 100_000,
5764 fee_proportional_millionths: 0,
5765 excess_data: Vec::new()
5768 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5769 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5770 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5771 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5772 short_channel_id: 5,
5774 message_flags: 1, // Only must_be_one
5776 cltv_expiry_delta: 0,
5777 htlc_minimum_msat: 0,
5778 htlc_maximum_msat: 200_000,
5780 fee_proportional_millionths: 0,
5781 excess_data: Vec::new()
5783 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5784 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5785 short_channel_id: 5,
5787 message_flags: 1, // Only must_be_one
5788 channel_flags: 3, // disable direction 1
5789 cltv_expiry_delta: 0,
5790 htlc_minimum_msat: 0,
5791 htlc_maximum_msat: 200_000,
5793 fee_proportional_millionths: 0,
5794 excess_data: Vec::new()
5797 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5798 // Add 100 sats to the capacities of {12, 13}, because these channels
5799 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5800 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5801 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5802 short_channel_id: 12,
5804 message_flags: 1, // Only must_be_one
5806 cltv_expiry_delta: 0,
5807 htlc_minimum_msat: 0,
5808 htlc_maximum_msat: 200_000,
5810 fee_proportional_millionths: 0,
5811 excess_data: Vec::new()
5813 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5814 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5815 short_channel_id: 13,
5817 message_flags: 1, // Only must_be_one
5819 cltv_expiry_delta: 0,
5820 htlc_minimum_msat: 0,
5821 htlc_maximum_msat: 200_000,
5823 fee_proportional_millionths: 0,
5824 excess_data: Vec::new()
5827 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5828 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5829 short_channel_id: 6,
5831 message_flags: 1, // Only must_be_one
5833 cltv_expiry_delta: 0,
5834 htlc_minimum_msat: 0,
5835 htlc_maximum_msat: 100_000,
5836 fee_base_msat: 1_000,
5837 fee_proportional_millionths: 0,
5838 excess_data: Vec::new()
5840 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5841 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5842 short_channel_id: 11,
5844 message_flags: 1, // Only must_be_one
5846 cltv_expiry_delta: 0,
5847 htlc_minimum_msat: 0,
5848 htlc_maximum_msat: 100_000,
5850 fee_proportional_millionths: 0,
5851 excess_data: Vec::new()
5854 // Path via {node7, node2} is channels {12, 13, 5}.
5855 // We already limited them to 200 sats (they are used twice for 100 sats).
5856 // Nothing to do here.
5859 // Now, attempt to route 180 sats.
5860 // Our algorithm should provide us with these 2 paths.
5861 let route_params = RouteParameters::from_payment_params_and_value(
5862 payment_params, 180_000);
5863 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5864 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5865 assert_eq!(route.paths.len(), 2);
5867 let mut total_value_transferred_msat = 0;
5868 let mut total_paid_msat = 0;
5869 for path in &route.paths {
5870 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5871 total_value_transferred_msat += path.final_value_msat();
5872 for hop in &path.hops {
5873 total_paid_msat += hop.fee_msat;
5876 // If we paid fee, this would be higher.
5877 assert_eq!(total_value_transferred_msat, 180_000);
5878 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5879 assert_eq!(total_fees_paid, 0);
5884 fn fees_on_mpp_route_test() {
5885 // This test makes sure that MPP algorithm properly takes into account
5886 // fees charged on the channels, by making the fees impactful:
5887 // if the fee is not properly accounted for, the behavior is different.
5888 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5889 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5890 let scorer = ln_test_utils::TestScorer::new();
5891 let random_seed_bytes = [42; 32];
5892 let config = UserConfig::default();
5893 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5894 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5897 // We need a route consisting of 2 paths:
5898 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5899 // We will route 200 sats, Each path will have 100 sats capacity.
5901 // This test is not particularly stable: e.g.,
5902 // there's a way to route via {node0, node2, node4}.
5903 // It works while pathfinding is deterministic, but can be broken otherwise.
5904 // It's fine to ignore this concern for now.
5906 // Disable other potential paths.
5907 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5908 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5909 short_channel_id: 2,
5911 message_flags: 1, // Only must_be_one
5913 cltv_expiry_delta: 0,
5914 htlc_minimum_msat: 0,
5915 htlc_maximum_msat: 100_000,
5917 fee_proportional_millionths: 0,
5918 excess_data: Vec::new()
5921 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5922 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5923 short_channel_id: 7,
5925 message_flags: 1, // Only must_be_one
5927 cltv_expiry_delta: 0,
5928 htlc_minimum_msat: 0,
5929 htlc_maximum_msat: 100_000,
5931 fee_proportional_millionths: 0,
5932 excess_data: Vec::new()
5935 // Path via {node0, node2} is channels {1, 3, 5}.
5936 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5937 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5938 short_channel_id: 1,
5940 message_flags: 1, // Only must_be_one
5942 cltv_expiry_delta: 0,
5943 htlc_minimum_msat: 0,
5944 htlc_maximum_msat: 100_000,
5946 fee_proportional_millionths: 0,
5947 excess_data: Vec::new()
5949 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5950 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5951 short_channel_id: 3,
5953 message_flags: 1, // Only must_be_one
5955 cltv_expiry_delta: 0,
5956 htlc_minimum_msat: 0,
5957 htlc_maximum_msat: 100_000,
5959 fee_proportional_millionths: 0,
5960 excess_data: Vec::new()
5963 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5964 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5965 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5966 short_channel_id: 5,
5968 message_flags: 1, // Only must_be_one
5970 cltv_expiry_delta: 0,
5971 htlc_minimum_msat: 0,
5972 htlc_maximum_msat: 100_000,
5974 fee_proportional_millionths: 0,
5975 excess_data: Vec::new()
5977 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5978 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5979 short_channel_id: 5,
5981 message_flags: 1, // Only must_be_one
5982 channel_flags: 3, // Disable direction 1
5983 cltv_expiry_delta: 0,
5984 htlc_minimum_msat: 0,
5985 htlc_maximum_msat: 100_000,
5987 fee_proportional_millionths: 0,
5988 excess_data: Vec::new()
5991 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5992 // All channels should be 100 sats capacity. But for the fee experiment,
5993 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5994 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5995 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5996 // so no matter how large are other channels,
5997 // the whole path will be limited by 100 sats with just these 2 conditions:
5998 // - channel 12 capacity is 250 sats
5999 // - fee for channel 6 is 150 sats
6000 // Let's test this by enforcing these 2 conditions and removing other limits.
6001 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6002 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6003 short_channel_id: 12,
6005 message_flags: 1, // Only must_be_one
6007 cltv_expiry_delta: 0,
6008 htlc_minimum_msat: 0,
6009 htlc_maximum_msat: 250_000,
6011 fee_proportional_millionths: 0,
6012 excess_data: Vec::new()
6014 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6015 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6016 short_channel_id: 13,
6018 message_flags: 1, // Only must_be_one
6020 cltv_expiry_delta: 0,
6021 htlc_minimum_msat: 0,
6022 htlc_maximum_msat: MAX_VALUE_MSAT,
6024 fee_proportional_millionths: 0,
6025 excess_data: Vec::new()
6028 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
6029 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6030 short_channel_id: 6,
6032 message_flags: 1, // Only must_be_one
6034 cltv_expiry_delta: 0,
6035 htlc_minimum_msat: 0,
6036 htlc_maximum_msat: MAX_VALUE_MSAT,
6037 fee_base_msat: 150_000,
6038 fee_proportional_millionths: 0,
6039 excess_data: Vec::new()
6041 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6042 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6043 short_channel_id: 11,
6045 message_flags: 1, // Only must_be_one
6047 cltv_expiry_delta: 0,
6048 htlc_minimum_msat: 0,
6049 htlc_maximum_msat: MAX_VALUE_MSAT,
6051 fee_proportional_millionths: 0,
6052 excess_data: Vec::new()
6056 // Attempt to route more than available results in a failure.
6057 let route_params = RouteParameters::from_payment_params_and_value(
6058 payment_params.clone(), 210_000);
6059 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6060 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6061 &scorer, &Default::default(), &random_seed_bytes) {
6062 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6063 } else { panic!(); }
6067 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
6068 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
6069 max_total_routing_fee_msat: Some(149_999) };
6070 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6071 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6072 &scorer, &Default::default(), &random_seed_bytes) {
6073 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6074 } else { panic!(); }
6078 // Now, attempt to route 200 sats (exact amount we can route).
6079 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
6080 max_total_routing_fee_msat: Some(150_000) };
6081 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6082 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6083 assert_eq!(route.paths.len(), 2);
6085 let mut total_amount_paid_msat = 0;
6086 for path in &route.paths {
6087 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
6088 total_amount_paid_msat += path.final_value_msat();
6090 assert_eq!(total_amount_paid_msat, 200_000);
6091 assert_eq!(route.get_total_fees(), 150_000);
6096 fn mpp_with_last_hops() {
6097 // Previously, if we tried to send an MPP payment to a destination which was only reachable
6098 // via a single last-hop route hint, we'd fail to route if we first collected routes
6099 // totaling close but not quite enough to fund the full payment.
6101 // This was because we considered last-hop hints to have exactly the sought payment amount
6102 // instead of the amount we were trying to collect, needlessly limiting our path searching
6103 // at the very first hop.
6105 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
6106 // criterion to cause us to refuse all routes at the last hop hint which would be considered
6107 // to only have the remaining to-collect amount in available liquidity.
6109 // This bug appeared in production in some specific channel configurations.
6110 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6111 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6112 let scorer = ln_test_utils::TestScorer::new();
6113 let random_seed_bytes = [42; 32];
6114 let config = UserConfig::default();
6115 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
6116 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
6117 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
6118 src_node_id: nodes[2],
6119 short_channel_id: 42,
6120 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
6121 cltv_expiry_delta: 42,
6122 htlc_minimum_msat: None,
6123 htlc_maximum_msat: None,
6124 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
6126 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
6127 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
6128 // would first use the no-fee route and then fail to find a path along the second route as
6129 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
6130 // under 5% of our payment amount.
6131 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6132 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6133 short_channel_id: 1,
6135 message_flags: 1, // Only must_be_one
6137 cltv_expiry_delta: (5 << 4) | 5,
6138 htlc_minimum_msat: 0,
6139 htlc_maximum_msat: 99_000,
6140 fee_base_msat: u32::max_value(),
6141 fee_proportional_millionths: u32::max_value(),
6142 excess_data: Vec::new()
6144 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6145 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6146 short_channel_id: 2,
6148 message_flags: 1, // Only must_be_one
6150 cltv_expiry_delta: (5 << 4) | 3,
6151 htlc_minimum_msat: 0,
6152 htlc_maximum_msat: 99_000,
6153 fee_base_msat: u32::max_value(),
6154 fee_proportional_millionths: u32::max_value(),
6155 excess_data: Vec::new()
6157 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6158 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6159 short_channel_id: 4,
6161 message_flags: 1, // Only must_be_one
6163 cltv_expiry_delta: (4 << 4) | 1,
6164 htlc_minimum_msat: 0,
6165 htlc_maximum_msat: MAX_VALUE_MSAT,
6167 fee_proportional_millionths: 0,
6168 excess_data: Vec::new()
6170 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6171 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6172 short_channel_id: 13,
6174 message_flags: 1, // Only must_be_one
6175 channel_flags: 0|2, // Channel disabled
6176 cltv_expiry_delta: (13 << 4) | 1,
6177 htlc_minimum_msat: 0,
6178 htlc_maximum_msat: MAX_VALUE_MSAT,
6180 fee_proportional_millionths: 2000000,
6181 excess_data: Vec::new()
6184 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
6186 let route_params = RouteParameters::from_payment_params_and_value(
6187 payment_params, 100_000);
6188 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6189 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6190 assert_eq!(route.paths.len(), 2);
6191 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
6192 // Paths are manually ordered ordered by SCID, so:
6193 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
6194 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
6195 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
6196 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
6197 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
6198 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
6199 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
6200 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
6201 assert_eq!(route.get_total_fees(), 1);
6202 assert_eq!(route.get_total_amount(), 100_000);
6206 fn drop_lowest_channel_mpp_route_test() {
6207 // This test checks that low-capacity channel is dropped when after
6208 // path finding we realize that we found more capacity than we need.
6209 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6210 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6211 let scorer = ln_test_utils::TestScorer::new();
6212 let random_seed_bytes = [42; 32];
6213 let config = UserConfig::default();
6214 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6215 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6217 .with_max_channel_saturation_power_of_half(0);
6219 // We need a route consisting of 3 paths:
6220 // From our node to node2 via node0, node7, node1 (three paths one hop each).
6222 // The first and the second paths should be sufficient, but the third should be
6223 // cheaper, so that we select it but drop later.
6225 // First, we set limits on these (previously unlimited) channels.
6226 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
6228 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
6229 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6230 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6231 short_channel_id: 1,
6233 message_flags: 1, // Only must_be_one
6235 cltv_expiry_delta: 0,
6236 htlc_minimum_msat: 0,
6237 htlc_maximum_msat: 100_000,
6239 fee_proportional_millionths: 0,
6240 excess_data: Vec::new()
6242 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6243 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6244 short_channel_id: 3,
6246 message_flags: 1, // Only must_be_one
6248 cltv_expiry_delta: 0,
6249 htlc_minimum_msat: 0,
6250 htlc_maximum_msat: 50_000,
6252 fee_proportional_millionths: 0,
6253 excess_data: Vec::new()
6256 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
6257 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6258 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6259 short_channel_id: 12,
6261 message_flags: 1, // Only must_be_one
6263 cltv_expiry_delta: 0,
6264 htlc_minimum_msat: 0,
6265 htlc_maximum_msat: 60_000,
6267 fee_proportional_millionths: 0,
6268 excess_data: Vec::new()
6270 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6271 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6272 short_channel_id: 13,
6274 message_flags: 1, // Only must_be_one
6276 cltv_expiry_delta: 0,
6277 htlc_minimum_msat: 0,
6278 htlc_maximum_msat: 60_000,
6280 fee_proportional_millionths: 0,
6281 excess_data: Vec::new()
6284 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
6285 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6286 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6287 short_channel_id: 2,
6289 message_flags: 1, // Only must_be_one
6291 cltv_expiry_delta: 0,
6292 htlc_minimum_msat: 0,
6293 htlc_maximum_msat: 20_000,
6295 fee_proportional_millionths: 0,
6296 excess_data: Vec::new()
6298 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6299 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6300 short_channel_id: 4,
6302 message_flags: 1, // Only must_be_one
6304 cltv_expiry_delta: 0,
6305 htlc_minimum_msat: 0,
6306 htlc_maximum_msat: 20_000,
6308 fee_proportional_millionths: 0,
6309 excess_data: Vec::new()
6313 // Attempt to route more than available results in a failure.
6314 let route_params = RouteParameters::from_payment_params_and_value(
6315 payment_params.clone(), 150_000);
6316 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6317 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6318 &scorer, &Default::default(), &random_seed_bytes) {
6319 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6320 } else { panic!(); }
6324 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
6325 // Our algorithm should provide us with these 3 paths.
6326 let route_params = RouteParameters::from_payment_params_and_value(
6327 payment_params.clone(), 125_000);
6328 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6329 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6330 assert_eq!(route.paths.len(), 3);
6331 let mut total_amount_paid_msat = 0;
6332 for path in &route.paths {
6333 assert_eq!(path.hops.len(), 2);
6334 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6335 total_amount_paid_msat += path.final_value_msat();
6337 assert_eq!(total_amount_paid_msat, 125_000);
6341 // Attempt to route without the last small cheap channel
6342 let route_params = RouteParameters::from_payment_params_and_value(
6343 payment_params, 90_000);
6344 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6345 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6346 assert_eq!(route.paths.len(), 2);
6347 let mut total_amount_paid_msat = 0;
6348 for path in &route.paths {
6349 assert_eq!(path.hops.len(), 2);
6350 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6351 total_amount_paid_msat += path.final_value_msat();
6353 assert_eq!(total_amount_paid_msat, 90_000);
6358 fn min_criteria_consistency() {
6359 // Test that we don't use an inconsistent metric between updating and walking nodes during
6360 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
6361 // was updated with a different criterion from the heap sorting, resulting in loops in
6362 // calculated paths. We test for that specific case here.
6364 // We construct a network that looks like this:
6366 // node2 -1(3)2- node3
6370 // node1 -1(5)2- node4 -1(1)2- node6
6376 // We create a loop on the side of our real path - our destination is node 6, with a
6377 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
6378 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
6379 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
6380 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
6381 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
6382 // "previous hop" being set to node 3, creating a loop in the path.
6383 let secp_ctx = Secp256k1::new();
6384 let logger = Arc::new(ln_test_utils::TestLogger::new());
6385 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6386 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
6387 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6388 let scorer = ln_test_utils::TestScorer::new();
6389 let random_seed_bytes = [42; 32];
6390 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
6392 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
6393 for (key, channel_flags) in [(&our_privkey, 0), (&privkeys[1], 3)] {
6394 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6395 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6396 short_channel_id: 6,
6398 message_flags: 1, // Only must_be_one
6400 cltv_expiry_delta: (6 << 4) | 0,
6401 htlc_minimum_msat: 0,
6402 htlc_maximum_msat: MAX_VALUE_MSAT,
6404 fee_proportional_millionths: 0,
6405 excess_data: Vec::new()
6408 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
6410 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6411 for (key, channel_flags) in [(&privkeys[1], 0), (&privkeys[4], 3)] {
6412 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6413 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6414 short_channel_id: 5,
6416 message_flags: 1, // Only must_be_one
6418 cltv_expiry_delta: (5 << 4) | 0,
6419 htlc_minimum_msat: 0,
6420 htlc_maximum_msat: MAX_VALUE_MSAT,
6422 fee_proportional_millionths: 0,
6423 excess_data: Vec::new()
6426 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
6428 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
6429 for (key, channel_flags) in [(&privkeys[4], 0), (&privkeys[3], 3)] {
6430 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6431 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6432 short_channel_id: 4,
6434 message_flags: 1, // Only must_be_one
6436 cltv_expiry_delta: (4 << 4) | 0,
6437 htlc_minimum_msat: 0,
6438 htlc_maximum_msat: MAX_VALUE_MSAT,
6440 fee_proportional_millionths: 0,
6441 excess_data: Vec::new()
6444 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6446 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6447 for (key, channel_flags) in [(&privkeys[3], 0), (&privkeys[2], 3)] {
6448 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6449 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6450 short_channel_id: 3,
6452 message_flags: 1, // Only must_be_one
6454 cltv_expiry_delta: (3 << 4) | 0,
6455 htlc_minimum_msat: 0,
6456 htlc_maximum_msat: MAX_VALUE_MSAT,
6458 fee_proportional_millionths: 0,
6459 excess_data: Vec::new()
6462 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6464 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6465 for (key, channel_flags) in [(&privkeys[2], 0), (&privkeys[4], 3)] {
6466 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6467 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6468 short_channel_id: 2,
6470 message_flags: 1, // Only must_be_one
6472 cltv_expiry_delta: (2 << 4) | 0,
6473 htlc_minimum_msat: 0,
6474 htlc_maximum_msat: MAX_VALUE_MSAT,
6476 fee_proportional_millionths: 0,
6477 excess_data: Vec::new()
6481 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6482 for (key, channel_flags) in [(&privkeys[4], 0), (&privkeys[6], 3)] {
6483 update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6484 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6485 short_channel_id: 1,
6487 message_flags: 1, // Only must_be_one
6489 cltv_expiry_delta: (1 << 4) | 0,
6490 htlc_minimum_msat: 100,
6491 htlc_maximum_msat: MAX_VALUE_MSAT,
6493 fee_proportional_millionths: 0,
6494 excess_data: Vec::new()
6497 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6500 // Now ensure the route flows simply over nodes 1 and 4 to 6.
6501 let route_params = RouteParameters::from_payment_params_and_value(
6502 payment_params, 10_000);
6503 let route = get_route(&our_id, &route_params, &network.read_only(), None,
6504 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6505 assert_eq!(route.paths.len(), 1);
6506 assert_eq!(route.paths[0].hops.len(), 3);
6508 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6509 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6510 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6511 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6512 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6513 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6515 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6516 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6517 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6518 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6519 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6520 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6522 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6523 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6524 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6525 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6526 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6527 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6533 fn exact_fee_liquidity_limit() {
6534 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6535 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6536 // we calculated fees on a higher value, resulting in us ignoring such paths.
6537 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6538 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6539 let scorer = ln_test_utils::TestScorer::new();
6540 let random_seed_bytes = [42; 32];
6541 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6543 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6545 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6546 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6547 short_channel_id: 2,
6549 message_flags: 1, // Only must_be_one
6551 cltv_expiry_delta: 0,
6552 htlc_minimum_msat: 0,
6553 htlc_maximum_msat: 85_000,
6555 fee_proportional_millionths: 0,
6556 excess_data: Vec::new()
6559 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6560 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6561 short_channel_id: 12,
6563 message_flags: 1, // Only must_be_one
6565 cltv_expiry_delta: (4 << 4) | 1,
6566 htlc_minimum_msat: 0,
6567 htlc_maximum_msat: 270_000,
6569 fee_proportional_millionths: 1000000,
6570 excess_data: Vec::new()
6574 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6575 // 200% fee charged channel 13 in the 1-to-2 direction.
6576 let mut route_params = RouteParameters::from_payment_params_and_value(
6577 payment_params, 90_000);
6578 route_params.max_total_routing_fee_msat = Some(90_000*2);
6579 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6580 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6581 assert_eq!(route.paths.len(), 1);
6582 assert_eq!(route.paths[0].hops.len(), 2);
6584 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6585 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6586 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6587 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6588 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6589 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6591 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6592 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6593 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6594 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6595 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6596 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6601 fn htlc_max_reduction_below_min() {
6602 // Test that if, while walking the graph, we reduce the value being sent to meet an
6603 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6604 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6605 // resulting in us thinking there is no possible path, even if other paths exist.
6606 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6607 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6608 let scorer = ln_test_utils::TestScorer::new();
6609 let random_seed_bytes = [42; 32];
6610 let config = UserConfig::default();
6611 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6612 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6615 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6616 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6617 // then try to send 90_000.
6618 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6619 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6620 short_channel_id: 2,
6622 message_flags: 1, // Only must_be_one
6624 cltv_expiry_delta: 0,
6625 htlc_minimum_msat: 0,
6626 htlc_maximum_msat: 80_000,
6628 fee_proportional_millionths: 0,
6629 excess_data: Vec::new()
6631 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6632 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6633 short_channel_id: 4,
6635 message_flags: 1, // Only must_be_one
6637 cltv_expiry_delta: (4 << 4) | 1,
6638 htlc_minimum_msat: 90_000,
6639 htlc_maximum_msat: MAX_VALUE_MSAT,
6641 fee_proportional_millionths: 0,
6642 excess_data: Vec::new()
6646 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6647 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6648 // expensive) channels 12-13 path.
6649 let mut route_params = RouteParameters::from_payment_params_and_value(
6650 payment_params, 90_000);
6651 route_params.max_total_routing_fee_msat = Some(90_000*2);
6652 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6653 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6654 assert_eq!(route.paths.len(), 1);
6655 assert_eq!(route.paths[0].hops.len(), 2);
6657 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6658 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6659 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6660 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6661 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6662 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6664 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6665 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6666 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6667 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6668 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6669 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6674 fn multiple_direct_first_hops() {
6675 // Previously we'd only ever considered one first hop path per counterparty.
6676 // However, as we don't restrict users to one channel per peer, we really need to support
6677 // looking at all first hop paths.
6678 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6679 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6680 // route over multiple channels with the same first hop.
6681 let secp_ctx = Secp256k1::new();
6682 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6683 let logger = Arc::new(ln_test_utils::TestLogger::new());
6684 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6685 let scorer = ln_test_utils::TestScorer::new();
6686 let config = UserConfig::default();
6687 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6688 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6690 let random_seed_bytes = [42; 32];
6693 let route_params = RouteParameters::from_payment_params_and_value(
6694 payment_params.clone(), 100_000);
6695 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6696 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6697 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6698 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6699 assert_eq!(route.paths.len(), 1);
6700 assert_eq!(route.paths[0].hops.len(), 1);
6702 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6703 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6704 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6707 let route_params = RouteParameters::from_payment_params_and_value(
6708 payment_params.clone(), 100_000);
6709 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6710 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6711 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6712 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6713 assert_eq!(route.paths.len(), 2);
6714 assert_eq!(route.paths[0].hops.len(), 1);
6715 assert_eq!(route.paths[1].hops.len(), 1);
6717 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6718 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6720 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6721 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6723 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6724 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6728 // If we have a bunch of outbound channels to the same node, where most are not
6729 // sufficient to pay the full payment, but one is, we should default to just using the
6730 // one single channel that has sufficient balance, avoiding MPP.
6732 // If we have several options above the 3xpayment value threshold, we should pick the
6733 // smallest of them, avoiding further fragmenting our available outbound balance to
6735 let route_params = RouteParameters::from_payment_params_and_value(
6736 payment_params, 100_000);
6737 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6738 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6739 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6740 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6741 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6742 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6743 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6744 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6745 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6746 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6747 assert_eq!(route.paths.len(), 1);
6748 assert_eq!(route.paths[0].hops.len(), 1);
6750 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6751 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6752 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6757 fn prefers_shorter_route_with_higher_fees() {
6758 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6759 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6760 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6762 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6763 let scorer = ln_test_utils::TestScorer::new();
6764 let random_seed_bytes = [42; 32];
6765 let route_params = RouteParameters::from_payment_params_and_value(
6766 payment_params.clone(), 100);
6767 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6768 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6769 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6771 assert_eq!(route.get_total_fees(), 100);
6772 assert_eq!(route.get_total_amount(), 100);
6773 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6775 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6776 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6777 let scorer = FixedPenaltyScorer::with_penalty(100);
6778 let route_params = RouteParameters::from_payment_params_and_value(
6779 payment_params, 100);
6780 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6781 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6782 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6784 assert_eq!(route.get_total_fees(), 300);
6785 assert_eq!(route.get_total_amount(), 100);
6786 assert_eq!(path, vec![2, 4, 7, 10]);
6789 struct BadChannelScorer {
6790 short_channel_id: u64,
6794 impl Writeable for BadChannelScorer {
6795 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6797 impl ScoreLookUp for BadChannelScorer {
6798 type ScoreParams = ();
6799 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6800 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6804 struct BadNodeScorer {
6809 impl Writeable for BadNodeScorer {
6810 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6813 impl ScoreLookUp for BadNodeScorer {
6814 type ScoreParams = ();
6815 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6816 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6821 fn avoids_routing_through_bad_channels_and_nodes() {
6822 let (secp_ctx, network, _, _, logger) = build_graph();
6823 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6824 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6825 let network_graph = network.read_only();
6827 // A path to nodes[6] exists when no penalties are applied to any channel.
6828 let scorer = ln_test_utils::TestScorer::new();
6829 let random_seed_bytes = [42; 32];
6830 let route_params = RouteParameters::from_payment_params_and_value(
6831 payment_params, 100);
6832 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6833 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6834 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6836 assert_eq!(route.get_total_fees(), 100);
6837 assert_eq!(route.get_total_amount(), 100);
6838 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6840 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6841 let scorer = BadChannelScorer { short_channel_id: 6 };
6842 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6843 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6844 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6846 assert_eq!(route.get_total_fees(), 300);
6847 assert_eq!(route.get_total_amount(), 100);
6848 assert_eq!(path, vec![2, 4, 7, 10]);
6850 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6851 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6852 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6853 &scorer, &Default::default(), &random_seed_bytes) {
6854 Err(LightningError { err, .. } ) => {
6855 assert_eq!(err, "Failed to find a path to the given destination");
6857 Ok(_) => panic!("Expected error"),
6862 fn total_fees_single_path() {
6864 paths: vec![Path { hops: vec![
6866 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6867 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6868 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6871 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6872 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6873 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6876 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6877 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6878 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6880 ], blinded_tail: None }],
6884 assert_eq!(route.get_total_fees(), 250);
6885 assert_eq!(route.get_total_amount(), 225);
6889 fn total_fees_multi_path() {
6891 paths: vec![Path { hops: vec![
6893 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6894 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6895 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6898 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6899 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6900 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6902 ], blinded_tail: None }, Path { hops: vec![
6904 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6905 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6906 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6909 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6910 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6911 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6913 ], blinded_tail: None }],
6917 assert_eq!(route.get_total_fees(), 200);
6918 assert_eq!(route.get_total_amount(), 300);
6922 fn total_empty_route_no_panic() {
6923 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6924 // would both panic if the route was completely empty. We test to ensure they return 0
6925 // here, even though its somewhat nonsensical as a route.
6926 let route = Route { paths: Vec::new(), route_params: None };
6928 assert_eq!(route.get_total_fees(), 0);
6929 assert_eq!(route.get_total_amount(), 0);
6933 fn limits_total_cltv_delta() {
6934 let (secp_ctx, network, _, _, logger) = build_graph();
6935 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6936 let network_graph = network.read_only();
6938 let scorer = ln_test_utils::TestScorer::new();
6940 // Make sure that generally there is at least one route available
6941 let feasible_max_total_cltv_delta = 1008;
6942 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6943 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6944 let random_seed_bytes = [42; 32];
6945 let route_params = RouteParameters::from_payment_params_and_value(
6946 feasible_payment_params, 100);
6947 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6948 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6949 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6950 assert_ne!(path.len(), 0);
6952 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6953 let fail_max_total_cltv_delta = 23;
6954 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6955 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6956 let route_params = RouteParameters::from_payment_params_and_value(
6957 fail_payment_params, 100);
6958 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6959 &Default::default(), &random_seed_bytes)
6961 Err(LightningError { err, .. } ) => {
6962 assert_eq!(err, "Failed to find a path to the given destination");
6964 Ok(_) => panic!("Expected error"),
6969 fn avoids_recently_failed_paths() {
6970 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6971 // randomly inserting channels into it until we can't find a route anymore.
6972 let (secp_ctx, network, _, _, logger) = build_graph();
6973 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6974 let network_graph = network.read_only();
6976 let scorer = ln_test_utils::TestScorer::new();
6977 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6978 .with_max_path_count(1);
6979 let random_seed_bytes = [42; 32];
6981 // We should be able to find a route initially, and then after we fail a few random
6982 // channels eventually we won't be able to any longer.
6983 let route_params = RouteParameters::from_payment_params_and_value(
6984 payment_params.clone(), 100);
6985 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6986 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6988 let route_params = RouteParameters::from_payment_params_and_value(
6989 payment_params.clone(), 100);
6990 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6991 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6993 for chan in route.paths[0].hops.iter() {
6994 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6996 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6997 % route.paths[0].hops.len();
6998 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
7004 fn limits_path_length() {
7005 let (secp_ctx, network, _, _, logger) = build_line_graph();
7006 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7007 let network_graph = network.read_only();
7009 let scorer = ln_test_utils::TestScorer::new();
7010 let random_seed_bytes = [42; 32];
7012 // First check we can actually create a long route on this graph.
7013 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
7014 let route_params = RouteParameters::from_payment_params_and_value(
7015 feasible_payment_params, 100);
7016 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7017 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7018 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
7019 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
7021 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
7022 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
7023 let route_params = RouteParameters::from_payment_params_and_value(
7024 fail_payment_params, 100);
7025 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7026 &Default::default(), &random_seed_bytes)
7028 Err(LightningError { err, .. } ) => {
7029 assert_eq!(err, "Failed to find a path to the given destination");
7031 Ok(_) => panic!("Expected error"),
7036 fn adds_and_limits_cltv_offset() {
7037 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7038 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7040 let scorer = ln_test_utils::TestScorer::new();
7042 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
7043 let random_seed_bytes = [42; 32];
7044 let route_params = RouteParameters::from_payment_params_and_value(
7045 payment_params.clone(), 100);
7046 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
7047 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
7048 assert_eq!(route.paths.len(), 1);
7050 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
7052 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
7053 let mut route_default = route.clone();
7054 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
7055 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
7056 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
7057 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
7058 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
7060 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
7061 let mut route_limited = route.clone();
7062 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
7063 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
7064 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
7065 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
7066 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
7070 fn adds_plausible_cltv_offset() {
7071 let (secp_ctx, network, _, _, logger) = build_graph();
7072 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7073 let network_graph = network.read_only();
7074 let network_nodes = network_graph.nodes();
7075 let network_channels = network_graph.channels();
7076 let scorer = ln_test_utils::TestScorer::new();
7077 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
7078 let random_seed_bytes = [42; 32];
7080 let route_params = RouteParameters::from_payment_params_and_value(
7081 payment_params.clone(), 100);
7082 let mut route = get_route(&our_id, &route_params, &network_graph, None,
7083 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
7084 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
7086 let mut path_plausibility = vec![];
7088 for p in route.paths {
7089 // 1. Select random observation point
7090 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
7091 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
7093 prng.process_in_place(&mut random_bytes);
7094 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
7095 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
7097 // 2. Calculate what CLTV expiry delta we would observe there
7098 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
7100 // 3. Starting from the observation point, find candidate paths
7101 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
7102 candidates.push_back((observation_point, vec![]));
7104 let mut found_plausible_candidate = false;
7106 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
7107 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
7108 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
7109 found_plausible_candidate = true;
7110 break 'candidate_loop;
7114 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
7115 for channel_id in &cur_node.channels {
7116 if let Some(channel_info) = network_channels.get(&channel_id) {
7117 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
7118 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
7119 if cur_path_cltv_deltas.iter().sum::<u32>()
7120 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
7121 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
7122 new_path_cltv_deltas.push(next_cltv_expiry_delta);
7123 candidates.push_back((*next_id, new_path_cltv_deltas));
7131 path_plausibility.push(found_plausible_candidate);
7133 assert!(path_plausibility.iter().all(|x| *x));
7137 fn builds_correct_path_from_hops() {
7138 let (secp_ctx, network, _, _, logger) = build_graph();
7139 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7140 let network_graph = network.read_only();
7142 let random_seed_bytes = [42; 32];
7143 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
7144 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
7145 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
7146 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
7147 Arc::clone(&logger), &random_seed_bytes).unwrap();
7148 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
7149 assert_eq!(hops.len(), route.paths[0].hops.len());
7150 for (idx, hop_pubkey) in hops.iter().enumerate() {
7151 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
7156 fn avoids_saturating_channels() {
7157 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
7158 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
7159 let decay_params = ProbabilisticScoringDecayParameters::default();
7160 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
7162 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
7163 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
7164 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7165 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7166 short_channel_id: 4,
7168 message_flags: 1, // Only must_be_one
7170 cltv_expiry_delta: (4 << 4) | 1,
7171 htlc_minimum_msat: 0,
7172 htlc_maximum_msat: 250_000_000,
7174 fee_proportional_millionths: 0,
7175 excess_data: Vec::new()
7177 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
7178 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7179 short_channel_id: 13,
7181 message_flags: 1, // Only must_be_one
7183 cltv_expiry_delta: (13 << 4) | 1,
7184 htlc_minimum_msat: 0,
7185 htlc_maximum_msat: 250_000_000,
7187 fee_proportional_millionths: 0,
7188 excess_data: Vec::new()
7191 let config = UserConfig::default();
7192 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
7193 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7195 let random_seed_bytes = [42; 32];
7197 // 100,000 sats is less than the available liquidity on each channel, set above.
7198 let route_params = RouteParameters::from_payment_params_and_value(
7199 payment_params, 100_000_000);
7200 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
7201 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
7202 assert_eq!(route.paths.len(), 2);
7203 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
7204 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
7207 #[cfg(feature = "std")]
7208 pub(super) fn random_init_seed() -> u64 {
7209 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
7210 use core::hash::{BuildHasher, Hasher};
7211 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
7212 println!("Using seed of {}", seed);
7217 #[cfg(feature = "std")]
7218 fn generate_routes() {
7219 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7221 let logger = ln_test_utils::TestLogger::new();
7222 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7230 let params = ProbabilisticScoringFeeParameters::default();
7231 let features = super::Bolt11InvoiceFeatures::empty();
7233 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7237 #[cfg(feature = "std")]
7238 fn generate_routes_mpp() {
7239 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7241 let logger = ln_test_utils::TestLogger::new();
7242 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7250 let params = ProbabilisticScoringFeeParameters::default();
7251 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7253 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7257 #[cfg(feature = "std")]
7258 fn generate_large_mpp_routes() {
7259 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7261 let logger = ln_test_utils::TestLogger::new();
7262 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7270 let params = ProbabilisticScoringFeeParameters::default();
7271 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7273 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
7277 fn honors_manual_penalties() {
7278 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
7279 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7281 let random_seed_bytes = [42; 32];
7282 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
7283 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
7285 // First check set manual penalties are returned by the scorer.
7286 let usage = ChannelUsage {
7288 inflight_htlc_msat: 0,
7289 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
7291 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
7292 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
7293 let network_graph = network_graph.read_only();
7294 let channels = network_graph.channels();
7295 let channel = channels.get(&5).unwrap();
7296 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
7297 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop(PublicHopCandidate {
7299 short_channel_id: 5,
7301 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
7303 // Then check we can get a normal route
7304 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
7305 let route_params = RouteParameters::from_payment_params_and_value(
7306 payment_params, 100);
7307 let route = get_route(&our_id, &route_params, &network_graph, None,
7308 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
7309 assert!(route.is_ok());
7311 // Then check that we can't get a route if we ban an intermediate node.
7312 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
7313 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7314 assert!(route.is_err());
7316 // Finally make sure we can route again, when we remove the ban.
7317 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
7318 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7319 assert!(route.is_ok());
7323 fn abide_by_route_hint_max_htlc() {
7324 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
7325 // params in the final route.
7326 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7327 let netgraph = network_graph.read_only();
7328 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7329 let scorer = ln_test_utils::TestScorer::new();
7330 let random_seed_bytes = [42; 32];
7331 let config = UserConfig::default();
7333 let max_htlc_msat = 50_000;
7334 let route_hint_1 = RouteHint(vec![RouteHintHop {
7335 src_node_id: nodes[2],
7336 short_channel_id: 42,
7339 proportional_millionths: 0,
7341 cltv_expiry_delta: 10,
7342 htlc_minimum_msat: None,
7343 htlc_maximum_msat: Some(max_htlc_msat),
7345 let dest_node_id = ln_test_utils::pubkey(42);
7346 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7347 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
7348 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7351 // Make sure we'll error if our route hints don't have enough liquidity according to their
7352 // htlc_maximum_msat.
7353 let mut route_params = RouteParameters::from_payment_params_and_value(
7354 payment_params, max_htlc_msat + 1);
7355 route_params.max_total_routing_fee_msat = None;
7356 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
7357 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
7360 assert_eq!(err, "Failed to find a sufficient route to the given destination");
7361 } else { panic!(); }
7363 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
7364 let mut route_hint_2 = route_hint_1.clone();
7365 route_hint_2.0[0].short_channel_id = 43;
7366 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7367 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7368 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7370 let mut route_params = RouteParameters::from_payment_params_and_value(
7371 payment_params, max_htlc_msat + 1);
7372 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
7373 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
7374 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7375 assert_eq!(route.paths.len(), 2);
7376 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7377 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7381 fn direct_channel_to_hints_with_max_htlc() {
7382 // Check that if we have a first hop channel peer that's connected to multiple provided route
7383 // hints, that we properly split the payment between the route hints if needed.
7384 let logger = Arc::new(ln_test_utils::TestLogger::new());
7385 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7386 let scorer = ln_test_utils::TestScorer::new();
7387 let random_seed_bytes = [42; 32];
7388 let config = UserConfig::default();
7390 let our_node_id = ln_test_utils::pubkey(42);
7391 let intermed_node_id = ln_test_utils::pubkey(43);
7392 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7394 let amt_msat = 900_000;
7395 let max_htlc_msat = 500_000;
7396 let route_hint_1 = RouteHint(vec![RouteHintHop {
7397 src_node_id: intermed_node_id,
7398 short_channel_id: 44,
7401 proportional_millionths: 0,
7403 cltv_expiry_delta: 10,
7404 htlc_minimum_msat: None,
7405 htlc_maximum_msat: Some(max_htlc_msat),
7407 src_node_id: intermed_node_id,
7408 short_channel_id: 45,
7411 proportional_millionths: 0,
7413 cltv_expiry_delta: 10,
7414 htlc_minimum_msat: None,
7415 // Check that later route hint max htlcs don't override earlier ones
7416 htlc_maximum_msat: Some(max_htlc_msat - 50),
7418 let mut route_hint_2 = route_hint_1.clone();
7419 route_hint_2.0[0].short_channel_id = 46;
7420 route_hint_2.0[1].short_channel_id = 47;
7421 let dest_node_id = ln_test_utils::pubkey(44);
7422 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7423 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7424 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7427 let route_params = RouteParameters::from_payment_params_and_value(
7428 payment_params, amt_msat);
7429 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7430 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7431 &Default::default(), &random_seed_bytes).unwrap();
7432 assert_eq!(route.paths.len(), 2);
7433 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7434 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7435 assert_eq!(route.get_total_amount(), amt_msat);
7437 // Re-run but with two first hop channels connected to the same route hint peers that must be
7439 let first_hops = vec![
7440 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7441 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7443 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7444 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7445 &Default::default(), &random_seed_bytes).unwrap();
7446 assert_eq!(route.paths.len(), 2);
7447 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7448 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7449 assert_eq!(route.get_total_amount(), amt_msat);
7451 // Make sure this works for blinded route hints.
7452 let blinded_path = BlindedPath {
7453 introduction_node: IntroductionNode::NodeId(intermed_node_id),
7454 blinding_point: ln_test_utils::pubkey(42),
7456 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
7457 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
7460 let blinded_payinfo = BlindedPayInfo {
7462 fee_proportional_millionths: 0,
7463 htlc_minimum_msat: 1,
7464 htlc_maximum_msat: max_htlc_msat,
7465 cltv_expiry_delta: 10,
7466 features: BlindedHopFeatures::empty(),
7468 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7469 let payment_params = PaymentParameters::blinded(vec![
7470 (blinded_payinfo.clone(), blinded_path.clone()),
7471 (blinded_payinfo.clone(), blinded_path.clone())])
7472 .with_bolt12_features(bolt12_features).unwrap();
7473 let route_params = RouteParameters::from_payment_params_and_value(
7474 payment_params, amt_msat);
7475 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7476 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7477 &Default::default(), &random_seed_bytes).unwrap();
7478 assert_eq!(route.paths.len(), 2);
7479 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7480 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7481 assert_eq!(route.get_total_amount(), amt_msat);
7485 fn blinded_route_ser() {
7486 let blinded_path_1 = BlindedPath {
7487 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(42)),
7488 blinding_point: ln_test_utils::pubkey(43),
7490 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7491 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7494 let blinded_path_2 = BlindedPath {
7495 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(46)),
7496 blinding_point: ln_test_utils::pubkey(47),
7498 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7499 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7502 // (De)serialize a Route with 1 blinded path out of two total paths.
7503 let mut route = Route { paths: vec![Path {
7504 hops: vec![RouteHop {
7505 pubkey: ln_test_utils::pubkey(50),
7506 node_features: NodeFeatures::empty(),
7507 short_channel_id: 42,
7508 channel_features: ChannelFeatures::empty(),
7510 cltv_expiry_delta: 0,
7511 maybe_announced_channel: true,
7513 blinded_tail: Some(BlindedTail {
7514 hops: blinded_path_1.blinded_hops,
7515 blinding_point: blinded_path_1.blinding_point,
7516 excess_final_cltv_expiry_delta: 40,
7517 final_value_msat: 100,
7519 hops: vec![RouteHop {
7520 pubkey: ln_test_utils::pubkey(51),
7521 node_features: NodeFeatures::empty(),
7522 short_channel_id: 43,
7523 channel_features: ChannelFeatures::empty(),
7525 cltv_expiry_delta: 0,
7526 maybe_announced_channel: true,
7527 }], blinded_tail: None }],
7530 let encoded_route = route.encode();
7531 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7532 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7533 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7535 // (De)serialize a Route with two paths, each containing a blinded tail.
7536 route.paths[1].blinded_tail = Some(BlindedTail {
7537 hops: blinded_path_2.blinded_hops,
7538 blinding_point: blinded_path_2.blinding_point,
7539 excess_final_cltv_expiry_delta: 41,
7540 final_value_msat: 101,
7542 let encoded_route = route.encode();
7543 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7544 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7545 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7549 fn blinded_path_inflight_processing() {
7550 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7551 // account for the blinded tail's final amount_msat.
7552 let mut inflight_htlcs = InFlightHtlcs::new();
7553 let blinded_path = BlindedPath {
7554 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(43)),
7555 blinding_point: ln_test_utils::pubkey(48),
7556 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7559 hops: vec![RouteHop {
7560 pubkey: ln_test_utils::pubkey(42),
7561 node_features: NodeFeatures::empty(),
7562 short_channel_id: 42,
7563 channel_features: ChannelFeatures::empty(),
7565 cltv_expiry_delta: 0,
7566 maybe_announced_channel: false,
7569 pubkey: ln_test_utils::pubkey(43),
7570 node_features: NodeFeatures::empty(),
7571 short_channel_id: 43,
7572 channel_features: ChannelFeatures::empty(),
7574 cltv_expiry_delta: 0,
7575 maybe_announced_channel: false,
7577 blinded_tail: Some(BlindedTail {
7578 hops: blinded_path.blinded_hops,
7579 blinding_point: blinded_path.blinding_point,
7580 excess_final_cltv_expiry_delta: 0,
7581 final_value_msat: 200,
7584 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7585 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7586 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7590 fn blinded_path_cltv_shadow_offset() {
7591 // Make sure we add a shadow offset when sending to blinded paths.
7592 let blinded_path = BlindedPath {
7593 introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(43)),
7594 blinding_point: ln_test_utils::pubkey(44),
7596 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7597 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7600 let mut route = Route { paths: vec![Path {
7601 hops: vec![RouteHop {
7602 pubkey: ln_test_utils::pubkey(42),
7603 node_features: NodeFeatures::empty(),
7604 short_channel_id: 42,
7605 channel_features: ChannelFeatures::empty(),
7607 cltv_expiry_delta: 0,
7608 maybe_announced_channel: false,
7611 pubkey: ln_test_utils::pubkey(43),
7612 node_features: NodeFeatures::empty(),
7613 short_channel_id: 43,
7614 channel_features: ChannelFeatures::empty(),
7616 cltv_expiry_delta: 0,
7617 maybe_announced_channel: false,
7620 blinded_tail: Some(BlindedTail {
7621 hops: blinded_path.blinded_hops,
7622 blinding_point: blinded_path.blinding_point,
7623 excess_final_cltv_expiry_delta: 0,
7624 final_value_msat: 200,
7626 }], route_params: None};
7628 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7629 let (_, network_graph, _, _, _) = build_line_graph();
7630 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7631 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7632 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7636 fn simple_blinded_route_hints() {
7637 do_simple_blinded_route_hints(1);
7638 do_simple_blinded_route_hints(2);
7639 do_simple_blinded_route_hints(3);
7642 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7643 // Check that we can generate a route to a blinded path with the expected hops.
7644 let (secp_ctx, network, _, _, logger) = build_graph();
7645 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7646 let network_graph = network.read_only();
7648 let scorer = ln_test_utils::TestScorer::new();
7649 let random_seed_bytes = [42; 32];
7651 let mut blinded_path = BlindedPath {
7652 introduction_node: IntroductionNode::NodeId(nodes[2]),
7653 blinding_point: ln_test_utils::pubkey(42),
7654 blinded_hops: Vec::with_capacity(num_blinded_hops),
7656 for i in 0..num_blinded_hops {
7657 blinded_path.blinded_hops.push(
7658 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7661 let blinded_payinfo = BlindedPayInfo {
7663 fee_proportional_millionths: 500,
7664 htlc_minimum_msat: 1000,
7665 htlc_maximum_msat: 100_000_000,
7666 cltv_expiry_delta: 15,
7667 features: BlindedHopFeatures::empty(),
7670 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7671 let route_params = RouteParameters::from_payment_params_and_value(
7672 payment_params, 1001);
7673 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7674 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7675 assert_eq!(route.paths.len(), 1);
7676 assert_eq!(route.paths[0].hops.len(), 2);
7678 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7679 assert_eq!(tail.hops, blinded_path.blinded_hops);
7680 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7681 assert_eq!(tail.final_value_msat, 1001);
7683 let final_hop = route.paths[0].hops.last().unwrap();
7685 NodeId::from_pubkey(&final_hop.pubkey),
7686 *blinded_path.public_introduction_node_id(&network_graph).unwrap()
7688 if tail.hops.len() > 1 {
7689 assert_eq!(final_hop.fee_msat,
7690 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7691 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7693 assert_eq!(final_hop.fee_msat, 0);
7694 assert_eq!(final_hop.cltv_expiry_delta, 0);
7699 fn blinded_path_routing_errors() {
7700 // Check that we can generate a route to a blinded path with the expected hops.
7701 let (secp_ctx, network, _, _, logger) = build_graph();
7702 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7703 let network_graph = network.read_only();
7705 let scorer = ln_test_utils::TestScorer::new();
7706 let random_seed_bytes = [42; 32];
7708 let mut invalid_blinded_path = BlindedPath {
7709 introduction_node: IntroductionNode::NodeId(nodes[2]),
7710 blinding_point: ln_test_utils::pubkey(42),
7712 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7715 let blinded_payinfo = BlindedPayInfo {
7717 fee_proportional_millionths: 500,
7718 htlc_minimum_msat: 1000,
7719 htlc_maximum_msat: 100_000_000,
7720 cltv_expiry_delta: 15,
7721 features: BlindedHopFeatures::empty(),
7724 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7725 invalid_blinded_path_2.introduction_node = IntroductionNode::NodeId(ln_test_utils::pubkey(45));
7726 let payment_params = PaymentParameters::blinded(vec![
7727 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7728 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7729 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7730 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7731 &scorer, &Default::default(), &random_seed_bytes)
7733 Err(LightningError { err, .. }) => {
7734 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7736 _ => panic!("Expected error")
7739 invalid_blinded_path.introduction_node = IntroductionNode::NodeId(our_id);
7740 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7741 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7742 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7743 &Default::default(), &random_seed_bytes)
7745 Err(LightningError { err, .. }) => {
7746 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7748 _ => panic!("Expected error")
7751 invalid_blinded_path.introduction_node = IntroductionNode::NodeId(ln_test_utils::pubkey(46));
7752 invalid_blinded_path.blinded_hops.clear();
7753 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7754 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7755 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7756 &Default::default(), &random_seed_bytes)
7758 Err(LightningError { err, .. }) => {
7759 assert_eq!(err, "0-hop blinded path provided");
7761 _ => panic!("Expected error")
7766 fn matching_intro_node_paths_provided() {
7767 // Check that if multiple blinded paths with the same intro node are provided in payment
7768 // parameters, we'll return the correct paths in the resulting MPP route.
7769 let (secp_ctx, network, _, _, logger) = build_graph();
7770 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7771 let network_graph = network.read_only();
7773 let scorer = ln_test_utils::TestScorer::new();
7774 let random_seed_bytes = [42; 32];
7775 let config = UserConfig::default();
7777 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7778 let blinded_path_1 = BlindedPath {
7779 introduction_node: IntroductionNode::NodeId(nodes[2]),
7780 blinding_point: ln_test_utils::pubkey(42),
7782 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7783 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7786 let blinded_payinfo_1 = BlindedPayInfo {
7788 fee_proportional_millionths: 0,
7789 htlc_minimum_msat: 0,
7790 htlc_maximum_msat: 30_000,
7791 cltv_expiry_delta: 0,
7792 features: BlindedHopFeatures::empty(),
7795 let mut blinded_path_2 = blinded_path_1.clone();
7796 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7797 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7798 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7800 let blinded_hints = vec![
7801 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7802 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7804 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7805 .with_bolt12_features(bolt12_features).unwrap();
7807 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7808 route_params.max_total_routing_fee_msat = Some(100_000);
7809 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7810 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7811 assert_eq!(route.paths.len(), 2);
7812 let mut total_amount_paid_msat = 0;
7813 for path in route.paths.into_iter() {
7814 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7815 if let Some(bt) = &path.blinded_tail {
7816 assert_eq!(bt.blinding_point,
7817 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7818 .map(|(_, bp)| bp.blinding_point).unwrap());
7819 } else { panic!(); }
7820 total_amount_paid_msat += path.final_value_msat();
7822 assert_eq!(total_amount_paid_msat, 100_000);
7826 fn direct_to_intro_node() {
7827 // This previously caused a debug panic in the router when asserting
7828 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7829 // direct channels we failed to account for the fee charged for use of the blinded path.
7832 // node0 -1(1)2 - node1
7833 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7834 // doesn't account for the blinded path fee.
7836 let secp_ctx = Secp256k1::new();
7837 let logger = Arc::new(ln_test_utils::TestLogger::new());
7838 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7839 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7840 let scorer = ln_test_utils::TestScorer::new();
7841 let random_seed_bytes = [42; 32];
7843 let amt_msat = 10_000_000;
7844 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7845 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7846 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7847 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7848 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7849 short_channel_id: 1,
7851 message_flags: 1, // Only must_be_one
7853 cltv_expiry_delta: 42,
7854 htlc_minimum_msat: 1_000,
7855 htlc_maximum_msat: 10_000_000,
7857 fee_proportional_millionths: 0,
7858 excess_data: Vec::new()
7860 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7861 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7862 short_channel_id: 1,
7864 message_flags: 1, // Only must_be_one
7866 cltv_expiry_delta: 42,
7867 htlc_minimum_msat: 1_000,
7868 htlc_maximum_msat: 10_000_000,
7870 fee_proportional_millionths: 0,
7871 excess_data: Vec::new()
7873 let first_hops = vec![
7874 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7876 let blinded_path = BlindedPath {
7877 introduction_node: IntroductionNode::NodeId(nodes[1]),
7878 blinding_point: ln_test_utils::pubkey(42),
7880 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7881 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7884 let blinded_payinfo = BlindedPayInfo {
7885 fee_base_msat: 1000,
7886 fee_proportional_millionths: 0,
7887 htlc_minimum_msat: 1000,
7888 htlc_maximum_msat: MAX_VALUE_MSAT,
7889 cltv_expiry_delta: 0,
7890 features: BlindedHopFeatures::empty(),
7892 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7894 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7896 let netgraph = network_graph.read_only();
7897 let route_params = RouteParameters::from_payment_params_and_value(
7898 payment_params.clone(), amt_msat);
7899 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7900 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7901 &Default::default(), &random_seed_bytes) {
7902 assert_eq!(err, "Failed to find a path to the given destination");
7903 } else { panic!("Expected error") }
7905 // Sending an exact amount accounting for the blinded path fee works.
7906 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7907 let route_params = RouteParameters::from_payment_params_and_value(
7908 payment_params, amt_minus_blinded_path_fee);
7909 let route = get_route(&nodes[0], &route_params, &netgraph,
7910 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7911 &Default::default(), &random_seed_bytes).unwrap();
7912 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7913 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7917 fn direct_to_matching_intro_nodes() {
7918 // This previously caused us to enter `unreachable` code in the following situation:
7919 // 1. We add a route candidate for intro_node contributing a high amount
7920 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7921 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7922 // amount, and update our route candidate for intro_node for the lower amount
7923 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7924 // lower contribution amount, but fail (this was previously caused by failure to account for
7925 // blinded path fees when adding first_hop<>intro_node candidates)
7926 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7927 // candidate still thinks its path is contributing the original higher amount. This caused us
7928 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7930 let secp_ctx = Secp256k1::new();
7931 let logger = Arc::new(ln_test_utils::TestLogger::new());
7932 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7933 let scorer = ln_test_utils::TestScorer::new();
7934 let random_seed_bytes = [42; 32];
7935 let config = UserConfig::default();
7937 // Values are taken from the fuzz input that uncovered this panic.
7938 let amt_msat = 21_7020_5185_1403_2640;
7939 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7940 let first_hops = vec![
7941 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7942 18446744073709551615)];
7944 let blinded_path = BlindedPath {
7945 introduction_node: IntroductionNode::NodeId(nodes[1]),
7946 blinding_point: ln_test_utils::pubkey(42),
7948 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7949 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7952 let blinded_payinfo = BlindedPayInfo {
7953 fee_base_msat: 5046_2720,
7954 fee_proportional_millionths: 0,
7955 htlc_minimum_msat: 4503_5996_2737_0496,
7956 htlc_maximum_msat: 45_0359_9627_3704_9600,
7957 cltv_expiry_delta: 0,
7958 features: BlindedHopFeatures::empty(),
7960 let mut blinded_hints = vec![
7961 (blinded_payinfo.clone(), blinded_path.clone()),
7962 (blinded_payinfo.clone(), blinded_path.clone()),
7964 blinded_hints[1].0.fee_base_msat = 419_4304;
7965 blinded_hints[1].0.fee_proportional_millionths = 257;
7966 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7967 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7968 blinded_hints[1].0.cltv_expiry_delta = 0;
7970 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7971 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7972 .with_bolt12_features(bolt12_features).unwrap();
7974 let netgraph = network_graph.read_only();
7975 let route_params = RouteParameters::from_payment_params_and_value(
7976 payment_params, amt_msat);
7977 let route = get_route(&nodes[0], &route_params, &netgraph,
7978 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7979 &Default::default(), &random_seed_bytes).unwrap();
7980 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7981 assert_eq!(route.get_total_amount(), amt_msat);
7985 fn we_are_intro_node_candidate_hops() {
7986 // This previously led to a panic in the router because we'd generate a Path with only a
7987 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7988 // where the origin node is the intro node. We now fully disallow considering candidate hops
7989 // where the origin node is the intro node.
7990 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7991 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7992 let scorer = ln_test_utils::TestScorer::new();
7993 let random_seed_bytes = [42; 32];
7994 let config = UserConfig::default();
7996 // Values are taken from the fuzz input that uncovered this panic.
7997 let amt_msat = 21_7020_5185_1423_0019;
7999 let blinded_path = BlindedPath {
8000 introduction_node: IntroductionNode::NodeId(our_id),
8001 blinding_point: ln_test_utils::pubkey(42),
8003 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8004 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8007 let blinded_payinfo = BlindedPayInfo {
8008 fee_base_msat: 5052_9027,
8009 fee_proportional_millionths: 0,
8010 htlc_minimum_msat: 21_7020_5185_1423_0019,
8011 htlc_maximum_msat: 1844_6744_0737_0955_1615,
8012 cltv_expiry_delta: 0,
8013 features: BlindedHopFeatures::empty(),
8015 let mut blinded_hints = vec![
8016 (blinded_payinfo.clone(), blinded_path.clone()),
8017 (blinded_payinfo.clone(), blinded_path.clone()),
8019 blinded_hints[1].1.introduction_node = IntroductionNode::NodeId(nodes[6]);
8021 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8022 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8023 .with_bolt12_features(bolt12_features.clone()).unwrap();
8025 let netgraph = network_graph.read_only();
8026 let route_params = RouteParameters::from_payment_params_and_value(
8027 payment_params, amt_msat);
8028 if let Err(LightningError { err, .. }) = get_route(
8029 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8031 assert_eq!(err, "Failed to find a path to the given destination");
8036 fn we_are_intro_node_bp_in_final_path_fee_calc() {
8037 // This previously led to a debug panic in the router because we'd find an invalid Path with
8038 // 0 unblinded hops and a blinded tail, leading to the generation of a final
8039 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
8040 // the payment, when it was intended to only include the final value of the payment.
8041 let (secp_ctx, network_graph, _, _, logger) = build_graph();
8042 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8043 let scorer = ln_test_utils::TestScorer::new();
8044 let random_seed_bytes = [42; 32];
8045 let config = UserConfig::default();
8047 // Values are taken from the fuzz input that uncovered this panic.
8048 let amt_msat = 21_7020_5185_1423_0019;
8050 let blinded_path = BlindedPath {
8051 introduction_node: IntroductionNode::NodeId(our_id),
8052 blinding_point: ln_test_utils::pubkey(42),
8054 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8055 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8058 let blinded_payinfo = BlindedPayInfo {
8059 fee_base_msat: 10_4425_1395,
8060 fee_proportional_millionths: 0,
8061 htlc_minimum_msat: 21_7301_9934_9094_0931,
8062 htlc_maximum_msat: 1844_6744_0737_0955_1615,
8063 cltv_expiry_delta: 0,
8064 features: BlindedHopFeatures::empty(),
8066 let mut blinded_hints = vec![
8067 (blinded_payinfo.clone(), blinded_path.clone()),
8068 (blinded_payinfo.clone(), blinded_path.clone()),
8069 (blinded_payinfo.clone(), blinded_path.clone()),
8071 blinded_hints[1].0.fee_base_msat = 5052_9027;
8072 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
8073 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
8075 blinded_hints[2].1.introduction_node = IntroductionNode::NodeId(nodes[6]);
8077 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8078 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8079 .with_bolt12_features(bolt12_features.clone()).unwrap();
8081 let netgraph = network_graph.read_only();
8082 let route_params = RouteParameters::from_payment_params_and_value(
8083 payment_params, amt_msat);
8084 if let Err(LightningError { err, .. }) = get_route(
8085 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8087 assert_eq!(err, "Failed to find a path to the given destination");
8092 fn min_htlc_overpay_violates_max_htlc() {
8093 do_min_htlc_overpay_violates_max_htlc(true);
8094 do_min_htlc_overpay_violates_max_htlc(false);
8096 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
8097 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
8098 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
8099 // to `targets` and build an invalid path with it, and subsequently hit a debug panic asserting
8100 // that the used liquidity for a hop was less than its available liquidity limit.
8101 let secp_ctx = Secp256k1::new();
8102 let logger = Arc::new(ln_test_utils::TestLogger::new());
8103 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8104 let scorer = ln_test_utils::TestScorer::new();
8105 let random_seed_bytes = [42; 32];
8106 let config = UserConfig::default();
8108 // Values are taken from the fuzz input that uncovered this panic.
8109 let amt_msat = 7_4009_8048;
8110 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8111 let first_hop_outbound_capacity = 2_7345_2000;
8112 let first_hops = vec![get_channel_details(
8113 Some(200), nodes[0], channelmanager::provided_init_features(&config),
8114 first_hop_outbound_capacity
8117 let base_fee = 1_6778_3453;
8118 let htlc_min = 2_5165_8240;
8119 let payment_params = if blinded_payee {
8120 let blinded_path = BlindedPath {
8121 introduction_node: IntroductionNode::NodeId(nodes[0]),
8122 blinding_point: ln_test_utils::pubkey(42),
8124 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8125 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8128 let blinded_payinfo = BlindedPayInfo {
8129 fee_base_msat: base_fee,
8130 fee_proportional_millionths: 0,
8131 htlc_minimum_msat: htlc_min,
8132 htlc_maximum_msat: htlc_min * 1000,
8133 cltv_expiry_delta: 0,
8134 features: BlindedHopFeatures::empty(),
8136 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8137 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
8138 .with_bolt12_features(bolt12_features.clone()).unwrap()
8140 let route_hint = RouteHint(vec![RouteHintHop {
8141 src_node_id: nodes[0],
8142 short_channel_id: 42,
8144 base_msat: base_fee,
8145 proportional_millionths: 0,
8147 cltv_expiry_delta: 10,
8148 htlc_minimum_msat: Some(htlc_min),
8149 htlc_maximum_msat: None,
8152 PaymentParameters::from_node_id(nodes[1], 42)
8153 .with_route_hints(vec![route_hint]).unwrap()
8154 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8157 let netgraph = network_graph.read_only();
8158 let route_params = RouteParameters::from_payment_params_and_value(
8159 payment_params, amt_msat);
8160 if let Err(LightningError { err, .. }) = get_route(
8161 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8162 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8164 assert_eq!(err, "Failed to find a path to the given destination");
8169 fn previously_used_liquidity_violates_max_htlc() {
8170 do_previously_used_liquidity_violates_max_htlc(true);
8171 do_previously_used_liquidity_violates_max_htlc(false);
8174 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
8175 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
8176 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
8177 // candidate. In this case, the candidate does not have enough due to a previous path taking up
8178 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
8179 // asserting that the used liquidity for a hop was less than its available liquidity limit.
8180 let secp_ctx = Secp256k1::new();
8181 let logger = Arc::new(ln_test_utils::TestLogger::new());
8182 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8183 let scorer = ln_test_utils::TestScorer::new();
8184 let random_seed_bytes = [42; 32];
8185 let config = UserConfig::default();
8187 // Values are taken from the fuzz input that uncovered this panic.
8188 let amt_msat = 52_4288;
8189 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8190 let first_hops = vec![get_channel_details(
8191 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
8192 ), get_channel_details(
8193 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
8196 let base_fees = [0, 425_9840, 0, 0];
8197 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
8198 let payment_params = if blinded_payee {
8199 let blinded_path = BlindedPath {
8200 introduction_node: IntroductionNode::NodeId(nodes[0]),
8201 blinding_point: ln_test_utils::pubkey(42),
8203 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8204 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8207 let mut blinded_hints = Vec::new();
8208 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
8209 blinded_hints.push((BlindedPayInfo {
8210 fee_base_msat: *base_fee,
8211 fee_proportional_millionths: 0,
8212 htlc_minimum_msat: *htlc_min,
8213 htlc_maximum_msat: htlc_min * 100,
8214 cltv_expiry_delta: 10,
8215 features: BlindedHopFeatures::empty(),
8216 }, blinded_path.clone()));
8218 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8219 PaymentParameters::blinded(blinded_hints.clone())
8220 .with_bolt12_features(bolt12_features.clone()).unwrap()
8222 let mut route_hints = Vec::new();
8223 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
8224 route_hints.push(RouteHint(vec![RouteHintHop {
8225 src_node_id: nodes[0],
8226 short_channel_id: 42 + idx as u64,
8228 base_msat: *base_fee,
8229 proportional_millionths: 0,
8231 cltv_expiry_delta: 10,
8232 htlc_minimum_msat: Some(*htlc_min),
8233 htlc_maximum_msat: Some(htlc_min * 100),
8236 PaymentParameters::from_node_id(nodes[1], 42)
8237 .with_route_hints(route_hints).unwrap()
8238 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8241 let netgraph = network_graph.read_only();
8242 let route_params = RouteParameters::from_payment_params_and_value(
8243 payment_params, amt_msat);
8245 let route = get_route(
8246 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8247 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8249 assert_eq!(route.paths.len(), 1);
8250 assert_eq!(route.get_total_amount(), amt_msat);
8254 fn candidate_path_min() {
8255 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
8256 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
8257 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
8258 // would add a connecting first_hop node that did not have enough contribution amount, leading
8259 // to a debug panic upon invalid path construction.
8260 let secp_ctx = Secp256k1::new();
8261 let logger = Arc::new(ln_test_utils::TestLogger::new());
8262 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8263 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
8264 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8265 let random_seed_bytes = [42; 32];
8266 let config = UserConfig::default();
8268 // Values are taken from the fuzz input that uncovered this panic.
8269 let amt_msat = 7_4009_8048;
8270 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
8271 let first_hops = vec![get_channel_details(
8272 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
8275 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
8276 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8277 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8278 short_channel_id: 6,
8280 message_flags: 1, // Only must_be_one
8282 cltv_expiry_delta: (6 << 4) | 0,
8283 htlc_minimum_msat: 0,
8284 htlc_maximum_msat: MAX_VALUE_MSAT,
8286 fee_proportional_millionths: 0,
8287 excess_data: Vec::new()
8289 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
8291 let htlc_min = 2_5165_8240;
8292 let blinded_hints = vec![
8294 fee_base_msat: 1_6778_3453,
8295 fee_proportional_millionths: 0,
8296 htlc_minimum_msat: htlc_min,
8297 htlc_maximum_msat: htlc_min * 100,
8298 cltv_expiry_delta: 10,
8299 features: BlindedHopFeatures::empty(),
8301 introduction_node: IntroductionNode::NodeId(nodes[0]),
8302 blinding_point: ln_test_utils::pubkey(42),
8304 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8305 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8309 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8310 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8311 .with_bolt12_features(bolt12_features.clone()).unwrap();
8312 let route_params = RouteParameters::from_payment_params_and_value(
8313 payment_params, amt_msat);
8314 let netgraph = network_graph.read_only();
8316 if let Err(LightningError { err, .. }) = get_route(
8317 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8318 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8321 assert_eq!(err, "Failed to find a path to the given destination");
8326 fn path_contribution_includes_min_htlc_overpay() {
8327 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
8328 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
8329 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
8330 // selection, both tested here.
8331 let secp_ctx = Secp256k1::new();
8332 let logger = Arc::new(ln_test_utils::TestLogger::new());
8333 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8334 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8335 let random_seed_bytes = [42; 32];
8336 let config = UserConfig::default();
8338 // Values are taken from the fuzz input that uncovered this panic.
8339 let amt_msat = 562_0000;
8340 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8341 let first_hops = vec![
8342 get_channel_details(
8343 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
8347 let htlc_mins = [49_0000, 1125_0000];
8348 let payment_params = {
8349 let blinded_path = BlindedPath {
8350 introduction_node: IntroductionNode::NodeId(nodes[0]),
8351 blinding_point: ln_test_utils::pubkey(42),
8353 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8354 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8357 let mut blinded_hints = Vec::new();
8358 for htlc_min in htlc_mins.iter() {
8359 blinded_hints.push((BlindedPayInfo {
8361 fee_proportional_millionths: 0,
8362 htlc_minimum_msat: *htlc_min,
8363 htlc_maximum_msat: *htlc_min * 100,
8364 cltv_expiry_delta: 10,
8365 features: BlindedHopFeatures::empty(),
8366 }, blinded_path.clone()));
8368 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8369 PaymentParameters::blinded(blinded_hints.clone())
8370 .with_bolt12_features(bolt12_features.clone()).unwrap()
8373 let netgraph = network_graph.read_only();
8374 let route_params = RouteParameters::from_payment_params_and_value(
8375 payment_params, amt_msat);
8376 let route = get_route(
8377 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8378 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8381 assert_eq!(route.paths.len(), 1);
8382 assert_eq!(route.get_total_amount(), amt_msat);
8386 fn first_hop_preferred_over_hint() {
8387 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
8388 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
8389 let secp_ctx = Secp256k1::new();
8390 let logger = Arc::new(ln_test_utils::TestLogger::new());
8391 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8392 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
8393 let scorer = ln_test_utils::TestScorer::new();
8394 let random_seed_bytes = [42; 32];
8395 let config = UserConfig::default();
8397 let amt_msat = 1_000_000;
8398 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
8400 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
8401 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
8402 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8403 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8404 short_channel_id: 1,
8406 message_flags: 1, // Only must_be_one
8408 cltv_expiry_delta: 42,
8409 htlc_minimum_msat: 1_000,
8410 htlc_maximum_msat: 10_000_000,
8412 fee_proportional_millionths: 0,
8413 excess_data: Vec::new()
8415 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8416 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8417 short_channel_id: 1,
8419 message_flags: 1, // Only must_be_one
8421 cltv_expiry_delta: 42,
8422 htlc_minimum_msat: 1_000,
8423 htlc_maximum_msat: 10_000_000,
8425 fee_proportional_millionths: 0,
8426 excess_data: Vec::new()
8429 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
8430 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
8431 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8432 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8433 short_channel_id: 2,
8435 message_flags: 1, // Only must_be_one
8437 cltv_expiry_delta: 42,
8438 htlc_minimum_msat: 1_000,
8439 htlc_maximum_msat: 10_000_000,
8441 fee_proportional_millionths: 0,
8442 excess_data: Vec::new()
8444 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8445 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8446 short_channel_id: 2,
8448 message_flags: 1, // Only must_be_one
8450 cltv_expiry_delta: 42,
8451 htlc_minimum_msat: 1_000,
8452 htlc_maximum_msat: 10_000_000,
8454 fee_proportional_millionths: 0,
8455 excess_data: Vec::new()
8458 let dest_node_id = nodes[2];
8460 let route_hint = RouteHint(vec![RouteHintHop {
8461 src_node_id: our_node_id,
8462 short_channel_id: 44,
8465 proportional_millionths: 0,
8467 cltv_expiry_delta: 10,
8468 htlc_minimum_msat: None,
8469 htlc_maximum_msat: Some(5_000_000),
8472 src_node_id: nodes[0],
8473 short_channel_id: 45,
8476 proportional_millionths: 0,
8478 cltv_expiry_delta: 10,
8479 htlc_minimum_msat: None,
8480 htlc_maximum_msat: None,
8483 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8484 .with_route_hints(vec![route_hint]).unwrap()
8485 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8486 let route_params = RouteParameters::from_payment_params_and_value(
8487 payment_params, amt_msat);
8489 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8491 let first_hop = get_channel_details(Some(1), nodes[0],
8492 channelmanager::provided_init_features(&config), 999_999);
8493 let first_hops = vec![first_hop];
8495 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8496 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8497 &Default::default(), &random_seed_bytes).unwrap();
8498 assert_eq!(route.paths.len(), 1);
8499 assert_eq!(route.get_total_amount(), amt_msat);
8500 assert_eq!(route.paths[0].hops.len(), 2);
8501 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8502 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8503 assert_eq!(route.get_total_fees(), 123);
8505 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8506 // for a first hop channel.
8507 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8508 first_hop.outbound_scid_alias = Some(44);
8509 let first_hops = vec![first_hop];
8511 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8512 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8513 &Default::default(), &random_seed_bytes);
8514 assert!(route_res.is_err());
8516 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8517 // use the cheaper second hop of the route hint.
8518 let mut first_hop = get_channel_details(Some(1), nodes[0],
8519 channelmanager::provided_init_features(&config), 10_000_000);
8520 first_hop.outbound_scid_alias = Some(44);
8521 let first_hops = vec![first_hop];
8523 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8524 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8525 &Default::default(), &random_seed_bytes).unwrap();
8526 assert_eq!(route.paths.len(), 1);
8527 assert_eq!(route.get_total_amount(), amt_msat);
8528 assert_eq!(route.paths[0].hops.len(), 2);
8529 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8530 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8531 assert_eq!(route.get_total_fees(), 123);
8535 fn allow_us_being_first_hint() {
8536 // Check that we consider a route hint even if we are the src of the first hop.
8537 let secp_ctx = Secp256k1::new();
8538 let logger = Arc::new(ln_test_utils::TestLogger::new());
8539 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8540 let scorer = ln_test_utils::TestScorer::new();
8541 let random_seed_bytes = [42; 32];
8542 let config = UserConfig::default();
8544 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8546 let amt_msat = 1_000_000;
8547 let dest_node_id = nodes[1];
8549 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8550 let first_hops = vec![first_hop];
8552 let route_hint = RouteHint(vec![RouteHintHop {
8553 src_node_id: our_node_id,
8554 short_channel_id: 44,
8557 proportional_millionths: 0,
8559 cltv_expiry_delta: 10,
8560 htlc_minimum_msat: None,
8561 htlc_maximum_msat: None,
8564 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8565 .with_route_hints(vec![route_hint]).unwrap()
8566 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8568 let route_params = RouteParameters::from_payment_params_and_value(
8569 payment_params, amt_msat);
8572 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8573 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8574 &Default::default(), &random_seed_bytes).unwrap();
8576 assert_eq!(route.paths.len(), 1);
8577 assert_eq!(route.get_total_amount(), amt_msat);
8578 assert_eq!(route.get_total_fees(), 0);
8579 assert_eq!(route.paths[0].hops.len(), 1);
8581 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8585 #[cfg(all(any(test, ldk_bench), feature = "std"))]
8586 pub(crate) mod bench_utils {
8590 use bitcoin::hashes::Hash;
8591 use bitcoin::secp256k1::SecretKey;
8593 use crate::chain::transaction::OutPoint;
8594 use crate::routing::scoring::{ProbabilisticScorer, ScoreUpdate};
8595 use crate::ln::channel_state::{ChannelCounterparty, ChannelShutdownState};
8596 use crate::ln::channelmanager;
8597 use crate::ln::types::ChannelId;
8598 use crate::util::config::UserConfig;
8599 use crate::util::test_utils::TestLogger;
8600 use crate::sync::Arc;
8602 /// Tries to open a network graph file, or panics with a URL to fetch it.
8603 pub(crate) fn get_graph_scorer_file() -> Result<(std::fs::File, std::fs::File), &'static str> {
8604 let load_file = |fname, err_str| {
8605 File::open(fname) // By default we're run in RL/lightning
8606 .or_else(|_| File::open(&format!("lightning/{}", fname))) // We may be run manually in RL/
8607 .or_else(|_| { // Fall back to guessing based on the binary location
8608 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8609 let mut path = std::env::current_exe().unwrap();
8610 path.pop(); // lightning-...
8612 path.pop(); // debug
8613 path.pop(); // target
8614 path.push("lightning");
8618 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8619 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8620 let mut path = std::env::current_exe().unwrap();
8621 path.pop(); // bench...
8623 path.pop(); // debug
8624 path.pop(); // target
8625 path.pop(); // bench
8626 path.push("lightning");
8630 .map_err(|_| err_str)
8632 let graph_res = load_file(
8633 "net_graph-2023-12-10.bin",
8634 "Please fetch https://bitcoin.ninja/ldk-net_graph-v0.0.118-2023-12-10.bin and place it at lightning/net_graph-2023-12-10.bin"
8636 let scorer_res = load_file(
8637 "scorer-2023-12-10.bin",
8638 "Please fetch https://bitcoin.ninja/ldk-scorer-v0.0.118-2023-12-10.bin and place it at lightning/scorer-2023-12-10.bin"
8640 #[cfg(require_route_graph_test)]
8641 return Ok((graph_res.unwrap(), scorer_res.unwrap()));
8642 #[cfg(not(require_route_graph_test))]
8643 return Ok((graph_res?, scorer_res?));
8646 pub(crate) fn read_graph_scorer(logger: &TestLogger)
8647 -> Result<(Arc<NetworkGraph<&TestLogger>>, ProbabilisticScorer<Arc<NetworkGraph<&TestLogger>>, &TestLogger>), &'static str> {
8648 let (mut graph_file, mut scorer_file) = get_graph_scorer_file()?;
8649 let graph = Arc::new(NetworkGraph::read(&mut graph_file, logger).unwrap());
8650 let scorer_args = (Default::default(), Arc::clone(&graph), logger);
8651 let scorer = ProbabilisticScorer::read(&mut scorer_file, scorer_args).unwrap();
8655 pub(crate) fn payer_pubkey() -> PublicKey {
8656 let secp_ctx = Secp256k1::new();
8657 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8661 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8663 channel_id: ChannelId::new_zero(),
8664 counterparty: ChannelCounterparty {
8665 features: channelmanager::provided_init_features(&UserConfig::default()),
8667 unspendable_punishment_reserve: 0,
8668 forwarding_info: None,
8669 outbound_htlc_minimum_msat: None,
8670 outbound_htlc_maximum_msat: None,
8672 funding_txo: Some(OutPoint {
8673 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8676 short_channel_id: Some(1),
8677 inbound_scid_alias: None,
8678 outbound_scid_alias: None,
8679 channel_value_satoshis: 10_000_000_000,
8681 balance_msat: 10_000_000_000,
8682 outbound_capacity_msat: 10_000_000_000,
8683 next_outbound_htlc_minimum_msat: 0,
8684 next_outbound_htlc_limit_msat: 10_000_000_000,
8685 inbound_capacity_msat: 0,
8686 unspendable_punishment_reserve: None,
8687 confirmations_required: None,
8688 confirmations: None,
8689 force_close_spend_delay: None,
8691 is_channel_ready: true,
8694 inbound_htlc_minimum_msat: None,
8695 inbound_htlc_maximum_msat: None,
8697 feerate_sat_per_1000_weight: None,
8698 channel_shutdown_state: Some(ChannelShutdownState::NotShuttingDown),
8699 pending_inbound_htlcs: Vec::new(),
8700 pending_outbound_htlcs: Vec::new(),
8704 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8705 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8706 starting_amount: u64, route_count: usize,
8707 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8708 let payer = payer_pubkey();
8709 let random_seed_bytes = [42; 32];
8711 let nodes = graph.read_only().nodes().clone();
8712 let mut route_endpoints = Vec::new();
8713 for _ in 0..route_count {
8715 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8716 let src = PublicKey::from_slice(nodes.unordered_keys()
8717 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8718 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8719 let dst = PublicKey::from_slice(nodes.unordered_keys()
8720 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8721 let params = PaymentParameters::from_node_id(dst, 42)
8722 .with_bolt11_features(features.clone()).unwrap();
8723 let first_hop = first_hop(src);
8724 let amt_msat = starting_amount + seed % 1_000_000;
8725 let route_params = RouteParameters::from_payment_params_and_value(
8726 params.clone(), amt_msat);
8728 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8729 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8731 route_endpoints.push((first_hop, params, amt_msat));
8744 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8745 use crate::ln::channelmanager;
8746 use crate::ln::features::Bolt11InvoiceFeatures;
8747 use crate::routing::gossip::NetworkGraph;
8748 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScoringFeeParameters};
8749 use crate::util::config::UserConfig;
8750 use crate::util::logger::{Logger, Record};
8751 use crate::util::test_utils::TestLogger;
8753 use criterion::Criterion;
8755 struct DummyLogger {}
8756 impl Logger for DummyLogger {
8757 fn log(&self, _record: Record) {}
8760 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8761 let logger = TestLogger::new();
8762 let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap();
8763 let scorer = FixedPenaltyScorer::with_penalty(0);
8764 generate_routes(bench, &network_graph, scorer, &Default::default(),
8765 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8768 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8769 let logger = TestLogger::new();
8770 let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap();
8771 let scorer = FixedPenaltyScorer::with_penalty(0);
8772 generate_routes(bench, &network_graph, scorer, &Default::default(),
8773 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8774 "generate_mpp_routes_with_zero_penalty_scorer");
8777 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8778 let logger = TestLogger::new();
8779 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8780 let params = ProbabilisticScoringFeeParameters::default();
8781 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8782 "generate_routes_with_probabilistic_scorer");
8785 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8786 let logger = TestLogger::new();
8787 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8788 let params = ProbabilisticScoringFeeParameters::default();
8789 generate_routes(bench, &network_graph, scorer, ¶ms,
8790 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8791 "generate_mpp_routes_with_probabilistic_scorer");
8794 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8795 let logger = TestLogger::new();
8796 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8797 let params = ProbabilisticScoringFeeParameters::default();
8798 generate_routes(bench, &network_graph, scorer, ¶ms,
8799 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8800 "generate_large_mpp_routes_with_probabilistic_scorer");
8803 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8804 let logger = TestLogger::new();
8805 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8806 let mut params = ProbabilisticScoringFeeParameters::default();
8807 params.linear_success_probability = false;
8808 generate_routes(bench, &network_graph, scorer, ¶ms,
8809 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8810 "generate_routes_with_nonlinear_probabilistic_scorer");
8813 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8814 let logger = TestLogger::new();
8815 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8816 let mut params = ProbabilisticScoringFeeParameters::default();
8817 params.linear_success_probability = false;
8818 generate_routes(bench, &network_graph, scorer, ¶ms,
8819 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8820 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8823 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8824 let logger = TestLogger::new();
8825 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8826 let mut params = ProbabilisticScoringFeeParameters::default();
8827 params.linear_success_probability = false;
8828 generate_routes(bench, &network_graph, scorer, ¶ms,
8829 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8830 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8833 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8834 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8835 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8836 bench_name: &'static str,
8838 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8839 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8841 // ...then benchmark finding paths between the nodes we learned.
8842 do_route_bench(bench, graph, scorer, score_params, bench_name, route_endpoints);
8846 fn do_route_bench<S: ScoreLookUp + ScoreUpdate>(
8847 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, scorer: S,
8848 score_params: &S::ScoreParams, bench_name: &'static str,
8849 route_endpoints: Vec<(ChannelDetails, PaymentParameters, u64)>,
8851 let payer = bench_utils::payer_pubkey();
8852 let random_seed_bytes = [42; 32];
8855 bench.bench_function(bench_name, |b| b.iter(|| {
8856 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8857 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8858 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8859 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());