1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The router finds paths within a [`NetworkGraph`] for a payment.
12 use bitcoin::secp256k1::{PublicKey, Secp256k1, self};
14 use crate::blinded_path::{BlindedHop, BlindedPath};
15 use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, PaymentConstraints, PaymentRelay, ReceiveTlvs};
16 use crate::ln::PaymentHash;
17 use crate::ln::channelmanager::{ChannelDetails, PaymentId, MIN_FINAL_CLTV_EXPIRY_DELTA};
18 use crate::ln::features::{BlindedHopFeatures, Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
19 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice};
21 use crate::onion_message::messenger::{DefaultMessageRouter, Destination, MessageRouter, OnionMessagePath};
22 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
23 use crate::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp};
24 use crate::sign::EntropySource;
25 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
26 use crate::util::logger::{Level, Logger};
27 use crate::crypto::chacha20::ChaCha20;
30 use crate::prelude::*;
31 use alloc::collections::BinaryHeap;
35 /// A [`Router`] implemented using [`find_route`].
36 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> where
38 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
39 ES::Target: EntropySource,
46 message_router: DefaultMessageRouter<G, L, ES>,
49 impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref + Clone, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> DefaultRouter<G, L, ES, S, SP, Sc> where
51 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
52 ES::Target: EntropySource,
54 /// Creates a new router.
55 pub fn new(network_graph: G, logger: L, entropy_source: ES, scorer: S, score_params: SP) -> Self {
56 let message_router = DefaultMessageRouter::new(network_graph.clone(), entropy_source.clone());
57 Self { network_graph, logger, entropy_source, scorer, score_params, message_router }
61 impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> Router for DefaultRouter<G, L, ES, S, SP, Sc> where
63 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
64 ES::Target: EntropySource,
69 params: &RouteParameters,
70 first_hops: Option<&[&ChannelDetails]>,
71 inflight_htlcs: InFlightHtlcs
72 ) -> Result<Route, LightningError> {
73 let random_seed_bytes = self.entropy_source.get_secure_random_bytes();
75 payer, params, &self.network_graph, first_hops, &*self.logger,
76 &ScorerAccountingForInFlightHtlcs::new(self.scorer.read_lock(), &inflight_htlcs),
82 fn create_blinded_payment_paths<
83 T: secp256k1::Signing + secp256k1::Verification
85 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
86 amount_msats: u64, secp_ctx: &Secp256k1<T>
87 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
88 // Limit the number of blinded paths that are computed.
89 const MAX_PAYMENT_PATHS: usize = 3;
91 // Ensure peers have at least three channels so that it is more difficult to infer the
92 // recipient's node_id.
93 const MIN_PEER_CHANNELS: usize = 3;
95 let network_graph = self.network_graph.deref().read_only();
96 let paths = first_hops.into_iter()
97 .filter(|details| details.counterparty.features.supports_route_blinding())
98 .filter(|details| amount_msats <= details.inbound_capacity_msat)
99 .filter(|details| amount_msats >= details.inbound_htlc_minimum_msat.unwrap_or(0))
100 .filter(|details| amount_msats <= details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX))
101 .filter(|details| network_graph
102 .node(&NodeId::from_pubkey(&details.counterparty.node_id))
103 .map(|node_info| node_info.channels.len() >= MIN_PEER_CHANNELS)
106 .filter_map(|details| {
107 let short_channel_id = match details.get_inbound_payment_scid() {
108 Some(short_channel_id) => short_channel_id,
111 let payment_relay: PaymentRelay = match details.counterparty.forwarding_info {
112 Some(forwarding_info) => match forwarding_info.try_into() {
113 Ok(payment_relay) => payment_relay,
114 Err(()) => return None,
119 let cltv_expiry_delta = payment_relay.cltv_expiry_delta as u32;
120 let payment_constraints = PaymentConstraints {
121 max_cltv_expiry: tlvs.payment_constraints.max_cltv_expiry + cltv_expiry_delta,
122 htlc_minimum_msat: details.inbound_htlc_minimum_msat.unwrap_or(0),
129 features: BlindedHopFeatures::empty(),
131 node_id: details.counterparty.node_id,
132 htlc_maximum_msat: details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX),
135 .map(|forward_node| {
136 BlindedPath::new_for_payment(
137 &[forward_node], recipient, tlvs.clone(), u64::MAX, MIN_FINAL_CLTV_EXPIRY_DELTA,
138 &*self.entropy_source, secp_ctx
141 .take(MAX_PAYMENT_PATHS)
142 .collect::<Result<Vec<_>, _>>();
145 Ok(paths) if !paths.is_empty() => Ok(paths),
147 if network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient)) {
148 BlindedPath::one_hop_for_payment(
149 recipient, tlvs, MIN_FINAL_CLTV_EXPIRY_DELTA, &*self.entropy_source, secp_ctx
150 ).map(|path| vec![path])
159 impl< G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> MessageRouter for DefaultRouter<G, L, ES, S, SP, Sc> where
161 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
162 ES::Target: EntropySource,
165 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
166 ) -> Result<OnionMessagePath, ()> {
167 self.message_router.find_path(sender, peers, destination)
170 fn create_blinded_paths<
171 T: secp256k1::Signing + secp256k1::Verification
173 &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
174 ) -> Result<Vec<BlindedPath>, ()> {
175 self.message_router.create_blinded_paths(recipient, peers, secp_ctx)
179 /// A trait defining behavior for routing a payment.
180 pub trait Router: MessageRouter {
181 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
183 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
184 /// and [`RouteParameters::final_value_msat`], respectively.
186 &self, payer: &PublicKey, route_params: &RouteParameters,
187 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
188 ) -> Result<Route, LightningError>;
190 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
192 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
193 /// and [`RouteParameters::final_value_msat`], respectively.
195 /// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
197 fn find_route_with_id(
198 &self, payer: &PublicKey, route_params: &RouteParameters,
199 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
200 _payment_hash: PaymentHash, _payment_id: PaymentId
201 ) -> Result<Route, LightningError> {
202 self.find_route(payer, route_params, first_hops, inflight_htlcs)
205 /// Creates [`BlindedPath`]s for payment to the `recipient` node. The channels in `first_hops`
206 /// are assumed to be with the `recipient`'s peers. The payment secret and any constraints are
208 fn create_blinded_payment_paths<
209 T: secp256k1::Signing + secp256k1::Verification
211 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
212 amount_msats: u64, secp_ctx: &Secp256k1<T>
213 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()>;
216 /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
218 /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
221 /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
222 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> where S::Target: ScoreLookUp {
224 // Maps a channel's short channel id and its direction to the liquidity used up.
225 inflight_htlcs: &'a InFlightHtlcs,
227 impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
228 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
229 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
230 ScorerAccountingForInFlightHtlcs {
237 impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
238 type ScoreParams = <S::Target as ScoreLookUp>::ScoreParams;
239 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
240 let target = match candidate.target() {
241 Some(target) => target,
242 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
244 let short_channel_id = match candidate.short_channel_id() {
245 Some(short_channel_id) => short_channel_id,
246 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
248 let source = candidate.source();
249 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
250 &source, &target, short_channel_id
252 let usage = ChannelUsage {
253 inflight_htlc_msat: usage.inflight_htlc_msat.saturating_add(used_liquidity),
257 self.scorer.channel_penalty_msat(candidate, usage, score_params)
259 self.scorer.channel_penalty_msat(candidate, usage, score_params)
264 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
265 /// in-use channel liquidity.
267 pub struct InFlightHtlcs(
268 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
269 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
270 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
272 HashMap<(u64, bool), u64>
276 /// Constructs an empty `InFlightHtlcs`.
277 pub fn new() -> Self { InFlightHtlcs(new_hash_map()) }
279 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
280 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
281 if path.hops.is_empty() { return };
283 let mut cumulative_msat = 0;
284 if let Some(tail) = &path.blinded_tail {
285 cumulative_msat += tail.final_value_msat;
288 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
289 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
290 // the router excludes the payer node. In the following lines, the payer's information is
291 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
292 // in our sliding window of two.
293 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
294 .map(|hop| hop.pubkey)
295 .chain(core::iter::once(payer_node_id));
297 // Taking the reversed vector from above, we zip it with just the reversed hops list to
298 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
299 // the total amount sent.
300 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
301 cumulative_msat += next_hop.fee_msat;
303 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
304 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
305 .or_insert(cumulative_msat);
309 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
311 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
313 .entry((channel_scid, source < target))
314 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
315 .or_insert(used_msat);
318 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
320 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
321 self.0.get(&(channel_scid, source < target)).map(|v| *v)
325 impl Writeable for InFlightHtlcs {
326 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
329 impl Readable for InFlightHtlcs {
330 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
331 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
332 Ok(Self(infight_map))
336 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
337 /// that leads to it.
338 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
339 pub struct RouteHop {
340 /// The node_id of the node at this hop.
341 pub pubkey: PublicKey,
342 /// The node_announcement features of the node at this hop. For the last hop, these may be
343 /// amended to match the features present in the invoice this node generated.
344 pub node_features: NodeFeatures,
345 /// The channel that should be used from the previous hop to reach this node.
346 pub short_channel_id: u64,
347 /// The channel_announcement features of the channel that should be used from the previous hop
348 /// to reach this node.
349 pub channel_features: ChannelFeatures,
350 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
351 /// If this is the last hop in [`Path::hops`]:
352 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
353 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
355 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
357 /// The CLTV delta added for this hop.
358 /// If this is the last hop in [`Path::hops`]:
359 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
360 /// * otherwise, this is the CLTV delta expected at the destination
362 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
363 pub cltv_expiry_delta: u32,
364 /// Indicates whether this hop is possibly announced in the public network graph.
366 /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
367 /// either know for sure it's announced in the public graph, or if any public channels exist
368 /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
369 /// the channel to be unannounced.
371 /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
372 pub maybe_announced_channel: bool,
375 impl_writeable_tlv_based!(RouteHop, {
376 (0, pubkey, required),
377 (1, maybe_announced_channel, (default_value, true)),
378 (2, node_features, required),
379 (4, short_channel_id, required),
380 (6, channel_features, required),
381 (8, fee_msat, required),
382 (10, cltv_expiry_delta, required),
385 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
386 /// their [`Bolt12Invoice`].
388 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
389 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
390 pub struct BlindedTail {
391 /// The hops of the [`BlindedPath`] provided by the recipient.
393 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
394 pub hops: Vec<BlindedHop>,
395 /// The blinding point of the [`BlindedPath`] provided by the recipient.
397 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
398 pub blinding_point: PublicKey,
399 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
400 /// inferring the destination. May be 0.
401 pub excess_final_cltv_expiry_delta: u32,
402 /// The total amount paid on this [`Path`], excluding the fees.
403 pub final_value_msat: u64,
406 impl_writeable_tlv_based!(BlindedTail, {
407 (0, hops, required_vec),
408 (2, blinding_point, required),
409 (4, excess_final_cltv_expiry_delta, required),
410 (6, final_value_msat, required),
413 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
414 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
415 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
417 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
418 pub hops: Vec<RouteHop>,
419 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
420 pub blinded_tail: Option<BlindedTail>,
424 /// Gets the fees for a given path, excluding any excess paid to the recipient.
425 pub fn fee_msat(&self) -> u64 {
426 match &self.blinded_tail {
427 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
429 // Do not count last hop of each path since that's the full value of the payment
430 self.hops.split_last().map_or(0,
431 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
436 /// Gets the total amount paid on this [`Path`], excluding the fees.
437 pub fn final_value_msat(&self) -> u64 {
438 match &self.blinded_tail {
439 Some(blinded_tail) => blinded_tail.final_value_msat,
440 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
444 /// Gets the final hop's CLTV expiry delta.
445 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
446 match &self.blinded_tail {
448 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
453 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
454 /// it can take multiple paths. Each path is composed of one or more hops through the network.
455 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
457 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
458 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
460 pub paths: Vec<Path>,
461 /// The `route_params` parameter passed to [`find_route`].
463 /// This is used by `ChannelManager` to track information which may be required for retries.
465 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
466 pub route_params: Option<RouteParameters>,
470 /// Returns the total amount of fees paid on this [`Route`].
472 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
473 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
474 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
476 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
477 pub fn get_total_fees(&self) -> u64 {
478 let overpaid_value_msat = self.route_params.as_ref()
479 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
480 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
483 /// Returns the total amount paid on this [`Route`], excluding the fees.
485 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
486 /// we had to reach the [`htlc_minimum_msat`] limits.
488 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
489 pub fn get_total_amount(&self) -> u64 {
490 self.paths.iter().map(|path| path.final_value_msat()).sum()
494 impl fmt::Display for Route {
495 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
496 log_route!(self).fmt(f)
500 const SERIALIZATION_VERSION: u8 = 1;
501 const MIN_SERIALIZATION_VERSION: u8 = 1;
503 impl Writeable for Route {
504 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
505 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
506 (self.paths.len() as u64).write(writer)?;
507 let mut blinded_tails = Vec::new();
508 for (idx, path) in self.paths.iter().enumerate() {
509 (path.hops.len() as u8).write(writer)?;
510 for hop in path.hops.iter() {
513 if let Some(blinded_tail) = &path.blinded_tail {
514 if blinded_tails.is_empty() {
515 blinded_tails = Vec::with_capacity(path.hops.len());
517 blinded_tails.push(None);
520 blinded_tails.push(Some(blinded_tail));
521 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
523 write_tlv_fields!(writer, {
524 // For compatibility with LDK versions prior to 0.0.117, we take the individual
525 // RouteParameters' fields and reconstruct them on read.
526 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
527 (2, blinded_tails, optional_vec),
528 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
529 (5, self.route_params.as_ref().and_then(|p| p.max_total_routing_fee_msat), option),
535 impl Readable for Route {
536 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
537 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
538 let path_count: u64 = Readable::read(reader)?;
539 if path_count == 0 { return Err(DecodeError::InvalidValue); }
540 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
541 let mut min_final_cltv_expiry_delta = u32::max_value();
542 for _ in 0..path_count {
543 let hop_count: u8 = Readable::read(reader)?;
544 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
545 for _ in 0..hop_count {
546 hops.push(Readable::read(reader)?);
548 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
549 min_final_cltv_expiry_delta =
550 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
551 paths.push(Path { hops, blinded_tail: None });
553 _init_and_read_len_prefixed_tlv_fields!(reader, {
554 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
555 (2, blinded_tails, optional_vec),
556 (3, final_value_msat, option),
557 (5, max_total_routing_fee_msat, option)
559 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
560 if blinded_tails.len() != 0 {
561 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
562 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
563 path.blinded_tail = blinded_tail_opt;
567 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
568 let route_params = match (payment_params, final_value_msat) {
569 (Some(payment_params), Some(final_value_msat)) => {
570 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
575 Ok(Route { paths, route_params })
579 /// Parameters needed to find a [`Route`].
581 /// Passed to [`find_route`] and [`build_route_from_hops`].
582 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
583 pub struct RouteParameters {
584 /// The parameters of the failed payment path.
585 pub payment_params: PaymentParameters,
587 /// The amount in msats sent on the failed payment path.
588 pub final_value_msat: u64,
590 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
592 /// This limit also applies to the total fees that may arise while retrying failed payment
595 /// Note that values below a few sats may result in some paths being spuriously ignored.
596 pub max_total_routing_fee_msat: Option<u64>,
599 impl RouteParameters {
600 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
602 /// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
603 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
604 Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
608 impl Writeable for RouteParameters {
609 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
610 write_tlv_fields!(writer, {
611 (0, self.payment_params, required),
612 (1, self.max_total_routing_fee_msat, option),
613 (2, self.final_value_msat, required),
614 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
615 // `RouteParameters` directly. For compatibility, we write it here.
616 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
622 impl Readable for RouteParameters {
623 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
624 _init_and_read_len_prefixed_tlv_fields!(reader, {
625 (0, payment_params, (required: ReadableArgs, 0)),
626 (1, max_total_routing_fee_msat, option),
627 (2, final_value_msat, required),
628 (4, final_cltv_delta, option),
630 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
631 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
632 if final_cltv_expiry_delta == &0 {
633 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
638 final_value_msat: final_value_msat.0.unwrap(),
639 max_total_routing_fee_msat,
644 /// Maximum total CTLV difference we allow for a full payment path.
645 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
647 /// Maximum number of paths we allow an (MPP) payment to have.
648 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
649 // limits, but for now more than 10 paths likely carries too much one-path failure.
650 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
652 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
654 // The median hop CLTV expiry delta currently seen in the network.
655 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
657 // During routing, we only consider paths shorter than our maximum length estimate.
658 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
659 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
660 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
662 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
663 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
664 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
665 // (payment_secret and total_msat) = 93 bytes for the final hop.
666 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
667 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
668 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
670 /// Information used to route a payment.
671 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
672 pub struct PaymentParameters {
673 /// Information about the payee, such as their features and route hints for their channels.
676 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
677 pub expiry_time: Option<u64>,
679 /// The maximum total CLTV delta we accept for the route.
680 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
681 pub max_total_cltv_expiry_delta: u32,
683 /// The maximum number of paths that may be used by (MPP) payments.
684 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
685 pub max_path_count: u8,
687 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
688 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
689 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
690 /// increasing failure probability for those paths.
692 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
693 /// restriction have been found. While paths which meet this criteria will be searched for, it
694 /// is ultimately up to the scorer to select them over other paths.
696 /// A value of 0 will allow payments up to and including a channel's total announced usable
697 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
700 pub max_channel_saturation_power_of_half: u8,
702 /// A list of SCIDs which this payment was previously attempted over and which caused the
703 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
705 pub previously_failed_channels: Vec<u64>,
707 /// A list of indices corresponding to blinded paths in [`Payee::Blinded::route_hints`] which this
708 /// payment was previously attempted over and which caused the payment to fail. Future attempts
709 /// for the same payment shouldn't be relayed through any of these blinded paths.
710 pub previously_failed_blinded_path_idxs: Vec<u64>,
713 impl Writeable for PaymentParameters {
714 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
715 let mut clear_hints = &vec![];
716 let mut blinded_hints = &vec![];
718 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
719 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
721 write_tlv_fields!(writer, {
722 (0, self.payee.node_id(), option),
723 (1, self.max_total_cltv_expiry_delta, required),
724 (2, self.payee.features(), option),
725 (3, self.max_path_count, required),
726 (4, *clear_hints, required_vec),
727 (5, self.max_channel_saturation_power_of_half, required),
728 (6, self.expiry_time, option),
729 (7, self.previously_failed_channels, required_vec),
730 (8, *blinded_hints, optional_vec),
731 (9, self.payee.final_cltv_expiry_delta(), option),
732 (11, self.previously_failed_blinded_path_idxs, required_vec),
738 impl ReadableArgs<u32> for PaymentParameters {
739 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
740 _init_and_read_len_prefixed_tlv_fields!(reader, {
741 (0, payee_pubkey, option),
742 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
743 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
744 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
745 (4, clear_route_hints, required_vec),
746 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
747 (6, expiry_time, option),
748 (7, previously_failed_channels, optional_vec),
749 (8, blinded_route_hints, optional_vec),
750 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
751 (11, previously_failed_blinded_path_idxs, optional_vec),
753 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
754 let payee = if blinded_route_hints.len() != 0 {
755 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
757 route_hints: blinded_route_hints,
758 features: features.and_then(|f: Features| f.bolt12()),
762 route_hints: clear_route_hints,
763 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
764 features: features.and_then(|f| f.bolt11()),
765 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
769 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
770 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
772 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
774 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
775 previously_failed_blinded_path_idxs: previously_failed_blinded_path_idxs.unwrap_or(Vec::new()),
781 impl PaymentParameters {
782 /// Creates a payee with the node id of the given `pubkey`.
784 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
786 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
788 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
790 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
791 max_path_count: DEFAULT_MAX_PATH_COUNT,
792 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
793 previously_failed_channels: Vec::new(),
794 previously_failed_blinded_path_idxs: Vec::new(),
798 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
800 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
803 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
804 /// whether your router will be allowed to find a multi-part route for this payment. If you
805 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
806 /// [`RecipientOnionFields::secret_only`].
808 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
809 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
810 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
811 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
812 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
815 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
816 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
817 /// [`PaymentParameters::expiry_time`].
818 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
819 Self::blinded(invoice.payment_paths().to_vec())
820 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
821 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
824 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
825 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
827 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
829 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
830 max_path_count: DEFAULT_MAX_PATH_COUNT,
831 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
832 previously_failed_channels: Vec::new(),
833 previously_failed_blinded_path_idxs: Vec::new(),
837 /// Includes the payee's features. Errors if the parameters were not initialized with
838 /// [`PaymentParameters::from_bolt12_invoice`].
840 /// This is not exported to bindings users since bindings don't support move semantics
841 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
843 Payee::Clear { .. } => Err(()),
844 Payee::Blinded { route_hints, .. } =>
845 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
849 /// Includes the payee's features. Errors if the parameters were initialized with
850 /// [`PaymentParameters::from_bolt12_invoice`].
852 /// This is not exported to bindings users since bindings don't support move semantics
853 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
855 Payee::Blinded { .. } => Err(()),
856 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
858 payee: Payee::Clear {
859 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
865 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
866 /// [`PaymentParameters::from_bolt12_invoice`].
868 /// This is not exported to bindings users since bindings don't support move semantics
869 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
871 Payee::Blinded { .. } => Err(()),
872 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
874 payee: Payee::Clear {
875 route_hints, node_id, features, final_cltv_expiry_delta,
881 /// Includes a payment expiration in seconds relative to the UNIX epoch.
883 /// This is not exported to bindings users since bindings don't support move semantics
884 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
885 Self { expiry_time: Some(expiry_time), ..self }
888 /// Includes a limit for the total CLTV expiry delta which is considered during routing
890 /// This is not exported to bindings users since bindings don't support move semantics
891 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
892 Self { max_total_cltv_expiry_delta, ..self }
895 /// Includes a limit for the maximum number of payment paths that may be used.
897 /// This is not exported to bindings users since bindings don't support move semantics
898 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
899 Self { max_path_count, ..self }
902 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
903 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
905 /// This is not exported to bindings users since bindings don't support move semantics
906 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
907 Self { max_channel_saturation_power_of_half, ..self }
910 pub(crate) fn insert_previously_failed_blinded_path(&mut self, failed_blinded_tail: &BlindedTail) {
911 let mut found_blinded_tail = false;
912 for (idx, (_, path)) in self.payee.blinded_route_hints().iter().enumerate() {
913 if failed_blinded_tail.hops == path.blinded_hops &&
914 failed_blinded_tail.blinding_point == path.blinding_point
916 self.previously_failed_blinded_path_idxs.push(idx as u64);
917 found_blinded_tail = true;
920 debug_assert!(found_blinded_tail);
924 /// The recipient of a payment, differing based on whether they've hidden their identity with route
926 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
928 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
929 /// will be included in the final [`Route`].
931 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
933 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
934 /// Features supported by the payee.
936 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
938 features: Option<Bolt12InvoiceFeatures>,
940 /// The recipient included these route hints in their BOLT11 invoice.
942 /// The node id of the payee.
944 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
945 route_hints: Vec<RouteHint>,
946 /// Features supported by the payee.
948 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
949 /// does not contain any features.
951 /// [`for_keysend`]: PaymentParameters::for_keysend
952 features: Option<Bolt11InvoiceFeatures>,
953 /// The minimum CLTV delta at the end of the route. This value must not be zero.
954 final_cltv_expiry_delta: u32,
959 fn node_id(&self) -> Option<PublicKey> {
961 Self::Clear { node_id, .. } => Some(*node_id),
965 fn node_features(&self) -> Option<NodeFeatures> {
967 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
968 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
971 fn supports_basic_mpp(&self) -> bool {
973 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
974 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
977 fn features(&self) -> Option<FeaturesRef> {
979 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
980 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
983 fn final_cltv_expiry_delta(&self) -> Option<u32> {
985 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
989 pub(crate) fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
991 Self::Blinded { route_hints, .. } => &route_hints[..],
992 Self::Clear { .. } => &[]
996 fn unblinded_route_hints(&self) -> &[RouteHint] {
998 Self::Blinded { .. } => &[],
999 Self::Clear { route_hints, .. } => &route_hints[..]
1004 enum FeaturesRef<'a> {
1005 Bolt11(&'a Bolt11InvoiceFeatures),
1006 Bolt12(&'a Bolt12InvoiceFeatures),
1009 Bolt11(Bolt11InvoiceFeatures),
1010 Bolt12(Bolt12InvoiceFeatures),
1014 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
1016 Self::Bolt12(f) => Some(f),
1020 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
1022 Self::Bolt11(f) => Some(f),
1028 impl<'a> Writeable for FeaturesRef<'a> {
1029 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1031 Self::Bolt11(f) => Ok(f.write(w)?),
1032 Self::Bolt12(f) => Ok(f.write(w)?),
1037 impl ReadableArgs<bool> for Features {
1038 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
1039 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
1040 Ok(Self::Bolt12(Readable::read(reader)?))
1044 /// A list of hops along a payment path terminating with a channel to the recipient.
1045 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1046 pub struct RouteHint(pub Vec<RouteHintHop>);
1048 impl Writeable for RouteHint {
1049 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1050 (self.0.len() as u64).write(writer)?;
1051 for hop in self.0.iter() {
1058 impl Readable for RouteHint {
1059 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1060 let hop_count: u64 = Readable::read(reader)?;
1061 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
1062 for _ in 0..hop_count {
1063 hops.push(Readable::read(reader)?);
1069 /// A channel descriptor for a hop along a payment path.
1071 /// While this generally comes from BOLT 11's `r` field, this struct includes more fields than are
1072 /// available in BOLT 11. Thus, encoding and decoding this via `lightning-invoice` is lossy, as
1073 /// fields not supported in BOLT 11 will be stripped.
1074 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1075 pub struct RouteHintHop {
1076 /// The node_id of the non-target end of the route
1077 pub src_node_id: PublicKey,
1078 /// The short_channel_id of this channel
1079 pub short_channel_id: u64,
1080 /// The fees which must be paid to use this channel
1081 pub fees: RoutingFees,
1082 /// The difference in CLTV values between this node and the next node.
1083 pub cltv_expiry_delta: u16,
1084 /// The minimum value, in msat, which must be relayed to the next hop.
1085 pub htlc_minimum_msat: Option<u64>,
1086 /// The maximum value in msat available for routing with a single HTLC.
1087 pub htlc_maximum_msat: Option<u64>,
1090 impl_writeable_tlv_based!(RouteHintHop, {
1091 (0, src_node_id, required),
1092 (1, htlc_minimum_msat, option),
1093 (2, short_channel_id, required),
1094 (3, htlc_maximum_msat, option),
1095 (4, fees, required),
1096 (6, cltv_expiry_delta, required),
1099 #[derive(Eq, PartialEq)]
1100 #[repr(align(64))] // Force the size to 64 bytes
1101 struct RouteGraphNode {
1104 // The maximum value a yet-to-be-constructed payment path might flow through this node.
1105 // This value is upper-bounded by us by:
1106 // - how much is needed for a path being constructed
1107 // - how much value can channels following this node (up to the destination) can contribute,
1108 // considering their capacity and fees
1109 value_contribution_msat: u64,
1110 total_cltv_delta: u32,
1111 /// The number of hops walked up to this node.
1112 path_length_to_node: u8,
1115 impl cmp::Ord for RouteGraphNode {
1116 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
1117 other.score.cmp(&self.score).then_with(|| other.node_id.cmp(&self.node_id))
1121 impl cmp::PartialOrd for RouteGraphNode {
1122 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
1123 Some(self.cmp(other))
1127 // While RouteGraphNode can be laid out with fewer bytes, performance appears to be improved
1128 // substantially when it is laid out at exactly 64 bytes.
1129 const _GRAPH_NODE_SMALL: usize = 64 - core::mem::size_of::<RouteGraphNode>();
1130 const _GRAPH_NODE_FIXED_SIZE: usize = core::mem::size_of::<RouteGraphNode>() - 64;
1132 /// A [`CandidateRouteHop::FirstHop`] entry.
1133 #[derive(Clone, Debug)]
1134 pub struct FirstHopCandidate<'a> {
1135 /// Channel details of the first hop
1137 /// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1138 /// has been funded and is able to pay), and accessor methods may panic otherwise.
1140 /// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1142 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1143 pub details: &'a ChannelDetails,
1144 /// The node id of the payer, which is also the source side of this candidate route hop.
1146 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1147 pub payer_node_id: &'a NodeId,
1148 /// A unique ID which describes the payer.
1150 /// It will not conflict with any [`super::gossip::NodeInfo::node_counter`]s, but may be equal
1151 /// to one if the payer is a public node.
1152 pub(crate) payer_node_counter: u32,
1153 /// A unique ID which describes the first hop counterparty.
1155 /// It will not conflict with any [`super::gossip::NodeInfo::node_counter`]s, but may be equal
1156 /// to one if the counterparty is a public node.
1157 pub(crate) target_node_counter: u32,
1160 /// A [`CandidateRouteHop::PublicHop`] entry.
1161 #[derive(Clone, Debug)]
1162 pub struct PublicHopCandidate<'a> {
1163 /// Information about the channel, including potentially its capacity and
1164 /// direction-specific information.
1166 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1167 pub info: DirectedChannelInfo<'a>,
1168 /// The short channel ID of the channel, i.e. the identifier by which we refer to this
1170 pub short_channel_id: u64,
1173 /// A [`CandidateRouteHop::PrivateHop`] entry.
1174 #[derive(Clone, Debug)]
1175 pub struct PrivateHopCandidate<'a> {
1176 /// Information about the private hop communicated via BOLT 11.
1178 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1179 pub hint: &'a RouteHintHop,
1180 /// Node id of the next hop in BOLT 11 route hint.
1182 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1183 pub target_node_id: &'a NodeId,
1184 /// A unique ID which describes the source node of the hop (further from the payment target).
1186 /// It will not conflict with any [`super::gossip::NodeInfo::node_counter`]s, but may be equal
1187 /// to one if the node is a public node.
1188 pub(crate) source_node_counter: u32,
1189 /// A unique ID which describes the destination node of the hop (towards the payment target).
1191 /// It will not conflict with any [`super::gossip::NodeInfo::node_counter`]s, but may be equal
1192 /// to one if the node is a public node.
1193 pub(crate) target_node_counter: u32,
1196 /// A [`CandidateRouteHop::Blinded`] entry.
1197 #[derive(Clone, Debug)]
1198 pub struct BlindedPathCandidate<'a> {
1199 /// Information about the blinded path including the fee, HTLC amount limits, and
1200 /// cryptographic material required to build an HTLC through the given path.
1202 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1203 pub hint: &'a (BlindedPayInfo, BlindedPath),
1204 /// Index of the hint in the original list of blinded hints.
1206 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1207 /// a short channel ID for this hop.
1209 /// A unique ID which describes the introduction point of the blinded path.
1211 /// It will not conflict with any [`super::gossip::NodeInfo::node_counter`]s, but will generally
1212 /// be equal to one from the public network graph (assuming the introduction point is a public
1214 source_node_counter: u32,
1217 /// A [`CandidateRouteHop::OneHopBlinded`] entry.
1218 #[derive(Clone, Debug)]
1219 pub struct OneHopBlindedPathCandidate<'a> {
1220 /// Information about the blinded path including the fee, HTLC amount limits, and
1221 /// cryptographic material required to build an HTLC terminating with the given path.
1223 /// Note that the [`BlindedPayInfo`] is ignored here.
1225 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1226 pub hint: &'a (BlindedPayInfo, BlindedPath),
1227 /// Index of the hint in the original list of blinded hints.
1229 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1230 /// a short channel ID for this hop.
1232 /// A unique ID which describes the introduction point of the blinded path.
1234 /// It will not conflict with any [`super::gossip::NodeInfo::node_counter`]s, but will generally
1235 /// be equal to one from the public network graph (assuming the introduction point is a public
1237 source_node_counter: u32,
1240 /// A wrapper around the various hop representations.
1242 /// Can be used to examine the properties of a hop,
1243 /// potentially to decide whether to include it in a route.
1244 #[derive(Clone, Debug)]
1245 pub enum CandidateRouteHop<'a> {
1246 /// A hop from the payer, where the outbound liquidity is known.
1247 FirstHop(FirstHopCandidate<'a>),
1248 /// A hop found in the [`ReadOnlyNetworkGraph`].
1249 PublicHop(PublicHopCandidate<'a>),
1250 /// A private hop communicated by the payee, generally via a BOLT 11 invoice.
1252 /// Because BOLT 11 route hints can take multiple hops to get to the destination, this may not
1253 /// terminate at the payee.
1254 PrivateHop(PrivateHopCandidate<'a>),
1255 /// A blinded path which starts with an introduction point and ultimately terminates with the
1258 /// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1259 /// `None` in this state.
1261 /// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1262 /// path, the full path is treated as a single [`CandidateRouteHop`].
1263 Blinded(BlindedPathCandidate<'a>),
1264 /// Similar to [`Self::Blinded`], but the path here only has one hop.
1266 /// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1267 /// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1268 /// payee's identity - it's the introduction point!
1270 /// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1271 /// to the hops *between* the introduction node and the destination.
1273 /// This primarily exists to track that we need to included a blinded path at the end of our
1274 /// [`Route`], even though it doesn't actually add an additional hop in the payment.
1275 OneHopBlinded(OneHopBlindedPathCandidate<'a>),
1278 impl<'a> CandidateRouteHop<'a> {
1279 /// Returns the short channel ID for this hop, if one is known.
1281 /// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1282 /// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1284 /// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1285 /// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1286 /// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1287 /// (which is always true for channels which are funded and ready for use).
1289 /// In other words, this should always return `Some` as long as the candidate hop is not a
1290 /// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1292 /// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1293 /// define a global namespace.
1295 fn short_channel_id(&self) -> Option<u64> {
1297 CandidateRouteHop::FirstHop(hop) => hop.details.get_outbound_payment_scid(),
1298 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1299 CandidateRouteHop::PrivateHop(hop) => Some(hop.hint.short_channel_id),
1300 CandidateRouteHop::Blinded(_) => None,
1301 CandidateRouteHop::OneHopBlinded(_) => None,
1305 /// Returns the globally unique short channel ID for this hop, if one is known.
1307 /// This only returns `Some` if the channel is public (either our own, or one we've learned
1308 /// from the public network graph), and thus the short channel ID we have for this channel is
1309 /// globally unique and identifies this channel in a global namespace.
1311 pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1313 CandidateRouteHop::FirstHop(hop) => if hop.details.is_public { hop.details.short_channel_id } else { None },
1314 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1315 CandidateRouteHop::PrivateHop(_) => None,
1316 CandidateRouteHop::Blinded(_) => None,
1317 CandidateRouteHop::OneHopBlinded(_) => None,
1321 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1322 fn features(&self) -> ChannelFeatures {
1324 CandidateRouteHop::FirstHop(hop) => hop.details.counterparty.features.to_context(),
1325 CandidateRouteHop::PublicHop(hop) => hop.info.channel().features.clone(),
1326 CandidateRouteHop::PrivateHop(_) => ChannelFeatures::empty(),
1327 CandidateRouteHop::Blinded(_) => ChannelFeatures::empty(),
1328 CandidateRouteHop::OneHopBlinded(_) => ChannelFeatures::empty(),
1332 /// Returns the required difference in HTLC CLTV expiry between the [`Self::source`] and the
1333 /// next-hop for an HTLC taking this hop.
1335 /// This is the time that the node(s) in this hop have to claim the HTLC on-chain if the
1336 /// next-hop goes on chain with a payment preimage.
1338 pub fn cltv_expiry_delta(&self) -> u32 {
1340 CandidateRouteHop::FirstHop(_) => 0,
1341 CandidateRouteHop::PublicHop(hop) => hop.info.direction().cltv_expiry_delta as u32,
1342 CandidateRouteHop::PrivateHop(hop) => hop.hint.cltv_expiry_delta as u32,
1343 CandidateRouteHop::Blinded(hop) => hop.hint.0.cltv_expiry_delta as u32,
1344 CandidateRouteHop::OneHopBlinded(_) => 0,
1348 /// Returns the minimum amount that can be sent over this hop, in millisatoshis.
1350 pub fn htlc_minimum_msat(&self) -> u64 {
1352 CandidateRouteHop::FirstHop(hop) => hop.details.next_outbound_htlc_minimum_msat,
1353 CandidateRouteHop::PublicHop(hop) => hop.info.direction().htlc_minimum_msat,
1354 CandidateRouteHop::PrivateHop(hop) => hop.hint.htlc_minimum_msat.unwrap_or(0),
1355 CandidateRouteHop::Blinded(hop) => hop.hint.0.htlc_minimum_msat,
1356 CandidateRouteHop::OneHopBlinded { .. } => 0,
1361 fn src_node_counter(&self) -> u32 {
1363 CandidateRouteHop::FirstHop(hop) => hop.payer_node_counter,
1364 CandidateRouteHop::PublicHop(hop) => hop.info.source_counter(),
1365 CandidateRouteHop::PrivateHop(hop) => hop.source_node_counter,
1366 CandidateRouteHop::Blinded(hop) => hop.source_node_counter,
1367 CandidateRouteHop::OneHopBlinded(hop) => hop.source_node_counter,
1372 fn target_node_counter(&self) -> Option<u32> {
1374 CandidateRouteHop::FirstHop(hop) => Some(hop.target_node_counter),
1375 CandidateRouteHop::PublicHop(hop) => Some(hop.info.target_counter()),
1376 CandidateRouteHop::PrivateHop(hop) => Some(hop.target_node_counter),
1377 CandidateRouteHop::Blinded(_) => None,
1378 CandidateRouteHop::OneHopBlinded(_) => None,
1382 /// Returns the fees that must be paid to route an HTLC over this channel.
1384 pub fn fees(&self) -> RoutingFees {
1386 CandidateRouteHop::FirstHop(_) => RoutingFees {
1387 base_msat: 0, proportional_millionths: 0,
1389 CandidateRouteHop::PublicHop(hop) => hop.info.direction().fees,
1390 CandidateRouteHop::PrivateHop(hop) => hop.hint.fees,
1391 CandidateRouteHop::Blinded(hop) => {
1393 base_msat: hop.hint.0.fee_base_msat,
1394 proportional_millionths: hop.hint.0.fee_proportional_millionths
1397 CandidateRouteHop::OneHopBlinded(_) =>
1398 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1402 /// Fetch the effective capacity of this hop.
1404 /// Note that this may be somewhat expensive, so calls to this should be limited and results
1406 fn effective_capacity(&self) -> EffectiveCapacity {
1408 CandidateRouteHop::FirstHop(hop) => EffectiveCapacity::ExactLiquidity {
1409 liquidity_msat: hop.details.next_outbound_htlc_limit_msat,
1411 CandidateRouteHop::PublicHop(hop) => hop.info.effective_capacity(),
1412 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. }) =>
1413 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1414 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. }) =>
1415 EffectiveCapacity::Infinite,
1416 CandidateRouteHop::Blinded(hop) =>
1417 EffectiveCapacity::HintMaxHTLC { amount_msat: hop.hint.0.htlc_maximum_msat },
1418 CandidateRouteHop::OneHopBlinded(_) => EffectiveCapacity::Infinite,
1422 /// Returns an ID describing the given hop.
1424 /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1426 fn id(&self) -> CandidateHopId {
1428 CandidateRouteHop::Blinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1429 CandidateRouteHop::OneHopBlinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1430 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1433 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1435 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1441 fn blinded_hint_idx(&self) -> Option<usize> {
1443 Self::Blinded(BlindedPathCandidate { hint_idx, .. }) |
1444 Self::OneHopBlinded(OneHopBlindedPathCandidate { hint_idx, .. }) => {
1450 /// Returns the source node id of current hop.
1452 /// Source node id refers to the node forwarding the HTLC through this hop.
1454 /// For [`Self::FirstHop`] we return payer's node id.
1456 pub fn source(&self) -> NodeId {
1458 CandidateRouteHop::FirstHop(hop) => *hop.payer_node_id,
1459 CandidateRouteHop::PublicHop(hop) => *hop.info.source(),
1460 CandidateRouteHop::PrivateHop(hop) => hop.hint.src_node_id.into(),
1461 CandidateRouteHop::Blinded(hop) => hop.hint.1.introduction_node_id.into(),
1462 CandidateRouteHop::OneHopBlinded(hop) => hop.hint.1.introduction_node_id.into(),
1465 /// Returns the target node id of this hop, if known.
1467 /// Target node id refers to the node receiving the HTLC after this hop.
1469 /// For [`Self::Blinded`] we return `None` because the ultimate destination after the blinded
1470 /// path is unknown.
1472 /// For [`Self::OneHopBlinded`] we return `None` because the target is the same as the source,
1473 /// and such a return value would be somewhat nonsensical.
1475 pub fn target(&self) -> Option<NodeId> {
1477 CandidateRouteHop::FirstHop(hop) => Some(hop.details.counterparty.node_id.into()),
1478 CandidateRouteHop::PublicHop(hop) => Some(*hop.info.target()),
1479 CandidateRouteHop::PrivateHop(hop) => Some(*hop.target_node_id),
1480 CandidateRouteHop::Blinded(_) => None,
1481 CandidateRouteHop::OneHopBlinded(_) => None,
1486 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1488 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1490 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1491 /// isn't guaranteed to be unique at all.
1493 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1494 /// difficult-to-use API.
1495 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1496 enum CandidateHopId {
1497 /// Contains (scid, src_node_id < target_node_id)
1499 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1503 /// To avoid doing [`PublicKey`] -> [`PathBuildingHop`] hashtable lookups, we assign each
1504 /// [`PublicKey`]/node a `usize` index and simply keep a `Vec` of values.
1506 /// While this is easy for gossip-originating nodes (the [`DirectedChannelInfo`] exposes "counters"
1507 /// for us for this purpose) we have to have our own indexes for nodes originating from invoice
1508 /// hints, local channels, or blinded path fake nodes.
1510 /// This wrapper handles all this for us, allowing look-up of counters from the various contexts.
1512 /// It is first built by passing all [`NodeId`]s that we'll ever care about either though
1513 /// [`NodeCountersBuilder::node_counter_from_pubkey`] or
1514 /// [`NodeCountersBuilder::node_counter_from_id`], then calling [`NodeCountersBuilder::build`] and
1515 /// using the resulting [`NodeCounters`] to look up any counters.
1517 /// [`NodeCounters::node_counter_from_pubkey`], specifically, will return `Some` iff
1518 /// [`NodeCountersBuilder::node_counter_from_pubkey`] was called on the same key (not
1519 /// [`NodeCountersBuilder::node_counter_from_id`]). It will also returned a cached copy of the
1520 /// [`PublicKey`] -> [`NodeId`] conversion.
1521 struct NodeCounters<'a> {
1522 network_graph: &'a ReadOnlyNetworkGraph<'a>,
1523 private_node_id_to_node_counter: HashMap<NodeId, u32>,
1524 private_hop_key_cache: HashMap<PublicKey, (NodeId, u32)>,
1527 struct NodeCountersBuilder<'a>(NodeCounters<'a>);
1529 impl<'a> NodeCountersBuilder<'a> {
1530 fn new(network_graph: &'a ReadOnlyNetworkGraph) -> Self {
1533 private_node_id_to_node_counter: new_hash_map(),
1534 private_hop_key_cache: new_hash_map(),
1538 fn node_counter_from_pubkey(&mut self, pubkey: PublicKey) -> u32 {
1539 let id = NodeId::from_pubkey(&pubkey);
1540 let counter = self.node_counter_from_id(id);
1541 self.0.private_hop_key_cache.insert(pubkey, (id, counter));
1545 fn node_counter_from_id(&mut self, node_id: NodeId) -> u32 {
1546 // For any node_id, we first have to check if its in the existing network graph, and then
1547 // ensure that we always look up in our internal map first.
1548 self.0.network_graph.nodes().get(&node_id)
1549 .map(|node| node.node_counter)
1550 .unwrap_or_else(|| {
1551 let next_node_counter = self.0.network_graph.max_node_counter() + 1 +
1552 self.0.private_node_id_to_node_counter.len() as u32;
1553 *self.0.private_node_id_to_node_counter.entry(node_id).or_insert(next_node_counter)
1557 fn build(self) -> NodeCounters<'a> { self.0 }
1560 impl<'a> NodeCounters<'a> {
1561 fn max_counter(&self) -> u32 {
1562 self.network_graph.max_node_counter() +
1563 self.private_node_id_to_node_counter.len() as u32
1566 fn node_counter_from_pubkey(&self, pubkey: &PublicKey) -> Option<&(NodeId, u32)> {
1567 self.private_hop_key_cache.get(pubkey)
1572 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1573 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1575 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1576 EffectiveCapacity::Infinite => u64::max_value(),
1577 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1578 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1579 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1580 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1581 // expected to have been generated from up-to-date capacity information.
1582 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1583 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1584 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1588 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1589 -> bool where I1::Item: PartialEq<I2::Item> {
1591 let a = iter_a.next();
1592 let b = iter_b.next();
1593 if a.is_none() && b.is_none() { return true; }
1594 if a.is_none() || b.is_none() { return false; }
1595 if a.unwrap().ne(&b.unwrap()) { return false; }
1599 /// It's useful to keep track of the hops associated with the fees required to use them,
1600 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1601 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1602 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1605 struct PathBuildingHop<'a> {
1606 candidate: CandidateRouteHop<'a>,
1607 target_node_counter: Option<u32>,
1608 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1609 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1610 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1611 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1612 /// avoid processing them again.
1613 was_processed: bool,
1614 /// When processing a node as the next best-score candidate, we want to quickly check if it is
1615 /// a direct counterparty of ours, using our local channel information immediately if we can.
1617 /// In order to do so efficiently, we cache whether a node is a direct counterparty here at the
1618 /// start of a route-finding pass. Unlike all other fields in this struct, this field is never
1619 /// updated after being initialized - it is set at the start of a route-finding pass and only
1620 /// read thereafter.
1621 is_first_hop_target: bool,
1622 /// Used to compare channels when choosing the for routing.
1623 /// Includes paying for the use of a hop and the following hops, as well as
1624 /// an estimated cost of reaching this hop.
1625 /// Might get stale when fees are recomputed. Primarily for internal use.
1626 total_fee_msat: u64,
1627 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1628 /// walk and may be invalid thereafter.
1629 path_htlc_minimum_msat: u64,
1630 /// All penalties incurred from this channel on the way to the destination, as calculated using
1631 /// channel scoring.
1632 path_penalty_msat: u64,
1636 /// All the fees paid *after* this channel on the way to the destination
1637 next_hops_fee_msat: u64,
1638 /// Fee paid for the use of the current channel (see candidate.fees()).
1639 /// The value will be actually deducted from the counterparty balance on the previous link.
1640 hop_use_fee_msat: u64,
1642 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1643 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1644 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1645 // value_contribution_msat, which requires tracking it here. See comments below where it is
1646 // used for more info.
1647 value_contribution_msat: u64,
1650 const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::<Option<PathBuildingHop>>();
1651 const _NODE_MAP_SIZE_EXACTLY_TWO_CACHE_LINES: usize = core::mem::size_of::<Option<PathBuildingHop>>() - 128;
1653 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1654 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1655 let mut debug_struct = f.debug_struct("PathBuildingHop");
1657 .field("source_node_id", &self.candidate.source())
1658 .field("target_node_id", &self.candidate.target())
1659 .field("short_channel_id", &self.candidate.short_channel_id())
1660 .field("total_fee_msat", &self.total_fee_msat)
1661 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1662 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1663 .field("total_fee_msat - (next_hops_fee_msat + hop_use_fee_msat)", &(&self.total_fee_msat.saturating_sub(self.next_hops_fee_msat).saturating_sub(self.hop_use_fee_msat)))
1664 .field("path_penalty_msat", &self.path_penalty_msat)
1665 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1666 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1667 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1668 let debug_struct = debug_struct
1669 .field("value_contribution_msat", &self.value_contribution_msat);
1670 debug_struct.finish()
1674 // Instantiated with a list of hops with correct data in them collected during path finding,
1675 // an instance of this struct should be further modified only via given methods.
1677 struct PaymentPath<'a> {
1678 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1681 impl<'a> PaymentPath<'a> {
1682 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1683 fn get_value_msat(&self) -> u64 {
1684 self.hops.last().unwrap().0.fee_msat
1687 fn get_path_penalty_msat(&self) -> u64 {
1688 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1691 fn get_total_fee_paid_msat(&self) -> u64 {
1692 if self.hops.len() < 1 {
1696 // Can't use next_hops_fee_msat because it gets outdated.
1697 for (i, (hop, _)) in self.hops.iter().enumerate() {
1698 if i != self.hops.len() - 1 {
1699 result += hop.fee_msat;
1705 fn get_cost_msat(&self) -> u64 {
1706 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1709 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1710 // to change fees may result in an inconsistency.
1712 // Sometimes we call this function right after constructing a path which is inconsistent in
1713 // that it the value being transferred has decreased while we were doing path finding, leading
1714 // to the fees being paid not lining up with the actual limits.
1716 // Note that this function is not aware of the available_liquidity limit, and thus does not
1717 // support increasing the value being transferred beyond what was selected during the initial
1720 // Returns the amount that this path contributes to the total payment value, which may be greater
1721 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1722 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1723 let mut extra_contribution_msat = 0;
1724 let mut total_fee_paid_msat = 0 as u64;
1725 for i in (0..self.hops.len()).rev() {
1726 let last_hop = i == self.hops.len() - 1;
1728 // For non-last-hop, this value will represent the fees paid on the current hop. It
1729 // will consist of the fees for the use of the next hop, and extra fees to match
1730 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1731 let mut cur_hop_fees_msat = 0;
1733 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1736 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1737 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1738 cur_hop.path_penalty_msat += extra_contribution_msat;
1739 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1740 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1741 // set it too high just to maliciously take more fees by exploiting this
1742 // match htlc_minimum_msat logic.
1743 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1744 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1745 // Note that there is a risk that *previous hops* (those closer to us, as we go
1746 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1748 // This might make us end up with a broken route, although this should be super-rare
1749 // in practice, both because of how healthy channels look like, and how we pick
1750 // channels in add_entry.
1751 // Also, this can't be exploited more heavily than *announce a free path and fail
1753 cur_hop_transferred_amount_msat += extra_fees_msat;
1755 // We remember and return the extra fees on the final hop to allow accounting for
1756 // them in the path's value contribution.
1758 extra_contribution_msat = extra_fees_msat;
1760 total_fee_paid_msat += extra_fees_msat;
1761 cur_hop_fees_msat += extra_fees_msat;
1766 // Final hop is a special case: it usually has just value_msat (by design), but also
1767 // it still could overpay for the htlc_minimum_msat.
1768 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1770 // Propagate updated fees for the use of the channels to one hop back, where they
1771 // will be actually paid (fee_msat). The last hop is handled above separately.
1772 cur_hop.fee_msat = cur_hop_fees_msat;
1775 // Fee for the use of the current hop which will be deducted on the previous hop.
1776 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1777 // this channel is free for us.
1779 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1780 cur_hop.hop_use_fee_msat = new_fee;
1781 total_fee_paid_msat += new_fee;
1783 // It should not be possible because this function is called only to reduce the
1784 // value. In that case, compute_fee was already called with the same fees for
1785 // larger amount and there was no overflow.
1790 value_msat + extra_contribution_msat
1795 /// Calculate the fees required to route the given amount over a channel with the given fees.
1796 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1797 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1798 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1802 /// Calculate the fees required to route the given amount over a channel with the given fees,
1803 /// saturating to [`u64::max_value`].
1804 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1805 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1806 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1807 .saturating_add(channel_fees.base_msat as u64)
1810 /// The default `features` we assume for a node in a route, when no `features` are known about that
1813 /// Default features are:
1814 /// * variable_length_onion_optional
1815 fn default_node_features() -> NodeFeatures {
1816 let mut features = NodeFeatures::empty();
1817 features.set_variable_length_onion_optional();
1821 struct LoggedPayeePubkey(Option<PublicKey>);
1822 impl fmt::Display for LoggedPayeePubkey {
1823 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1826 "payee node id ".fmt(f)?;
1830 "blinded payee".fmt(f)
1836 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1837 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1838 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1840 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1841 "blinded route hint with introduction node id ".fmt(f)?;
1842 hint.1.introduction_node_id.fmt(f)?;
1843 " and blinding point ".fmt(f)?;
1844 hint.1.blinding_point.fmt(f)
1846 CandidateRouteHop::FirstHop(_) => {
1847 "first hop with SCID ".fmt(f)?;
1848 self.0.short_channel_id().unwrap().fmt(f)
1850 CandidateRouteHop::PrivateHop(_) => {
1851 "route hint with SCID ".fmt(f)?;
1852 self.0.short_channel_id().unwrap().fmt(f)
1856 self.0.short_channel_id().unwrap().fmt(f)
1863 fn sort_first_hop_channels(
1864 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1865 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1867 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1868 // most like to use.
1870 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1871 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1874 // Second, because simply always sorting in descending order would always use our largest
1875 // available outbound capacity, needlessly fragmenting our available channel capacities,
1876 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1877 // which have enough, but not too much, capacity for the payment.
1879 // Available outbound balances factor in liquidity already reserved for previously found paths.
1880 channels.sort_unstable_by(|chan_a, chan_b| {
1881 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1882 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1883 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1884 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1885 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1886 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1887 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1888 // Sort in descending order
1889 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1891 // Sort in ascending order
1892 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1897 /// Finds a route from us (payer) to the given target node (payee).
1899 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1900 /// in the given [`RouteParameters::payment_params`].
1901 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1903 /// Private routing paths between a public node and the target may be included in the `payee` field
1904 /// of [`RouteParameters::payment_params`].
1906 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1907 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1908 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1910 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1911 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1912 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1916 /// Panics if first_hops contains channels without `short_channel_id`s;
1917 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1919 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1920 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1921 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1922 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1923 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1924 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1925 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1926 ) -> Result<Route, LightningError>
1927 where L::Target: Logger, GL::Target: Logger {
1928 let graph_lock = network_graph.read_only();
1929 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1930 scorer, score_params, random_seed_bytes)?;
1931 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1935 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1936 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1937 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1938 _random_seed_bytes: &[u8; 32]
1939 ) -> Result<Route, LightningError>
1940 where L::Target: Logger {
1942 let payment_params = &route_params.payment_params;
1943 let final_value_msat = route_params.final_value_msat;
1944 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1945 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1946 // so use a dummy id for this in the blinded case.
1947 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1948 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1949 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1950 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1951 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1953 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1954 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1956 if our_node_id == maybe_dummy_payee_node_id {
1957 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1960 if final_value_msat > MAX_VALUE_MSAT {
1961 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1964 if final_value_msat == 0 {
1965 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1968 match &payment_params.payee {
1969 Payee::Clear { route_hints, node_id, .. } => {
1970 for route in route_hints.iter() {
1971 for hop in &route.0 {
1972 if hop.src_node_id == *node_id {
1973 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1978 Payee::Blinded { route_hints, .. } => {
1979 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1980 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});
1982 for (_, blinded_path) in route_hints.iter() {
1983 if blinded_path.blinded_hops.len() == 0 {
1984 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1985 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1986 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1987 } else if blinded_path.blinded_hops.len() == 1 &&
1988 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1989 && p.introduction_node_id != blinded_path.introduction_node_id)
1991 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1996 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1997 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1998 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});
2001 // The general routing idea is the following:
2002 // 1. Fill first/last hops communicated by the caller.
2003 // 2. Attempt to construct a path from payer to payee for transferring
2004 // any ~sufficient (described later) value.
2005 // If succeed, remember which channels were used and how much liquidity they have available,
2006 // so that future paths don't rely on the same liquidity.
2007 // 3. Proceed to the next step if:
2008 // - we hit the recommended target value;
2009 // - OR if we could not construct a new path. Any next attempt will fail too.
2010 // Otherwise, repeat step 2.
2011 // 4. See if we managed to collect paths which aggregately are able to transfer target value
2012 // (not recommended value).
2013 // 5. If yes, proceed. If not, fail routing.
2014 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
2015 // transferred up to the transfer target value.
2016 // 7. Reduce the value of the last path until we are sending only the target value.
2017 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
2018 // them so that we're not sending two HTLCs along the same path.
2020 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
2021 // distance from the payee
2023 // We are not a faithful Dijkstra's implementation because we can change values which impact
2024 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
2025 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
2026 // the value we are currently attempting to send over a path, we simply reduce the value being
2027 // sent along the path for any hops after that channel. This may imply that later fees (which
2028 // we've already tabulated) are lower because a smaller value is passing through the channels
2029 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
2030 // channels which were selected earlier (and which may still be used for other paths without a
2031 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
2034 // One potentially problematic case for this algorithm would be if there are many
2035 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
2036 // graph walking), we may never find a path which is not liquidity-limited and has lower
2037 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
2038 // Because we only consider paths with at least 5% of the total value being sent, the damage
2039 // from such a case should be limited, however this could be further reduced in the future by
2040 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
2041 // limits for the purposes of fee calculation.
2043 // Alternatively, we could store more detailed path information in the heap (targets, below)
2044 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
2045 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
2046 // and practically (as we would need to store dynamically-allocated path information in heap
2047 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
2048 // results of such an algorithm would likely be biased towards lower-value paths.
2050 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
2051 // outside of our current search value, running a path search more times to gather candidate
2052 // paths at different values. While this may be acceptable, further path searches may increase
2053 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
2054 // graph for candidate paths, calculating the maximum value which can realistically be sent at
2055 // the same time, remaining generic across different payment values.
2057 let network_channels = network_graph.channels();
2058 let network_nodes = network_graph.nodes();
2060 if payment_params.max_path_count == 0 {
2061 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
2064 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
2065 // it. If the payee supports it they're supposed to include it in the invoice, so that should
2067 let allow_mpp = if payment_params.max_path_count == 1 {
2069 } else if payment_params.payee.supports_basic_mpp() {
2071 } else if let Some(payee) = payee_node_id_opt {
2072 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
2073 |info| info.features.supports_basic_mpp()))
2076 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
2078 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph with a fee limit of {} msat",
2079 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
2080 if allow_mpp { "with" } else { "without" },
2081 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " },
2082 max_total_routing_fee_msat);
2084 let mut node_counters = NodeCountersBuilder::new(&network_graph);
2086 let payer_node_counter = node_counters.node_counter_from_pubkey(*our_node_pubkey);
2087 let payee_node_counter = node_counters.node_counter_from_pubkey(maybe_dummy_payee_pk);
2089 for route in payment_params.payee.unblinded_route_hints().iter() {
2090 for hop in route.0.iter() {
2091 node_counters.node_counter_from_pubkey(hop.src_node_id);
2096 // Prepare the data we'll use for payee-to-payer search by
2097 // inserting first hops suggested by the caller as targets.
2098 // Our search will then attempt to reach them while traversing from the payee node.
2099 let mut first_hop_targets: HashMap<_, (Vec<&ChannelDetails>, u32)> =
2100 hash_map_with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
2101 if let Some(hops) = first_hops {
2103 if chan.get_outbound_payment_scid().is_none() {
2104 panic!("first_hops should be filled in with usable channels, not pending ones");
2106 if chan.counterparty.node_id == *our_node_pubkey {
2107 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
2109 let counterparty_node_id = NodeId::from_pubkey(&chan.counterparty.node_id);
2111 .entry(counterparty_node_id)
2112 .or_insert_with(|| {
2113 let node_counter = node_counters.node_counter_from_id(counterparty_node_id);
2114 (Vec::new(), node_counter)
2118 if first_hop_targets.is_empty() {
2119 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
2123 let node_counters = node_counters.build();
2125 // The main heap containing all candidate next-hops sorted by their score (max(fee,
2126 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
2127 // adding duplicate entries when we find a better path to a given node.
2128 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
2130 // Map from node_id to information about the best current path to that node, including feerate
2132 let dist_len = node_counters.max_counter() + 1;
2133 let mut dist: Vec<Option<PathBuildingHop>> = vec![None; dist_len as usize];
2135 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
2136 // indicating that we may wish to try again with a higher value, potentially paying to meet an
2137 // htlc_minimum with extra fees while still finding a cheaper path.
2138 let mut hit_minimum_limit;
2140 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
2141 // We start with a path_value of the exact amount we want, and if that generates a route we may
2142 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
2143 // amount we want in total across paths, selecting the best subset at the end.
2144 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
2145 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
2146 let mut path_value_msat = final_value_msat;
2148 // Routing Fragmentation Mitigation heuristic:
2150 // Routing fragmentation across many payment paths increases the overall routing
2151 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
2152 // Taking too many smaller paths also increases the chance of payment failure.
2153 // Thus to avoid this effect, we require from our collected links to provide
2154 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
2155 // This requirement is currently set to be 1/max_path_count of the payment
2156 // value to ensure we only ever return routes that do not violate this limit.
2157 let minimal_value_contribution_msat: u64 = if allow_mpp {
2158 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
2163 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
2164 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
2165 // drop the requirement by setting this to 0.
2166 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
2168 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
2169 // determine if the channel can be used by additional MPP paths or to inform path finding
2170 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
2171 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
2173 let mut used_liquidities: HashMap<CandidateHopId, u64> =
2174 hash_map_with_capacity(network_nodes.len());
2176 // Keeping track of how much value we already collected across other paths. Helps to decide
2177 // when we want to stop looking for new paths.
2178 let mut already_collected_value_msat = 0;
2180 for (_, (channels, _)) in first_hop_targets.iter_mut() {
2181 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
2185 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
2186 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
2188 // Remember how many candidates we ignored to allow for some logging afterwards.
2189 let mut num_ignored_value_contribution: u32 = 0;
2190 let mut num_ignored_path_length_limit: u32 = 0;
2191 let mut num_ignored_cltv_delta_limit: u32 = 0;
2192 let mut num_ignored_previously_failed: u32 = 0;
2193 let mut num_ignored_total_fee_limit: u32 = 0;
2194 let mut num_ignored_avoid_overpayment: u32 = 0;
2195 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
2197 macro_rules! add_entry {
2198 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
2199 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
2200 // since that value has to be transferred over this channel.
2201 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
2202 ( $candidate: expr, $next_hops_fee_msat: expr,
2203 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
2204 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
2205 // We "return" whether we updated the path at the end, and how much we can route via
2206 // this channel, via this:
2207 let mut hop_contribution_amt_msat = None;
2208 // Channels to self should not be used. This is more of belt-and-suspenders, because in
2209 // practice these cases should be caught earlier:
2210 // - for regular channels at channel announcement (TODO)
2211 // - for first and last hops early in get_route
2212 let src_node_id = $candidate.source();
2213 if Some(src_node_id) != $candidate.target() {
2214 let scid_opt = $candidate.short_channel_id();
2215 let effective_capacity = $candidate.effective_capacity();
2216 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
2218 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
2219 // It may be misleading because we might later choose to reduce the value transferred
2220 // over these channels, and the channel which was insufficient might become sufficient.
2221 // Worst case: we drop a good channel here because it can't cover the high following
2222 // fees caused by one expensive channel, but then this channel could have been used
2223 // if the amount being transferred over this path is lower.
2224 // We do this for now, but this is a subject for removal.
2225 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
2226 let used_liquidity_msat = used_liquidities
2227 .get(&$candidate.id())
2228 .map_or(0, |used_liquidity_msat| {
2229 available_value_contribution_msat = available_value_contribution_msat
2230 .saturating_sub(*used_liquidity_msat);
2231 *used_liquidity_msat
2234 // Verify the liquidity offered by this channel complies to the minimal contribution.
2235 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
2236 // Do not consider candidate hops that would exceed the maximum path length.
2237 let path_length_to_node = $next_hops_path_length + 1;
2238 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
2240 // Do not consider candidates that exceed the maximum total cltv expiry limit.
2241 // In order to already account for some of the privacy enhancing random CLTV
2242 // expiry delta offset we add on top later, we subtract a rough estimate
2243 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
2244 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
2245 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
2246 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
2247 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
2248 .saturating_add($candidate.cltv_expiry_delta());
2249 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
2251 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
2252 // Includes paying fees for the use of the following channels.
2253 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
2254 Some(result) => result,
2255 // Can't overflow due to how the values were computed right above.
2256 None => unreachable!(),
2258 let htlc_minimum_msat = $candidate.htlc_minimum_msat();
2259 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2260 let over_path_minimum_msat = amount_to_transfer_over_msat >= htlc_minimum_msat &&
2261 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
2263 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2264 let may_overpay_to_meet_path_minimum_msat =
2265 ((amount_to_transfer_over_msat < htlc_minimum_msat &&
2266 recommended_value_msat >= htlc_minimum_msat) ||
2267 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
2268 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
2270 let payment_failed_on_this_channel = match scid_opt {
2271 Some(scid) => payment_params.previously_failed_channels.contains(&scid),
2272 None => match $candidate.blinded_hint_idx() {
2274 payment_params.previously_failed_blinded_path_idxs.contains(&(idx as u64))
2280 let (should_log_candidate, first_hop_details) = match $candidate {
2281 CandidateRouteHop::FirstHop(hop) => (true, Some(hop.details)),
2282 CandidateRouteHop::PrivateHop(_) => (true, None),
2283 CandidateRouteHop::Blinded(_) => (true, None),
2284 CandidateRouteHop::OneHopBlinded(_) => (true, None),
2288 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
2289 // bother considering this channel. If retrying with recommended_value_msat may
2290 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
2291 // around again with a higher amount.
2292 if !contributes_sufficient_value {
2293 if should_log_candidate {
2294 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
2296 if let Some(details) = first_hop_details {
2298 "First hop candidate next_outbound_htlc_limit_msat: {}",
2299 details.next_outbound_htlc_limit_msat,
2303 num_ignored_value_contribution += 1;
2304 } else if exceeds_max_path_length {
2305 if should_log_candidate {
2306 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
2308 num_ignored_path_length_limit += 1;
2309 } else if exceeds_cltv_delta_limit {
2310 if should_log_candidate {
2311 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
2313 if let Some(_) = first_hop_details {
2315 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
2316 hop_total_cltv_delta,
2317 max_total_cltv_expiry_delta,
2321 num_ignored_cltv_delta_limit += 1;
2322 } else if payment_failed_on_this_channel {
2323 if should_log_candidate {
2324 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
2326 num_ignored_previously_failed += 1;
2327 } else if may_overpay_to_meet_path_minimum_msat {
2328 if should_log_candidate {
2330 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit.",
2331 LoggedCandidateHop(&$candidate));
2333 if let Some(details) = first_hop_details {
2335 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2336 details.next_outbound_htlc_minimum_msat,
2340 num_ignored_avoid_overpayment += 1;
2341 hit_minimum_limit = true;
2342 } else if over_path_minimum_msat {
2343 // Note that low contribution here (limited by available_liquidity_msat)
2344 // might violate htlc_minimum_msat on the hops which are next along the
2345 // payment path (upstream to the payee). To avoid that, we recompute
2346 // path fees knowing the final path contribution after constructing it.
2347 let curr_min = cmp::max(
2348 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
2350 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
2351 .saturating_add(curr_min);
2353 let dist_entry = &mut dist[$candidate.src_node_counter() as usize];
2354 let old_entry = if let Some(hop) = dist_entry {
2357 // If there was previously no known way to access the source node
2358 // (recall it goes payee-to-payer) of short_channel_id, first add a
2359 // semi-dummy record just to compute the fees to reach the source node.
2360 // This will affect our decision on selecting short_channel_id
2361 // as a way to reach the $candidate.target() node.
2362 *dist_entry = Some(PathBuildingHop {
2363 candidate: $candidate.clone(),
2364 target_node_counter: None,
2366 next_hops_fee_msat: u64::max_value(),
2367 hop_use_fee_msat: u64::max_value(),
2368 total_fee_msat: u64::max_value(),
2369 path_htlc_minimum_msat,
2370 path_penalty_msat: u64::max_value(),
2371 was_processed: false,
2372 is_first_hop_target: false,
2373 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2374 value_contribution_msat,
2376 dist_entry.as_mut().unwrap()
2379 #[allow(unused_mut)] // We only use the mut in cfg(test)
2380 let mut should_process = !old_entry.was_processed;
2381 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2383 // In test/fuzzing builds, we do extra checks to make sure the skipping
2384 // of already-seen nodes only happens in cases we expect (see below).
2385 if !should_process { should_process = true; }
2389 let mut hop_use_fee_msat = 0;
2390 let mut total_fee_msat: u64 = $next_hops_fee_msat;
2392 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2393 // will have the same effective-fee
2394 if src_node_id != our_node_id {
2395 // Note that `u64::max_value` means we'll always fail the
2396 // `old_entry.total_fee_msat > total_fee_msat` check below
2397 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
2398 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2401 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2402 if total_fee_msat > max_total_routing_fee_msat {
2403 if should_log_candidate {
2404 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2406 if let Some(_) = first_hop_details {
2408 "First hop candidate routing fee: {}. Limit: {}",
2410 max_total_routing_fee_msat,
2414 num_ignored_total_fee_limit += 1;
2416 let channel_usage = ChannelUsage {
2417 amount_msat: amount_to_transfer_over_msat,
2418 inflight_htlc_msat: used_liquidity_msat,
2421 let channel_penalty_msat =
2422 scorer.channel_penalty_msat($candidate,
2425 let path_penalty_msat = $next_hops_path_penalty_msat
2426 .saturating_add(channel_penalty_msat);
2428 // Update the way of reaching $candidate.source()
2429 // with the given short_channel_id (from $candidate.target()),
2430 // if this way is cheaper than the already known
2431 // (considering the cost to "reach" this channel from the route destination,
2432 // the cost of using this channel,
2433 // and the cost of routing to the source node of this channel).
2434 // Also, consider that htlc_minimum_msat_difference, because we might end up
2435 // paying it. Consider the following exploit:
2436 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2437 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2438 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2439 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2441 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2442 // but it may require additional tracking - we don't want to double-count
2443 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2444 // can't use something that may decrease on future hops.
2445 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2446 .saturating_add(old_entry.path_penalty_msat);
2447 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2448 .saturating_add(path_penalty_msat);
2450 if !old_entry.was_processed && new_cost < old_cost {
2451 let new_graph_node = RouteGraphNode {
2452 node_id: src_node_id,
2453 score: cmp::max(total_fee_msat, path_htlc_minimum_msat).saturating_add(path_penalty_msat),
2454 total_cltv_delta: hop_total_cltv_delta,
2455 value_contribution_msat,
2456 path_length_to_node,
2458 targets.push(new_graph_node);
2459 old_entry.target_node_counter = $candidate.target_node_counter();
2460 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2461 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2462 old_entry.total_fee_msat = total_fee_msat;
2463 old_entry.candidate = $candidate.clone();
2464 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2465 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2466 old_entry.path_penalty_msat = path_penalty_msat;
2467 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2469 old_entry.value_contribution_msat = value_contribution_msat;
2471 hop_contribution_amt_msat = Some(value_contribution_msat);
2472 } else if old_entry.was_processed && new_cost < old_cost {
2473 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2475 // If we're skipping processing a node which was previously
2476 // processed even though we found another path to it with a
2477 // cheaper fee, check that it was because the second path we
2478 // found (which we are processing now) has a lower value
2479 // contribution due to an HTLC minimum limit.
2481 // e.g. take a graph with two paths from node 1 to node 2, one
2482 // through channel A, and one through channel B. Channel A and
2483 // B are both in the to-process heap, with their scores set by
2484 // a higher htlc_minimum than fee.
2485 // Channel A is processed first, and the channels onwards from
2486 // node 1 are added to the to-process heap. Thereafter, we pop
2487 // Channel B off of the heap, note that it has a much more
2488 // restrictive htlc_maximum_msat, and recalculate the fees for
2489 // all of node 1's channels using the new, reduced, amount.
2491 // This would be bogus - we'd be selecting a higher-fee path
2492 // with a lower htlc_maximum_msat instead of the one we'd
2493 // already decided to use.
2494 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2496 value_contribution_msat + path_penalty_msat <
2497 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2504 if should_log_candidate {
2506 "Ignoring {} due to its htlc_minimum_msat limit.",
2507 LoggedCandidateHop(&$candidate));
2509 if let Some(details) = first_hop_details {
2511 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2512 details.next_outbound_htlc_minimum_msat,
2516 num_ignored_htlc_minimum_msat_limit += 1;
2520 hop_contribution_amt_msat
2524 let default_node_features = default_node_features();
2526 // Find ways (channels with destination) to reach a given node and store them
2527 // in the corresponding data structures (routing graph etc).
2528 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2529 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2530 // This data can later be helpful to optimize routing (pay lower fees).
2531 macro_rules! add_entries_to_cheapest_to_target_node {
2532 ( $node: expr, $node_id: expr, $next_hops_value_contribution: expr,
2533 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2534 let fee_to_target_msat;
2535 let next_hops_path_htlc_minimum_msat;
2536 let next_hops_path_penalty_msat;
2537 let is_first_hop_target;
2538 let skip_node = if let Some(elem) = &mut dist[$node.node_counter as usize] {
2539 let was_processed = elem.was_processed;
2540 elem.was_processed = true;
2541 fee_to_target_msat = elem.total_fee_msat;
2542 next_hops_path_htlc_minimum_msat = elem.path_htlc_minimum_msat;
2543 next_hops_path_penalty_msat = elem.path_penalty_msat;
2544 is_first_hop_target = elem.is_first_hop_target;
2547 // Entries are added to dist in add_entry!() when there is a channel from a node.
2548 // Because there are no channels from payee, it will not have a dist entry at this point.
2549 // If we're processing any other node, it is always be the result of a channel from it.
2550 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2552 fee_to_target_msat = 0;
2553 next_hops_path_htlc_minimum_msat = 0;
2554 next_hops_path_penalty_msat = 0;
2555 is_first_hop_target = false;
2560 if is_first_hop_target {
2561 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get(&$node_id) {
2562 for details in first_channels {
2563 debug_assert_eq!(*peer_node_counter, $node.node_counter);
2564 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2565 details, payer_node_id: &our_node_id, payer_node_counter,
2566 target_node_counter: $node.node_counter,
2568 add_entry!(&candidate, fee_to_target_msat,
2569 $next_hops_value_contribution,
2570 next_hops_path_htlc_minimum_msat, next_hops_path_penalty_msat,
2571 $next_hops_cltv_delta, $next_hops_path_length);
2576 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2579 &default_node_features
2582 if !features.requires_unknown_bits() {
2583 for chan_id in $node.channels.iter() {
2584 let chan = network_channels.get(chan_id).unwrap();
2585 if !chan.features.requires_unknown_bits() {
2586 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2587 if first_hops.is_none() || *source != our_node_id {
2588 if directed_channel.direction().enabled {
2589 let candidate = CandidateRouteHop::PublicHop(PublicHopCandidate {
2590 info: directed_channel,
2591 short_channel_id: *chan_id,
2593 add_entry!(&candidate,
2595 $next_hops_value_contribution,
2596 next_hops_path_htlc_minimum_msat,
2597 next_hops_path_penalty_msat,
2598 $next_hops_cltv_delta, $next_hops_path_length);
2609 let mut payment_paths = Vec::<PaymentPath>::new();
2611 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2612 'paths_collection: loop {
2613 // For every new path, start from scratch, except for used_liquidities, which
2614 // helps to avoid reusing previously selected paths in future iterations.
2616 for e in dist.iter_mut() {
2619 for (_, (chans, peer_node_counter)) in first_hop_targets.iter() {
2620 // In order to avoid looking up whether each node is a first-hop target, we store a
2621 // dummy entry in dist for each first-hop target, allowing us to do this lookup for
2622 // free since we're already looking at the `was_processed` flag.
2624 // Note that all the fields (except `is_first_hop_target`) will be overwritten whenever
2625 // we find a path to the target, so are left as dummies here.
2626 dist[*peer_node_counter as usize] = Some(PathBuildingHop {
2627 candidate: CandidateRouteHop::FirstHop(FirstHopCandidate {
2629 payer_node_id: &our_node_id,
2630 target_node_counter: u32::max_value(),
2631 payer_node_counter: u32::max_value(),
2633 target_node_counter: None,
2635 next_hops_fee_msat: u64::max_value(),
2636 hop_use_fee_msat: u64::max_value(),
2637 total_fee_msat: u64::max_value(),
2638 path_htlc_minimum_msat: u64::max_value(),
2639 path_penalty_msat: u64::max_value(),
2640 was_processed: false,
2641 is_first_hop_target: true,
2642 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2643 value_contribution_msat: 0,
2646 hit_minimum_limit = false;
2648 // If first hop is a private channel and the only way to reach the payee, this is the only
2649 // place where it could be added.
2650 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|(first_channels, peer_node_counter)| {
2651 debug_assert_eq!(*peer_node_counter, payee_node_counter);
2652 for details in first_channels {
2653 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2654 details, payer_node_id: &our_node_id, payer_node_counter,
2655 target_node_counter: payee_node_counter,
2657 let added = add_entry!(&candidate, 0, path_value_msat,
2658 0, 0u64, 0, 0).is_some();
2659 log_trace!(logger, "{} direct route to payee via {}",
2660 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2664 // Add the payee as a target, so that the payee-to-payer
2665 // search algorithm knows what to start with.
2666 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2667 // The payee is not in our network graph, so nothing to add here.
2668 // There is still a chance of reaching them via last_hops though,
2669 // so don't yet fail the payment here.
2670 // If not, targets.pop() will not even let us enter the loop in step 2.
2673 add_entries_to_cheapest_to_target_node!(node, payee, path_value_msat, 0, 0);
2678 // If a caller provided us with last hops, add them to routing targets. Since this happens
2679 // earlier than general path finding, they will be somewhat prioritized, although currently
2680 // it matters only if the fees are exactly the same.
2681 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2682 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2683 let intro_node_counter_opt =
2684 // Only add the hops in this route to our candidate set if either
2685 // we have a direct channel to the first hop or the first hop is
2686 // in the regular network graph.
2687 network_nodes.get(&intro_node_id).map(|node| node.node_counter)
2689 first_hop_targets.get(&intro_node_id).map(|(_, node_counter)| *node_counter)
2691 if intro_node_counter_opt.is_none() || our_node_id == intro_node_id { continue }
2692 let candidate = if hint.1.blinded_hops.len() == 1 {
2693 CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate {
2696 source_node_counter: intro_node_counter_opt.unwrap(),
2699 CandidateRouteHop::Blinded(BlindedPathCandidate {
2702 source_node_counter: intro_node_counter_opt.unwrap(),
2705 let mut path_contribution_msat = path_value_msat;
2706 if let Some(hop_used_msat) = add_entry!(&candidate,
2707 0, path_contribution_msat, 0, 0_u64, 0, 0)
2709 path_contribution_msat = hop_used_msat;
2711 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2712 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2714 for details in first_channels {
2715 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2716 details, payer_node_id: &our_node_id, payer_node_counter,
2717 target_node_counter: *peer_node_counter,
2719 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2723 let path_min = candidate.htlc_minimum_msat().saturating_add(
2724 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2725 add_entry!(&first_hop_candidate, blinded_path_fee,
2726 path_contribution_msat, path_min, 0_u64, candidate.cltv_expiry_delta(),
2727 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2731 for route in payment_params.payee.unblinded_route_hints().iter()
2732 .filter(|route| !route.0.is_empty())
2734 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2735 let first_hop_src_is_reachable =
2736 // Only add the hops in this route to our candidate set if either we are part of
2737 // the first hop, we have a direct channel to the first hop, or the first hop is in
2738 // the regular network graph.
2739 our_node_id == first_hop_src_id ||
2740 first_hop_targets.get(&first_hop_src_id).is_some() ||
2741 network_nodes.get(&first_hop_src_id).is_some();
2742 if first_hop_src_is_reachable {
2743 // We start building the path from reverse, i.e., from payee
2744 // to the first RouteHintHop in the path.
2745 let hop_iter = route.0.iter().rev();
2746 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2747 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2748 let mut hop_used = true;
2749 let mut aggregate_next_hops_fee_msat: u64 = 0;
2750 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2751 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2752 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2753 let mut aggregate_next_hops_path_length: u8 = 0;
2754 let mut aggregate_path_contribution_msat = path_value_msat;
2756 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2757 let (target, private_target_node_counter) =
2758 node_counters.node_counter_from_pubkey(&prev_hop_id)
2759 .expect("node_counter_from_pubkey is called on all unblinded_route_hints keys during setup, so is always Some here");
2760 let (_src_id, private_source_node_counter) =
2761 node_counters.node_counter_from_pubkey(&hop.src_node_id)
2762 .expect("node_counter_from_pubkey is called on all unblinded_route_hints keys during setup, so is always Some here");
2764 if let Some((first_channels, _)) = first_hop_targets.get(target) {
2765 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2766 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2767 hop.short_channel_id);
2772 let candidate = network_channels
2773 .get(&hop.short_channel_id)
2774 .and_then(|channel| channel.as_directed_to(target))
2775 .map(|(info, _)| CandidateRouteHop::PublicHop(PublicHopCandidate {
2777 short_channel_id: hop.short_channel_id,
2779 .unwrap_or_else(|| CandidateRouteHop::PrivateHop(PrivateHopCandidate {
2780 hint: hop, target_node_id: target,
2781 source_node_counter: *private_source_node_counter,
2782 target_node_counter: *private_target_node_counter,
2785 if let Some(hop_used_msat) = add_entry!(&candidate,
2786 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2787 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2788 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2790 aggregate_path_contribution_msat = hop_used_msat;
2792 // If this hop was not used then there is no use checking the preceding
2793 // hops in the RouteHint. We can break by just searching for a direct
2794 // channel between last checked hop and first_hop_targets.
2798 let used_liquidity_msat = used_liquidities
2799 .get(&candidate.id()).copied()
2801 let channel_usage = ChannelUsage {
2802 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2803 inflight_htlc_msat: used_liquidity_msat,
2804 effective_capacity: candidate.effective_capacity(),
2806 let channel_penalty_msat = scorer.channel_penalty_msat(
2807 &candidate, channel_usage, score_params
2809 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2810 .saturating_add(channel_penalty_msat);
2812 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2813 .saturating_add(hop.cltv_expiry_delta as u32);
2815 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2818 // Searching for a direct channel between last checked hop and first_hop_targets
2819 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get_mut(target) {
2820 sort_first_hop_channels(first_channels, &used_liquidities,
2821 recommended_value_msat, our_node_pubkey);
2822 for details in first_channels {
2823 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2824 details, payer_node_id: &our_node_id, payer_node_counter,
2825 target_node_counter: *peer_node_counter,
2827 add_entry!(&first_hop_candidate,
2828 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2829 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2830 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2838 // In the next values of the iterator, the aggregate fees already reflects
2839 // the sum of value sent from payer (final_value_msat) and routing fees
2840 // for the last node in the RouteHint. We need to just add the fees to
2841 // route through the current node so that the preceding node (next iteration)
2843 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2844 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2845 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2847 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2848 // this route hint's source node to forward said min over this channel.
2849 aggregate_next_hops_path_htlc_minimum_msat = {
2850 let curr_htlc_min = cmp::max(
2851 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2853 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2854 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2857 if idx == route.0.len() - 1 {
2858 // The last hop in this iterator is the first hop in
2859 // overall RouteHint.
2860 // If this hop connects to a node with which we have a direct channel,
2861 // ignore the network graph and, if the last hop was added, add our
2862 // direct channel to the candidate set.
2864 // Note that we *must* check if the last hop was added as `add_entry`
2865 // always assumes that the third argument is a node to which we have a
2867 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2868 sort_first_hop_channels(first_channels, &used_liquidities,
2869 recommended_value_msat, our_node_pubkey);
2870 for details in first_channels {
2871 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2872 details, payer_node_id: &our_node_id, payer_node_counter,
2873 target_node_counter: *peer_node_counter,
2875 add_entry!(&first_hop_candidate,
2876 aggregate_next_hops_fee_msat,
2877 aggregate_path_contribution_msat,
2878 aggregate_next_hops_path_htlc_minimum_msat,
2879 aggregate_next_hops_path_penalty_msat,
2880 aggregate_next_hops_cltv_delta,
2881 aggregate_next_hops_path_length);
2889 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2891 // At this point, targets are filled with the data from first and
2892 // last hops communicated by the caller, and the payment receiver.
2893 let mut found_new_path = false;
2896 // If this loop terminates due the exhaustion of targets, two situations are possible:
2897 // - not enough outgoing liquidity:
2898 // 0 < already_collected_value_msat < final_value_msat
2899 // - enough outgoing liquidity:
2900 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2901 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2902 // paths_collection will be stopped because found_new_path==false.
2903 // This is not necessarily a routing failure.
2904 'path_construction: while let Some(RouteGraphNode { node_id, total_cltv_delta, mut value_contribution_msat, path_length_to_node, .. }) = targets.pop() {
2906 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2907 // traversing the graph and arrange the path out of what we found.
2908 if node_id == our_node_id {
2909 let mut new_entry = dist[payer_node_counter as usize].take().unwrap();
2910 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2913 let mut features_set = false;
2914 let candidate = &ordered_hops.last().unwrap().0.candidate;
2915 let target = candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2916 let target_node_counter = candidate.target_node_counter();
2917 if let Some((first_channels, _)) = first_hop_targets.get(&target) {
2918 for details in first_channels {
2919 if let CandidateRouteHop::FirstHop(FirstHopCandidate { details: last_hop_details, .. })
2920 = ordered_hops.last().unwrap().0.candidate
2922 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2923 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2924 features_set = true;
2931 if let Some(node) = network_nodes.get(&target) {
2932 if let Some(node_info) = node.announcement_info.as_ref() {
2933 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2935 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2938 // We can fill in features for everything except hops which were
2939 // provided via the invoice we're paying. We could guess based on the
2940 // recipient's features but for now we simply avoid guessing at all.
2944 // Means we successfully traversed from the payer to the payee, now
2945 // save this path for the payment route. Also, update the liquidity
2946 // remaining on the used hops, so that we take them into account
2947 // while looking for more paths.
2948 if target_node_counter.is_none() {
2951 if target_node_counter == Some(payee_node_counter) { break 'path_walk; }
2953 new_entry = match dist[target_node_counter.unwrap() as usize].take() {
2954 Some(payment_hop) => payment_hop,
2955 // We can't arrive at None because, if we ever add an entry to targets,
2956 // we also fill in the entry in dist (see add_entry!).
2957 None => unreachable!(),
2959 // We "propagate" the fees one hop backward (topologically) here,
2960 // so that fees paid for a HTLC forwarding on the current channel are
2961 // associated with the previous channel (where they will be subtracted).
2962 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2963 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2965 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2966 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2968 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2969 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2971 let mut payment_path = PaymentPath {hops: ordered_hops};
2973 // We could have possibly constructed a slightly inconsistent path: since we reduce
2974 // value being transferred along the way, we could have violated htlc_minimum_msat
2975 // on some channels we already passed (assuming dest->source direction). Here, we
2976 // recompute the fees again, so that if that's the case, we match the currently
2977 // underpaid htlc_minimum_msat with fees.
2978 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2979 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2980 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2982 // Since a path allows to transfer as much value as
2983 // the smallest channel it has ("bottleneck"), we should recompute
2984 // the fees so sender HTLC don't overpay fees when traversing
2985 // larger channels than the bottleneck. This may happen because
2986 // when we were selecting those channels we were not aware how much value
2987 // this path will transfer, and the relative fee for them
2988 // might have been computed considering a larger value.
2989 // Remember that we used these channels so that we don't rely
2990 // on the same liquidity in future paths.
2991 let mut prevented_redundant_path_selection = false;
2992 for (hop, _) in payment_path.hops.iter() {
2993 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2994 let used_liquidity_msat = used_liquidities
2995 .entry(hop.candidate.id())
2996 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2997 .or_insert(spent_on_hop_msat);
2998 let hop_capacity = hop.candidate.effective_capacity();
2999 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
3000 if *used_liquidity_msat == hop_max_msat {
3001 // If this path used all of this channel's available liquidity, we know
3002 // this path will not be selected again in the next loop iteration.
3003 prevented_redundant_path_selection = true;
3005 debug_assert!(*used_liquidity_msat <= hop_max_msat);
3007 if !prevented_redundant_path_selection {
3008 // If we weren't capped by hitting a liquidity limit on a channel in the path,
3009 // we'll probably end up picking the same path again on the next iteration.
3010 // Decrease the available liquidity of a hop in the middle of the path.
3011 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
3012 let exhausted = u64::max_value();
3014 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
3015 LoggedCandidateHop(victim_candidate));
3016 if let Some(scid) = victim_candidate.short_channel_id() {
3017 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
3018 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
3022 // Track the total amount all our collected paths allow to send so that we know
3023 // when to stop looking for more paths
3024 already_collected_value_msat += value_contribution_msat;
3026 payment_paths.push(payment_path);
3027 found_new_path = true;
3028 break 'path_construction;
3031 // If we found a path back to the payee, we shouldn't try to process it again. This is
3032 // the equivalent of the `elem.was_processed` check in
3033 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
3034 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
3036 // Otherwise, since the current target node is not us,
3037 // keep "unrolling" the payment graph from payee to payer by
3038 // finding a way to reach the current target from the payer side.
3039 match network_nodes.get(&node_id) {
3042 add_entries_to_cheapest_to_target_node!(node, node_id,
3043 value_contribution_msat,
3044 total_cltv_delta, path_length_to_node);
3050 if !found_new_path && channel_saturation_pow_half != 0 {
3051 channel_saturation_pow_half = 0;
3052 continue 'paths_collection;
3054 // If we don't support MPP, no use trying to gather more value ever.
3055 break 'paths_collection;
3059 // Stop either when the recommended value is reached or if no new path was found in this
3061 // In the latter case, making another path finding attempt won't help,
3062 // because we deterministically terminated the search due to low liquidity.
3063 if !found_new_path && channel_saturation_pow_half != 0 {
3064 channel_saturation_pow_half = 0;
3065 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
3066 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
3067 path_value_msat = recommended_value_msat;
3068 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
3069 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
3070 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
3071 break 'paths_collection;
3072 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
3073 // Further, if this was our first walk of the graph, and we weren't limited by an
3074 // htlc_minimum_msat, return immediately because this path should suffice. If we were
3075 // limited by an htlc_minimum_msat value, find another path with a higher value,
3076 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
3077 // still keeping a lower total fee than this path.
3078 if !hit_minimum_limit {
3079 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
3080 break 'paths_collection;
3082 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.");
3083 path_value_msat = recommended_value_msat;
3087 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
3088 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
3089 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
3090 num_ignored_total_fee_limit;
3091 if num_ignored_total > 0 {
3093 "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.",
3094 num_ignored_value_contribution, num_ignored_path_length_limit,
3095 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
3096 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
3097 num_ignored_total_fee_limit, num_ignored_total);
3101 if payment_paths.len() == 0 {
3102 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
3105 if already_collected_value_msat < final_value_msat {
3106 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
3110 let mut selected_route = payment_paths;
3112 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
3113 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
3115 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
3116 // the value they contribute towards the payment amount.
3117 // We sort in descending order as we will remove from the front in `retain`, next.
3118 selected_route.sort_unstable_by(|a, b|
3119 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
3120 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
3123 // We should make sure that at least 1 path left.
3124 let mut paths_left = selected_route.len();
3125 selected_route.retain(|path| {
3126 if paths_left == 1 {
3129 let path_value_msat = path.get_value_msat();
3130 if path_value_msat <= overpaid_value_msat {
3131 overpaid_value_msat -= path_value_msat;
3137 debug_assert!(selected_route.len() > 0);
3139 if overpaid_value_msat != 0 {
3141 // Now, subtract the remaining overpaid value from the most-expensive path.
3142 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
3143 // so that the sender pays less fees overall. And also htlc_minimum_msat.
3144 selected_route.sort_unstable_by(|a, b| {
3145 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3146 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3147 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
3149 let expensive_payment_path = selected_route.first_mut().unwrap();
3151 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
3152 // can't go negative.
3153 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
3154 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
3158 // Sort by the path itself and combine redundant paths.
3159 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
3160 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
3162 selected_route.sort_unstable_by_key(|path| {
3163 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
3164 debug_assert!(path.hops.len() <= key.len());
3165 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
3170 for idx in 0..(selected_route.len() - 1) {
3171 if idx + 1 >= selected_route.len() { break; }
3172 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
3173 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
3174 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
3175 selected_route[idx].update_value_and_recompute_fees(new_value);
3176 selected_route.remove(idx + 1);
3180 let mut paths = Vec::new();
3181 for payment_path in selected_route {
3182 let mut hops = Vec::with_capacity(payment_path.hops.len());
3183 for (hop, node_features) in payment_path.hops.iter()
3184 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
3186 let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
3187 let maybe_announced_channel = if let CandidateRouteHop::PublicHop(_) = hop.candidate {
3188 // If we sourced the hop from the graph we're sure the target node is announced.
3190 } else if let CandidateRouteHop::FirstHop(first_hop) = &hop.candidate {
3191 // If this is a first hop we also know if it's announced.
3192 first_hop.details.is_public
3194 // If we sourced it any other way, we double-check the network graph to see if
3195 // there are announced channels between the endpoints. If so, the hop might be
3196 // referring to any of the announced channels, as its `short_channel_id` might be
3197 // an alias, in which case we don't take any chances here.
3198 network_graph.node(&target).map_or(false, |hop_node|
3199 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
3200 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
3204 hops.push(RouteHop {
3205 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
3206 node_features: node_features.clone(),
3207 short_channel_id: hop.candidate.short_channel_id().unwrap(),
3208 channel_features: hop.candidate.features(),
3209 fee_msat: hop.fee_msat,
3210 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
3211 maybe_announced_channel,
3214 let mut final_cltv_delta = final_cltv_expiry_delta;
3215 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
3216 if let Some(blinded_path) = h.candidate.blinded_path() {
3217 final_cltv_delta = h.candidate.cltv_expiry_delta();
3219 hops: blinded_path.blinded_hops.clone(),
3220 blinding_point: blinded_path.blinding_point,
3221 excess_final_cltv_expiry_delta: 0,
3222 final_value_msat: h.fee_msat,
3226 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
3227 // applicable for the previous hop.
3228 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
3229 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
3232 paths.push(Path { hops, blinded_tail });
3234 // Make sure we would never create a route with more paths than we allow.
3235 debug_assert!(paths.len() <= payment_params.max_path_count.into());
3237 if let Some(node_features) = payment_params.payee.node_features() {
3238 for path in paths.iter_mut() {
3239 path.hops.last_mut().unwrap().node_features = node_features.clone();
3243 let route = Route { paths, route_params: Some(route_params.clone()) };
3245 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
3246 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
3247 if route.get_total_fees() > max_total_routing_fee_msat {
3248 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
3249 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
3253 log_info!(logger, "Got route: {}", log_route!(route));
3257 // When an adversarial intermediary node observes a payment, it may be able to infer its
3258 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
3259 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
3260 // payment path by adding a randomized 'shadow route' offset to the final hop.
3261 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
3262 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
3264 let network_channels = network_graph.channels();
3265 let network_nodes = network_graph.nodes();
3267 for path in route.paths.iter_mut() {
3268 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
3270 // Remember the last three nodes of the random walk and avoid looping back on them.
3271 // Init with the last three nodes from the actual path, if possible.
3272 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
3273 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
3274 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
3276 // Choose the last publicly known node as the starting point for the random walk.
3277 let mut cur_hop: Option<NodeId> = None;
3278 let mut path_nonce = [0u8; 12];
3279 if let Some(starting_hop) = path.hops.iter().rev()
3280 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
3281 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
3282 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
3285 // Init PRNG with the path-dependant nonce, which is static for private paths.
3286 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
3287 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
3289 // Pick a random path length in [1 .. 3]
3290 prng.process_in_place(&mut random_path_bytes);
3291 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
3293 for random_hop in 0..random_walk_length {
3294 // If we don't find a suitable offset in the public network graph, we default to
3295 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3296 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
3298 if let Some(cur_node_id) = cur_hop {
3299 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
3300 // Randomly choose the next unvisited hop.
3301 prng.process_in_place(&mut random_path_bytes);
3302 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
3303 .checked_rem(cur_node.channels.len())
3304 .and_then(|index| cur_node.channels.get(index))
3305 .and_then(|id| network_channels.get(id)) {
3306 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
3307 if !nodes_to_avoid.iter().any(|x| x == next_id) {
3308 nodes_to_avoid[random_hop] = *next_id;
3309 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
3310 cur_hop = Some(*next_id);
3317 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
3318 .checked_add(random_hop_offset)
3319 .unwrap_or(shadow_ctlv_expiry_delta_offset);
3322 // Limit the total offset to reduce the worst-case locked liquidity timevalue
3323 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
3324 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
3326 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
3327 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3328 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
3329 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
3330 max_path_offset = cmp::max(
3331 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
3332 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
3333 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
3335 // Add 'shadow' CLTV offset to the final hop
3336 if let Some(tail) = path.blinded_tail.as_mut() {
3337 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
3338 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
3340 if let Some(last_hop) = path.hops.last_mut() {
3341 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
3342 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
3347 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
3348 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
3350 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
3351 pub fn build_route_from_hops<L: Deref, GL: Deref>(
3352 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3353 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
3354 ) -> Result<Route, LightningError>
3355 where L::Target: Logger, GL::Target: Logger {
3356 let graph_lock = network_graph.read_only();
3357 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
3358 &graph_lock, logger, random_seed_bytes)?;
3359 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
3363 fn build_route_from_hops_internal<L: Deref>(
3364 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3365 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
3366 ) -> Result<Route, LightningError> where L::Target: Logger {
3369 our_node_id: NodeId,
3370 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
3373 impl ScoreLookUp for HopScorer {
3374 type ScoreParams = ();
3375 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
3376 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
3378 let mut cur_id = self.our_node_id;
3379 for i in 0..self.hop_ids.len() {
3380 if let Some(next_id) = self.hop_ids[i] {
3381 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
3393 impl<'a> Writeable for HopScorer {
3395 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
3400 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
3401 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
3404 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
3405 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
3406 for i in 0..hops.len() {
3407 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
3410 let scorer = HopScorer { our_node_id, hop_ids };
3412 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
3417 use crate::blinded_path::{BlindedHop, BlindedPath};
3418 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
3419 use crate::routing::utxo::UtxoResult;
3420 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
3421 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
3422 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop, PublicHopCandidate};
3423 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
3424 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
3425 use crate::chain::transaction::OutPoint;
3426 use crate::sign::EntropySource;
3427 use crate::ln::ChannelId;
3428 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
3429 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
3430 use crate::ln::channelmanager;
3431 use crate::offers::invoice::BlindedPayInfo;
3432 use crate::util::config::UserConfig;
3433 use crate::util::test_utils as ln_test_utils;
3434 use crate::crypto::chacha20::ChaCha20;
3435 use crate::util::ser::{Readable, Writeable};
3437 use crate::util::ser::Writer;
3439 use bitcoin::hashes::Hash;
3440 use bitcoin::network::constants::Network;
3441 use bitcoin::blockdata::constants::ChainHash;
3442 use bitcoin::blockdata::script::Builder;
3443 use bitcoin::blockdata::opcodes;
3444 use bitcoin::blockdata::transaction::TxOut;
3445 use bitcoin::hashes::hex::FromHex;
3446 use bitcoin::secp256k1::{PublicKey,SecretKey};
3447 use bitcoin::secp256k1::Secp256k1;
3449 use crate::io::Cursor;
3450 use crate::prelude::*;
3451 use crate::sync::Arc;
3453 use core::convert::TryInto;
3455 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3456 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
3457 channelmanager::ChannelDetails {
3458 channel_id: ChannelId::new_zero(),
3459 counterparty: channelmanager::ChannelCounterparty {
3462 unspendable_punishment_reserve: 0,
3463 forwarding_info: None,
3464 outbound_htlc_minimum_msat: None,
3465 outbound_htlc_maximum_msat: None,
3467 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3470 outbound_scid_alias: None,
3471 inbound_scid_alias: None,
3472 channel_value_satoshis: 0,
3475 outbound_capacity_msat,
3476 next_outbound_htlc_limit_msat: outbound_capacity_msat,
3477 next_outbound_htlc_minimum_msat: 0,
3478 inbound_capacity_msat: 42,
3479 unspendable_punishment_reserve: None,
3480 confirmations_required: None,
3481 confirmations: None,
3482 force_close_spend_delay: None,
3483 is_outbound: true, is_channel_ready: true,
3484 is_usable: true, is_public: true,
3485 inbound_htlc_minimum_msat: None,
3486 inbound_htlc_maximum_msat: None,
3488 feerate_sat_per_1000_weight: None,
3489 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
3490 pending_inbound_htlcs: Vec::new(),
3491 pending_outbound_htlcs: Vec::new(),
3496 fn simple_route_test() {
3497 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3498 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3499 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3500 let scorer = ln_test_utils::TestScorer::new();
3501 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3502 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3504 // Simple route to 2 via 1
3506 let route_params = RouteParameters::from_payment_params_and_value(
3507 payment_params.clone(), 0);
3508 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3509 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3510 &Default::default(), &random_seed_bytes) {
3511 assert_eq!(err, "Cannot send a payment of 0 msat");
3512 } else { panic!(); }
3514 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3515 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3516 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3517 assert_eq!(route.paths[0].hops.len(), 2);
3519 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3520 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3521 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3522 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3523 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3524 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3526 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3527 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3528 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3529 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3530 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3531 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3535 fn invalid_first_hop_test() {
3536 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3537 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3538 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3539 let scorer = ln_test_utils::TestScorer::new();
3540 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3541 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3543 // Simple route to 2 via 1
3545 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3547 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3548 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3549 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3550 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3551 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3552 } else { panic!(); }
3554 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3555 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3556 assert_eq!(route.paths[0].hops.len(), 2);
3560 fn htlc_minimum_test() {
3561 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3562 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3563 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3564 let scorer = ln_test_utils::TestScorer::new();
3565 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3566 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3568 // Simple route to 2 via 1
3570 // Disable other paths
3571 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3572 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3573 short_channel_id: 12,
3575 flags: 2, // to disable
3576 cltv_expiry_delta: 0,
3577 htlc_minimum_msat: 0,
3578 htlc_maximum_msat: MAX_VALUE_MSAT,
3580 fee_proportional_millionths: 0,
3581 excess_data: Vec::new()
3583 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3584 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3585 short_channel_id: 3,
3587 flags: 2, // to disable
3588 cltv_expiry_delta: 0,
3589 htlc_minimum_msat: 0,
3590 htlc_maximum_msat: MAX_VALUE_MSAT,
3592 fee_proportional_millionths: 0,
3593 excess_data: Vec::new()
3595 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3596 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3597 short_channel_id: 13,
3599 flags: 2, // to disable
3600 cltv_expiry_delta: 0,
3601 htlc_minimum_msat: 0,
3602 htlc_maximum_msat: MAX_VALUE_MSAT,
3604 fee_proportional_millionths: 0,
3605 excess_data: Vec::new()
3607 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3608 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3609 short_channel_id: 6,
3611 flags: 2, // to disable
3612 cltv_expiry_delta: 0,
3613 htlc_minimum_msat: 0,
3614 htlc_maximum_msat: MAX_VALUE_MSAT,
3616 fee_proportional_millionths: 0,
3617 excess_data: Vec::new()
3619 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3620 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3621 short_channel_id: 7,
3623 flags: 2, // to disable
3624 cltv_expiry_delta: 0,
3625 htlc_minimum_msat: 0,
3626 htlc_maximum_msat: MAX_VALUE_MSAT,
3628 fee_proportional_millionths: 0,
3629 excess_data: Vec::new()
3632 // Check against amount_to_transfer_over_msat.
3633 // Set minimal HTLC of 200_000_000 msat.
3634 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3635 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3636 short_channel_id: 2,
3639 cltv_expiry_delta: 0,
3640 htlc_minimum_msat: 200_000_000,
3641 htlc_maximum_msat: MAX_VALUE_MSAT,
3643 fee_proportional_millionths: 0,
3644 excess_data: Vec::new()
3647 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3649 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3650 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3651 short_channel_id: 4,
3654 cltv_expiry_delta: 0,
3655 htlc_minimum_msat: 0,
3656 htlc_maximum_msat: 199_999_999,
3658 fee_proportional_millionths: 0,
3659 excess_data: Vec::new()
3662 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3663 let route_params = RouteParameters::from_payment_params_and_value(
3664 payment_params, 199_999_999);
3665 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3666 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3667 &Default::default(), &random_seed_bytes) {
3668 assert_eq!(err, "Failed to find a path to the given destination");
3669 } else { panic!(); }
3671 // Lift the restriction on the first hop.
3672 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3673 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3674 short_channel_id: 2,
3677 cltv_expiry_delta: 0,
3678 htlc_minimum_msat: 0,
3679 htlc_maximum_msat: MAX_VALUE_MSAT,
3681 fee_proportional_millionths: 0,
3682 excess_data: Vec::new()
3685 // A payment above the minimum should pass
3686 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3687 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3688 assert_eq!(route.paths[0].hops.len(), 2);
3692 fn htlc_minimum_overpay_test() {
3693 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3694 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3695 let config = UserConfig::default();
3696 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3697 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3699 let scorer = ln_test_utils::TestScorer::new();
3700 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3701 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3703 // A route to node#2 via two paths.
3704 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3705 // Thus, they can't send 60 without overpaying.
3706 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3707 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3708 short_channel_id: 2,
3711 cltv_expiry_delta: 0,
3712 htlc_minimum_msat: 35_000,
3713 htlc_maximum_msat: 40_000,
3715 fee_proportional_millionths: 0,
3716 excess_data: Vec::new()
3718 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3719 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3720 short_channel_id: 12,
3723 cltv_expiry_delta: 0,
3724 htlc_minimum_msat: 35_000,
3725 htlc_maximum_msat: 40_000,
3727 fee_proportional_millionths: 0,
3728 excess_data: Vec::new()
3732 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3733 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3734 short_channel_id: 13,
3737 cltv_expiry_delta: 0,
3738 htlc_minimum_msat: 0,
3739 htlc_maximum_msat: MAX_VALUE_MSAT,
3741 fee_proportional_millionths: 0,
3742 excess_data: Vec::new()
3744 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3745 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3746 short_channel_id: 4,
3749 cltv_expiry_delta: 0,
3750 htlc_minimum_msat: 0,
3751 htlc_maximum_msat: MAX_VALUE_MSAT,
3753 fee_proportional_millionths: 0,
3754 excess_data: Vec::new()
3757 // Disable other paths
3758 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3759 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3760 short_channel_id: 1,
3762 flags: 2, // to disable
3763 cltv_expiry_delta: 0,
3764 htlc_minimum_msat: 0,
3765 htlc_maximum_msat: MAX_VALUE_MSAT,
3767 fee_proportional_millionths: 0,
3768 excess_data: Vec::new()
3771 let mut route_params = RouteParameters::from_payment_params_and_value(
3772 payment_params.clone(), 60_000);
3773 route_params.max_total_routing_fee_msat = Some(15_000);
3774 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3775 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3776 // Overpay fees to hit htlc_minimum_msat.
3777 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3778 // TODO: this could be better balanced to overpay 10k and not 15k.
3779 assert_eq!(overpaid_fees, 15_000);
3781 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3782 // while taking even more fee to match htlc_minimum_msat.
3783 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3784 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3785 short_channel_id: 12,
3788 cltv_expiry_delta: 0,
3789 htlc_minimum_msat: 65_000,
3790 htlc_maximum_msat: 80_000,
3792 fee_proportional_millionths: 0,
3793 excess_data: Vec::new()
3795 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3796 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3797 short_channel_id: 2,
3800 cltv_expiry_delta: 0,
3801 htlc_minimum_msat: 0,
3802 htlc_maximum_msat: MAX_VALUE_MSAT,
3804 fee_proportional_millionths: 0,
3805 excess_data: Vec::new()
3807 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3808 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3809 short_channel_id: 4,
3812 cltv_expiry_delta: 0,
3813 htlc_minimum_msat: 0,
3814 htlc_maximum_msat: MAX_VALUE_MSAT,
3816 fee_proportional_millionths: 100_000,
3817 excess_data: Vec::new()
3820 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3821 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3822 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3823 assert_eq!(route.paths.len(), 1);
3824 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3825 let fees = route.paths[0].hops[0].fee_msat;
3826 assert_eq!(fees, 5_000);
3828 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3829 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3830 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3831 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3832 // the other channel.
3833 assert_eq!(route.paths.len(), 1);
3834 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3835 let fees = route.paths[0].hops[0].fee_msat;
3836 assert_eq!(fees, 5_000);
3840 fn htlc_minimum_recipient_overpay_test() {
3841 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3842 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3843 let config = UserConfig::default();
3844 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3845 let scorer = ln_test_utils::TestScorer::new();
3846 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3847 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3849 // Route to node2 over a single path which requires overpaying the recipient themselves.
3851 // First disable all paths except the us -> node1 -> node2 path
3852 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3853 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3854 short_channel_id: 13,
3857 cltv_expiry_delta: 0,
3858 htlc_minimum_msat: 0,
3859 htlc_maximum_msat: 0,
3861 fee_proportional_millionths: 0,
3862 excess_data: Vec::new()
3865 // Set channel 4 to free but with a high htlc_minimum_msat
3866 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3867 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3868 short_channel_id: 4,
3871 cltv_expiry_delta: 0,
3872 htlc_minimum_msat: 15_000,
3873 htlc_maximum_msat: MAX_VALUE_MSAT,
3875 fee_proportional_millionths: 0,
3876 excess_data: Vec::new()
3879 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3880 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3881 // what we try to find a route for, so this test only just happens to work out to exactly
3883 let mut route_params = RouteParameters::from_payment_params_and_value(
3884 payment_params.clone(), 5_000);
3885 route_params.max_total_routing_fee_msat = Some(9_999);
3886 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3887 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3888 &Default::default(), &random_seed_bytes) {
3889 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3890 } else { panic!(); }
3892 let mut route_params = RouteParameters::from_payment_params_and_value(
3893 payment_params.clone(), 5_000);
3894 route_params.max_total_routing_fee_msat = Some(10_000);
3895 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3896 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3897 assert_eq!(route.get_total_fees(), 10_000);
3901 fn disable_channels_test() {
3902 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3903 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3904 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3905 let scorer = ln_test_utils::TestScorer::new();
3906 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3907 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3909 // // Disable channels 4 and 12 by flags=2
3910 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3911 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3912 short_channel_id: 4,
3914 flags: 2, // to disable
3915 cltv_expiry_delta: 0,
3916 htlc_minimum_msat: 0,
3917 htlc_maximum_msat: MAX_VALUE_MSAT,
3919 fee_proportional_millionths: 0,
3920 excess_data: Vec::new()
3922 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3923 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3924 short_channel_id: 12,
3926 flags: 2, // to disable
3927 cltv_expiry_delta: 0,
3928 htlc_minimum_msat: 0,
3929 htlc_maximum_msat: MAX_VALUE_MSAT,
3931 fee_proportional_millionths: 0,
3932 excess_data: Vec::new()
3935 // If all the channels require some features we don't understand, route should fail
3936 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3937 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3938 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3939 &Default::default(), &random_seed_bytes) {
3940 assert_eq!(err, "Failed to find a path to the given destination");
3941 } else { panic!(); }
3943 // If we specify a channel to node7, that overrides our local channel view and that gets used
3944 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3945 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3946 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3947 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3948 &Default::default(), &random_seed_bytes).unwrap();
3949 assert_eq!(route.paths[0].hops.len(), 2);
3951 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3952 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3953 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3954 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3955 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3956 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3958 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3959 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3960 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3961 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3962 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3963 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3967 fn disable_node_test() {
3968 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3969 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3970 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3971 let scorer = ln_test_utils::TestScorer::new();
3972 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3973 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3975 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3976 let mut unknown_features = NodeFeatures::empty();
3977 unknown_features.set_unknown_feature_required();
3978 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3979 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3980 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3982 // If all nodes require some features we don't understand, route should fail
3983 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3984 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3985 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3986 &Default::default(), &random_seed_bytes) {
3987 assert_eq!(err, "Failed to find a path to the given destination");
3988 } else { panic!(); }
3990 // If we specify a channel to node7, that overrides our local channel view and that gets used
3991 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3992 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3993 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3994 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3995 &Default::default(), &random_seed_bytes).unwrap();
3996 assert_eq!(route.paths[0].hops.len(), 2);
3998 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3999 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4000 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4001 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
4002 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
4003 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4005 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4006 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
4007 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4008 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4009 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4010 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
4012 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
4013 // naively) assume that the user checked the feature bits on the invoice, which override
4014 // the node_announcement.
4018 fn our_chans_test() {
4019 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4020 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4021 let scorer = ln_test_utils::TestScorer::new();
4022 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4023 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4025 // Route to 1 via 2 and 3 because our channel to 1 is disabled
4026 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
4027 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4028 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4029 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4030 assert_eq!(route.paths[0].hops.len(), 3);
4032 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4033 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4034 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4035 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4036 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4037 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4039 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4040 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4041 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4042 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
4043 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4044 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4046 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
4047 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
4048 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
4049 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
4050 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
4051 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
4053 // If we specify a channel to node7, that overrides our local channel view and that gets used
4054 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4055 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4056 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
4057 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4058 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4059 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4060 &Default::default(), &random_seed_bytes).unwrap();
4061 assert_eq!(route.paths[0].hops.len(), 2);
4063 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
4064 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4065 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4066 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
4067 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4068 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4070 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4071 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
4072 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4073 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4074 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4075 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
4078 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4079 let zero_fees = RoutingFees {
4081 proportional_millionths: 0,
4083 vec![RouteHint(vec![RouteHintHop {
4084 src_node_id: nodes[3],
4085 short_channel_id: 8,
4087 cltv_expiry_delta: (8 << 4) | 1,
4088 htlc_minimum_msat: None,
4089 htlc_maximum_msat: None,
4091 ]), RouteHint(vec![RouteHintHop {
4092 src_node_id: nodes[4],
4093 short_channel_id: 9,
4096 proportional_millionths: 0,
4098 cltv_expiry_delta: (9 << 4) | 1,
4099 htlc_minimum_msat: None,
4100 htlc_maximum_msat: None,
4101 }]), RouteHint(vec![RouteHintHop {
4102 src_node_id: nodes[5],
4103 short_channel_id: 10,
4105 cltv_expiry_delta: (10 << 4) | 1,
4106 htlc_minimum_msat: None,
4107 htlc_maximum_msat: None,
4111 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4112 let zero_fees = RoutingFees {
4114 proportional_millionths: 0,
4116 vec![RouteHint(vec![RouteHintHop {
4117 src_node_id: nodes[2],
4118 short_channel_id: 5,
4121 proportional_millionths: 0,
4123 cltv_expiry_delta: (5 << 4) | 1,
4124 htlc_minimum_msat: None,
4125 htlc_maximum_msat: None,
4127 src_node_id: nodes[3],
4128 short_channel_id: 8,
4130 cltv_expiry_delta: (8 << 4) | 1,
4131 htlc_minimum_msat: None,
4132 htlc_maximum_msat: None,
4134 ]), RouteHint(vec![RouteHintHop {
4135 src_node_id: nodes[4],
4136 short_channel_id: 9,
4139 proportional_millionths: 0,
4141 cltv_expiry_delta: (9 << 4) | 1,
4142 htlc_minimum_msat: None,
4143 htlc_maximum_msat: None,
4144 }]), RouteHint(vec![RouteHintHop {
4145 src_node_id: nodes[5],
4146 short_channel_id: 10,
4148 cltv_expiry_delta: (10 << 4) | 1,
4149 htlc_minimum_msat: None,
4150 htlc_maximum_msat: None,
4155 fn partial_route_hint_test() {
4156 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4157 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4158 let scorer = ln_test_utils::TestScorer::new();
4159 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4160 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4162 // Simple test across 2, 3, 5, and 4 via a last_hop channel
4163 // Tests the behaviour when the RouteHint contains a suboptimal hop.
4164 // RouteHint may be partially used by the algo to build the best path.
4166 // First check that last hop can't have its source as the payee.
4167 let invalid_last_hop = RouteHint(vec![RouteHintHop {
4168 src_node_id: nodes[6],
4169 short_channel_id: 8,
4172 proportional_millionths: 0,
4174 cltv_expiry_delta: (8 << 4) | 1,
4175 htlc_minimum_msat: None,
4176 htlc_maximum_msat: None,
4179 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
4180 invalid_last_hops.push(invalid_last_hop);
4182 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4183 .with_route_hints(invalid_last_hops).unwrap();
4184 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4185 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
4186 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
4187 &Default::default(), &random_seed_bytes) {
4188 assert_eq!(err, "Route hint cannot have the payee as the source.");
4189 } else { panic!(); }
4192 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4193 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
4194 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4195 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4196 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4197 assert_eq!(route.paths[0].hops.len(), 5);
4199 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4200 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4201 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4202 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4203 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4204 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4206 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4207 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4208 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4209 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4210 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4211 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4213 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4214 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4215 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4216 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4217 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4218 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4220 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4221 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4222 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4223 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4224 // If we have a peer in the node map, we'll use their features here since we don't have
4225 // a way of figuring out their features from the invoice:
4226 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4227 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4229 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4230 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4231 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4232 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4233 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4234 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4237 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4238 let zero_fees = RoutingFees {
4240 proportional_millionths: 0,
4242 vec![RouteHint(vec![RouteHintHop {
4243 src_node_id: nodes[3],
4244 short_channel_id: 8,
4246 cltv_expiry_delta: (8 << 4) | 1,
4247 htlc_minimum_msat: None,
4248 htlc_maximum_msat: None,
4249 }]), RouteHint(vec![
4251 ]), RouteHint(vec![RouteHintHop {
4252 src_node_id: nodes[5],
4253 short_channel_id: 10,
4255 cltv_expiry_delta: (10 << 4) | 1,
4256 htlc_minimum_msat: None,
4257 htlc_maximum_msat: None,
4262 fn ignores_empty_last_hops_test() {
4263 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4264 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4265 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
4266 let scorer = ln_test_utils::TestScorer::new();
4267 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4268 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4270 // Test handling of an empty RouteHint passed in Invoice.
4271 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4272 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4273 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4274 assert_eq!(route.paths[0].hops.len(), 5);
4276 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4277 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4278 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4279 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4280 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4281 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4283 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4284 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4285 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4286 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4287 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4288 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4290 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4291 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4292 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4293 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4294 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4295 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4297 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4298 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4299 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4300 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4301 // If we have a peer in the node map, we'll use their features here since we don't have
4302 // a way of figuring out their features from the invoice:
4303 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4304 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4306 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4307 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4308 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4309 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4310 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4311 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4314 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
4316 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
4317 let zero_fees = RoutingFees {
4319 proportional_millionths: 0,
4321 vec![RouteHint(vec![RouteHintHop {
4322 src_node_id: hint_hops[0],
4323 short_channel_id: 0xff00,
4326 proportional_millionths: 0,
4328 cltv_expiry_delta: (5 << 4) | 1,
4329 htlc_minimum_msat: None,
4330 htlc_maximum_msat: None,
4332 src_node_id: hint_hops[1],
4333 short_channel_id: 0xff01,
4335 cltv_expiry_delta: (8 << 4) | 1,
4336 htlc_minimum_msat: None,
4337 htlc_maximum_msat: None,
4342 fn multi_hint_last_hops_test() {
4343 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4344 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4345 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
4346 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4347 let scorer = ln_test_utils::TestScorer::new();
4348 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4349 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4350 // Test through channels 2, 3, 0xff00, 0xff01.
4351 // Test shows that multiple hop hints are considered.
4353 // Disabling channels 6 & 7 by flags=2
4354 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4355 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4356 short_channel_id: 6,
4358 flags: 2, // to disable
4359 cltv_expiry_delta: 0,
4360 htlc_minimum_msat: 0,
4361 htlc_maximum_msat: MAX_VALUE_MSAT,
4363 fee_proportional_millionths: 0,
4364 excess_data: Vec::new()
4366 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4367 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4368 short_channel_id: 7,
4370 flags: 2, // to disable
4371 cltv_expiry_delta: 0,
4372 htlc_minimum_msat: 0,
4373 htlc_maximum_msat: MAX_VALUE_MSAT,
4375 fee_proportional_millionths: 0,
4376 excess_data: Vec::new()
4379 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4380 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4381 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4382 assert_eq!(route.paths[0].hops.len(), 4);
4384 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4385 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4386 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4387 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4388 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4389 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4391 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4392 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4393 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4394 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4395 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4396 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4398 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4399 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4400 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4401 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4402 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4403 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4405 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4406 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4407 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4408 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4409 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4410 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4414 fn private_multi_hint_last_hops_test() {
4415 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4416 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4418 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4419 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4421 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4422 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4423 let scorer = ln_test_utils::TestScorer::new();
4424 // Test through channels 2, 3, 0xff00, 0xff01.
4425 // Test shows that multiple hop hints are considered.
4427 // Disabling channels 6 & 7 by flags=2
4428 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4429 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4430 short_channel_id: 6,
4432 flags: 2, // to disable
4433 cltv_expiry_delta: 0,
4434 htlc_minimum_msat: 0,
4435 htlc_maximum_msat: MAX_VALUE_MSAT,
4437 fee_proportional_millionths: 0,
4438 excess_data: Vec::new()
4440 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4441 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4442 short_channel_id: 7,
4444 flags: 2, // to disable
4445 cltv_expiry_delta: 0,
4446 htlc_minimum_msat: 0,
4447 htlc_maximum_msat: MAX_VALUE_MSAT,
4449 fee_proportional_millionths: 0,
4450 excess_data: Vec::new()
4453 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4454 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4455 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4456 assert_eq!(route.paths[0].hops.len(), 4);
4458 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4459 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4460 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4461 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4462 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4463 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4465 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4466 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4467 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4468 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4469 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4470 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4472 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4473 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4474 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4475 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4476 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4477 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4479 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4480 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4481 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4482 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4483 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4484 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4487 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4488 let zero_fees = RoutingFees {
4490 proportional_millionths: 0,
4492 vec![RouteHint(vec![RouteHintHop {
4493 src_node_id: nodes[4],
4494 short_channel_id: 11,
4496 cltv_expiry_delta: (11 << 4) | 1,
4497 htlc_minimum_msat: None,
4498 htlc_maximum_msat: None,
4500 src_node_id: nodes[3],
4501 short_channel_id: 8,
4503 cltv_expiry_delta: (8 << 4) | 1,
4504 htlc_minimum_msat: None,
4505 htlc_maximum_msat: None,
4506 }]), RouteHint(vec![RouteHintHop {
4507 src_node_id: nodes[4],
4508 short_channel_id: 9,
4511 proportional_millionths: 0,
4513 cltv_expiry_delta: (9 << 4) | 1,
4514 htlc_minimum_msat: None,
4515 htlc_maximum_msat: None,
4516 }]), RouteHint(vec![RouteHintHop {
4517 src_node_id: nodes[5],
4518 short_channel_id: 10,
4520 cltv_expiry_delta: (10 << 4) | 1,
4521 htlc_minimum_msat: None,
4522 htlc_maximum_msat: None,
4527 fn last_hops_with_public_channel_test() {
4528 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4529 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4530 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4531 let scorer = ln_test_utils::TestScorer::new();
4532 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4533 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4534 // This test shows that public routes can be present in the invoice
4535 // which would be handled in the same manner.
4537 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4538 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4539 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4540 assert_eq!(route.paths[0].hops.len(), 5);
4542 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4543 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4544 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4545 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4546 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4547 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4549 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4550 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4551 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4552 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4553 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4554 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4556 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4557 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4558 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4559 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4560 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4561 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4563 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4564 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4565 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4566 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4567 // If we have a peer in the node map, we'll use their features here since we don't have
4568 // a way of figuring out their features from the invoice:
4569 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4570 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4572 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4573 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4574 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4575 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4576 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4577 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4581 fn our_chans_last_hop_connect_test() {
4582 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4583 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4584 let scorer = ln_test_utils::TestScorer::new();
4585 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4586 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4588 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4589 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4590 let mut last_hops = last_hops(&nodes);
4591 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4592 .with_route_hints(last_hops.clone()).unwrap();
4593 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4594 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4595 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4596 &Default::default(), &random_seed_bytes).unwrap();
4597 assert_eq!(route.paths[0].hops.len(), 2);
4599 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4600 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4601 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4602 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4603 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4604 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4606 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4607 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4608 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4609 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4610 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4611 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4613 last_hops[0].0[0].fees.base_msat = 1000;
4615 // Revert to via 6 as the fee on 8 goes up
4616 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4617 .with_route_hints(last_hops).unwrap();
4618 let route_params = RouteParameters::from_payment_params_and_value(
4619 payment_params.clone(), 100);
4620 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4621 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4622 assert_eq!(route.paths[0].hops.len(), 4);
4624 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4625 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4626 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4627 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4628 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4629 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4631 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4632 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4633 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4634 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4635 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4636 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4638 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4639 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4640 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4641 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 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[2].node_features.le_flags(), &id_to_feature_flags(6));
4645 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4647 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4648 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4649 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4650 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4651 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4652 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4654 // ...but still use 8 for larger payments as 6 has a variable feerate
4655 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4656 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4657 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4658 assert_eq!(route.paths[0].hops.len(), 5);
4660 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4661 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4662 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4663 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4664 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4665 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4667 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4668 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4669 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4670 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4671 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4672 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4674 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4675 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4676 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4677 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4678 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4679 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4681 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4682 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4683 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4684 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4685 // If we have a peer in the node map, we'll use their features here since we don't have
4686 // a way of figuring out their features from the invoice:
4687 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4688 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4690 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4691 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4692 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4693 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4694 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4695 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4698 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> {
4699 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4700 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4701 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4703 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4704 let last_hops = RouteHint(vec![RouteHintHop {
4705 src_node_id: middle_node_id,
4706 short_channel_id: 8,
4709 proportional_millionths: last_hop_fee_prop,
4711 cltv_expiry_delta: (8 << 4) | 1,
4712 htlc_minimum_msat: None,
4713 htlc_maximum_msat: last_hop_htlc_max,
4715 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4716 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4717 let scorer = ln_test_utils::TestScorer::new();
4718 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4719 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4720 let logger = ln_test_utils::TestLogger::new();
4721 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4722 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4723 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4724 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4725 &random_seed_bytes);
4730 fn unannounced_path_test() {
4731 // We should be able to send a payment to a destination without any help of a routing graph
4732 // if we have a channel with a common counterparty that appears in the first and last hop
4734 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4736 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4737 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4738 assert_eq!(route.paths[0].hops.len(), 2);
4740 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4741 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4742 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4743 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4744 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4745 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4747 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4748 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4749 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4750 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4751 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4752 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4756 fn overflow_unannounced_path_test_liquidity_underflow() {
4757 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4758 // the last-hop had a fee which overflowed a u64, we'd panic.
4759 // This was due to us adding the first-hop from us unconditionally, causing us to think
4760 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4761 // In this test, we previously hit a subtraction underflow due to having less available
4762 // liquidity at the last hop than 0.
4763 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());
4767 fn overflow_unannounced_path_test_feerate_overflow() {
4768 // This tests for the same case as above, except instead of hitting a subtraction
4769 // underflow, we hit a case where the fee charged at a hop overflowed.
4770 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());
4774 fn available_amount_while_routing_test() {
4775 // Tests whether we choose the correct available channel amount while routing.
4777 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4778 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4779 let scorer = ln_test_utils::TestScorer::new();
4780 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4781 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4782 let config = UserConfig::default();
4783 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4784 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4787 // We will use a simple single-path route from
4788 // our node to node2 via node0: channels {1, 3}.
4790 // First disable all other paths.
4791 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4792 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4793 short_channel_id: 2,
4796 cltv_expiry_delta: 0,
4797 htlc_minimum_msat: 0,
4798 htlc_maximum_msat: 100_000,
4800 fee_proportional_millionths: 0,
4801 excess_data: Vec::new()
4803 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4804 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4805 short_channel_id: 12,
4808 cltv_expiry_delta: 0,
4809 htlc_minimum_msat: 0,
4810 htlc_maximum_msat: 100_000,
4812 fee_proportional_millionths: 0,
4813 excess_data: Vec::new()
4816 // Make the first channel (#1) very permissive,
4817 // and we will be testing all limits on the second channel.
4818 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4819 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4820 short_channel_id: 1,
4823 cltv_expiry_delta: 0,
4824 htlc_minimum_msat: 0,
4825 htlc_maximum_msat: 1_000_000_000,
4827 fee_proportional_millionths: 0,
4828 excess_data: Vec::new()
4831 // First, let's see if routing works if we have absolutely no idea about the available amount.
4832 // In this case, it should be set to 250_000 sats.
4833 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4834 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4835 short_channel_id: 3,
4838 cltv_expiry_delta: 0,
4839 htlc_minimum_msat: 0,
4840 htlc_maximum_msat: 250_000_000,
4842 fee_proportional_millionths: 0,
4843 excess_data: Vec::new()
4847 // Attempt to route more than available results in a failure.
4848 let route_params = RouteParameters::from_payment_params_and_value(
4849 payment_params.clone(), 250_000_001);
4850 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4851 &our_id, &route_params, &network_graph.read_only(), None,
4852 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4853 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4854 } else { panic!(); }
4858 // Now, attempt to route an exact amount we have should be fine.
4859 let route_params = RouteParameters::from_payment_params_and_value(
4860 payment_params.clone(), 250_000_000);
4861 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4862 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4863 assert_eq!(route.paths.len(), 1);
4864 let path = route.paths.last().unwrap();
4865 assert_eq!(path.hops.len(), 2);
4866 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4867 assert_eq!(path.final_value_msat(), 250_000_000);
4870 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4871 // Disable channel #1 and use another first hop.
4872 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4873 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4874 short_channel_id: 1,
4877 cltv_expiry_delta: 0,
4878 htlc_minimum_msat: 0,
4879 htlc_maximum_msat: 1_000_000_000,
4881 fee_proportional_millionths: 0,
4882 excess_data: Vec::new()
4885 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4886 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4889 // Attempt to route more than available results in a failure.
4890 let route_params = RouteParameters::from_payment_params_and_value(
4891 payment_params.clone(), 200_000_001);
4892 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4893 &our_id, &route_params, &network_graph.read_only(),
4894 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4895 &Default::default(), &random_seed_bytes) {
4896 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4897 } else { panic!(); }
4901 // Now, attempt to route an exact amount we have should be fine.
4902 let route_params = RouteParameters::from_payment_params_and_value(
4903 payment_params.clone(), 200_000_000);
4904 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4905 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4906 &Default::default(), &random_seed_bytes).unwrap();
4907 assert_eq!(route.paths.len(), 1);
4908 let path = route.paths.last().unwrap();
4909 assert_eq!(path.hops.len(), 2);
4910 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4911 assert_eq!(path.final_value_msat(), 200_000_000);
4914 // Enable channel #1 back.
4915 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4916 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4917 short_channel_id: 1,
4920 cltv_expiry_delta: 0,
4921 htlc_minimum_msat: 0,
4922 htlc_maximum_msat: 1_000_000_000,
4924 fee_proportional_millionths: 0,
4925 excess_data: Vec::new()
4929 // Now let's see if routing works if we know only htlc_maximum_msat.
4930 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4931 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4932 short_channel_id: 3,
4935 cltv_expiry_delta: 0,
4936 htlc_minimum_msat: 0,
4937 htlc_maximum_msat: 15_000,
4939 fee_proportional_millionths: 0,
4940 excess_data: Vec::new()
4944 // Attempt to route more than available results in a failure.
4945 let route_params = RouteParameters::from_payment_params_and_value(
4946 payment_params.clone(), 15_001);
4947 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4948 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4949 &scorer, &Default::default(), &random_seed_bytes) {
4950 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4951 } else { panic!(); }
4955 // Now, attempt to route an exact amount we have should be fine.
4956 let route_params = RouteParameters::from_payment_params_and_value(
4957 payment_params.clone(), 15_000);
4958 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4959 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4960 assert_eq!(route.paths.len(), 1);
4961 let path = route.paths.last().unwrap();
4962 assert_eq!(path.hops.len(), 2);
4963 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4964 assert_eq!(path.final_value_msat(), 15_000);
4967 // Now let's see if routing works if we know only capacity from the UTXO.
4969 // We can't change UTXO capacity on the fly, so we'll disable
4970 // the existing channel and add another one with the capacity we need.
4971 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4972 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4973 short_channel_id: 3,
4976 cltv_expiry_delta: 0,
4977 htlc_minimum_msat: 0,
4978 htlc_maximum_msat: MAX_VALUE_MSAT,
4980 fee_proportional_millionths: 0,
4981 excess_data: Vec::new()
4984 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4985 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4986 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4987 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4988 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4990 *chain_monitor.utxo_ret.lock().unwrap() =
4991 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4992 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4994 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4995 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4996 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4997 short_channel_id: 333,
5000 cltv_expiry_delta: (3 << 4) | 1,
5001 htlc_minimum_msat: 0,
5002 htlc_maximum_msat: 15_000,
5004 fee_proportional_millionths: 0,
5005 excess_data: Vec::new()
5007 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5008 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5009 short_channel_id: 333,
5012 cltv_expiry_delta: (3 << 4) | 2,
5013 htlc_minimum_msat: 0,
5014 htlc_maximum_msat: 15_000,
5016 fee_proportional_millionths: 0,
5017 excess_data: Vec::new()
5021 // Attempt to route more than available results in a failure.
5022 let route_params = RouteParameters::from_payment_params_and_value(
5023 payment_params.clone(), 15_001);
5024 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5025 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5026 &scorer, &Default::default(), &random_seed_bytes) {
5027 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5028 } else { panic!(); }
5032 // Now, attempt to route an exact amount we have should be fine.
5033 let route_params = RouteParameters::from_payment_params_and_value(
5034 payment_params.clone(), 15_000);
5035 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5036 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5037 assert_eq!(route.paths.len(), 1);
5038 let path = route.paths.last().unwrap();
5039 assert_eq!(path.hops.len(), 2);
5040 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5041 assert_eq!(path.final_value_msat(), 15_000);
5044 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
5045 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5046 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5047 short_channel_id: 333,
5050 cltv_expiry_delta: 0,
5051 htlc_minimum_msat: 0,
5052 htlc_maximum_msat: 10_000,
5054 fee_proportional_millionths: 0,
5055 excess_data: Vec::new()
5059 // Attempt to route more than available results in a failure.
5060 let route_params = RouteParameters::from_payment_params_and_value(
5061 payment_params.clone(), 10_001);
5062 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5063 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5064 &scorer, &Default::default(), &random_seed_bytes) {
5065 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5066 } else { panic!(); }
5070 // Now, attempt to route an exact amount we have should be fine.
5071 let route_params = RouteParameters::from_payment_params_and_value(
5072 payment_params.clone(), 10_000);
5073 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5074 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5075 assert_eq!(route.paths.len(), 1);
5076 let path = route.paths.last().unwrap();
5077 assert_eq!(path.hops.len(), 2);
5078 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5079 assert_eq!(path.final_value_msat(), 10_000);
5084 fn available_liquidity_last_hop_test() {
5085 // Check that available liquidity properly limits the path even when only
5086 // one of the latter hops is limited.
5087 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5088 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5089 let scorer = ln_test_utils::TestScorer::new();
5090 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5091 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5092 let config = UserConfig::default();
5093 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5094 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5097 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5098 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
5099 // Total capacity: 50 sats.
5101 // Disable other potential paths.
5102 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5103 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5104 short_channel_id: 2,
5107 cltv_expiry_delta: 0,
5108 htlc_minimum_msat: 0,
5109 htlc_maximum_msat: 100_000,
5111 fee_proportional_millionths: 0,
5112 excess_data: Vec::new()
5114 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5115 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5116 short_channel_id: 7,
5119 cltv_expiry_delta: 0,
5120 htlc_minimum_msat: 0,
5121 htlc_maximum_msat: 100_000,
5123 fee_proportional_millionths: 0,
5124 excess_data: Vec::new()
5129 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5130 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5131 short_channel_id: 12,
5134 cltv_expiry_delta: 0,
5135 htlc_minimum_msat: 0,
5136 htlc_maximum_msat: 100_000,
5138 fee_proportional_millionths: 0,
5139 excess_data: Vec::new()
5141 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5142 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5143 short_channel_id: 13,
5146 cltv_expiry_delta: 0,
5147 htlc_minimum_msat: 0,
5148 htlc_maximum_msat: 100_000,
5150 fee_proportional_millionths: 0,
5151 excess_data: Vec::new()
5154 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5155 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5156 short_channel_id: 6,
5159 cltv_expiry_delta: 0,
5160 htlc_minimum_msat: 0,
5161 htlc_maximum_msat: 50_000,
5163 fee_proportional_millionths: 0,
5164 excess_data: Vec::new()
5166 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5167 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5168 short_channel_id: 11,
5171 cltv_expiry_delta: 0,
5172 htlc_minimum_msat: 0,
5173 htlc_maximum_msat: 100_000,
5175 fee_proportional_millionths: 0,
5176 excess_data: Vec::new()
5179 // Attempt to route more than available results in a failure.
5180 let route_params = RouteParameters::from_payment_params_and_value(
5181 payment_params.clone(), 60_000);
5182 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5183 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5184 &scorer, &Default::default(), &random_seed_bytes) {
5185 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5186 } else { panic!(); }
5190 // Now, attempt to route 49 sats (just a bit below the capacity).
5191 let route_params = RouteParameters::from_payment_params_and_value(
5192 payment_params.clone(), 49_000);
5193 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5194 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5195 assert_eq!(route.paths.len(), 1);
5196 let mut total_amount_paid_msat = 0;
5197 for path in &route.paths {
5198 assert_eq!(path.hops.len(), 4);
5199 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5200 total_amount_paid_msat += path.final_value_msat();
5202 assert_eq!(total_amount_paid_msat, 49_000);
5206 // Attempt to route an exact amount is also fine
5207 let route_params = RouteParameters::from_payment_params_and_value(
5208 payment_params, 50_000);
5209 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5210 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5211 assert_eq!(route.paths.len(), 1);
5212 let mut total_amount_paid_msat = 0;
5213 for path in &route.paths {
5214 assert_eq!(path.hops.len(), 4);
5215 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5216 total_amount_paid_msat += path.final_value_msat();
5218 assert_eq!(total_amount_paid_msat, 50_000);
5223 fn ignore_fee_first_hop_test() {
5224 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5225 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5226 let scorer = ln_test_utils::TestScorer::new();
5227 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5228 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5229 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5231 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5232 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5233 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5234 short_channel_id: 1,
5237 cltv_expiry_delta: 0,
5238 htlc_minimum_msat: 0,
5239 htlc_maximum_msat: 100_000,
5240 fee_base_msat: 1_000_000,
5241 fee_proportional_millionths: 0,
5242 excess_data: Vec::new()
5244 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5245 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5246 short_channel_id: 3,
5249 cltv_expiry_delta: 0,
5250 htlc_minimum_msat: 0,
5251 htlc_maximum_msat: 50_000,
5253 fee_proportional_millionths: 0,
5254 excess_data: Vec::new()
5258 let route_params = RouteParameters::from_payment_params_and_value(
5259 payment_params, 50_000);
5260 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5261 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5262 assert_eq!(route.paths.len(), 1);
5263 let mut total_amount_paid_msat = 0;
5264 for path in &route.paths {
5265 assert_eq!(path.hops.len(), 2);
5266 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5267 total_amount_paid_msat += path.final_value_msat();
5269 assert_eq!(total_amount_paid_msat, 50_000);
5274 fn simple_mpp_route_test() {
5275 let (secp_ctx, _, _, _, _) = build_graph();
5276 let (_, _, _, nodes) = get_nodes(&secp_ctx);
5277 let config = UserConfig::default();
5278 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5279 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5281 do_simple_mpp_route_test(clear_payment_params);
5283 // MPP to a 1-hop blinded path for nodes[2]
5284 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
5285 let blinded_path = BlindedPath {
5286 introduction_node_id: nodes[2],
5287 blinding_point: ln_test_utils::pubkey(42),
5288 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
5290 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
5292 fee_proportional_millionths: 0,
5293 htlc_minimum_msat: 0,
5294 htlc_maximum_msat: 0,
5295 cltv_expiry_delta: 0,
5296 features: BlindedHopFeatures::empty(),
5298 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
5299 .with_bolt12_features(bolt12_features.clone()).unwrap();
5300 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
5302 // MPP to 3 2-hop blinded paths
5303 let mut blinded_path_node_0 = blinded_path.clone();
5304 blinded_path_node_0.introduction_node_id = nodes[0];
5305 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
5306 let mut node_0_payinfo = blinded_payinfo.clone();
5307 node_0_payinfo.htlc_maximum_msat = 50_000;
5309 let mut blinded_path_node_7 = blinded_path_node_0.clone();
5310 blinded_path_node_7.introduction_node_id = nodes[7];
5311 let mut node_7_payinfo = blinded_payinfo.clone();
5312 node_7_payinfo.htlc_maximum_msat = 60_000;
5314 let mut blinded_path_node_1 = blinded_path_node_0.clone();
5315 blinded_path_node_1.introduction_node_id = nodes[1];
5316 let mut node_1_payinfo = blinded_payinfo.clone();
5317 node_1_payinfo.htlc_maximum_msat = 180_000;
5319 let two_hop_blinded_payment_params = PaymentParameters::blinded(
5321 (node_0_payinfo, blinded_path_node_0),
5322 (node_7_payinfo, blinded_path_node_7),
5323 (node_1_payinfo, blinded_path_node_1)
5325 .with_bolt12_features(bolt12_features).unwrap();
5326 do_simple_mpp_route_test(two_hop_blinded_payment_params);
5330 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
5331 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5332 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5333 let scorer = ln_test_utils::TestScorer::new();
5334 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5335 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5337 // We need a route consisting of 3 paths:
5338 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5339 // To achieve this, the amount being transferred should be around
5340 // the total capacity of these 3 paths.
5342 // First, we set limits on these (previously unlimited) channels.
5343 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
5345 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5346 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5347 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5348 short_channel_id: 1,
5351 cltv_expiry_delta: 0,
5352 htlc_minimum_msat: 0,
5353 htlc_maximum_msat: 100_000,
5355 fee_proportional_millionths: 0,
5356 excess_data: Vec::new()
5358 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5359 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5360 short_channel_id: 3,
5363 cltv_expiry_delta: 0,
5364 htlc_minimum_msat: 0,
5365 htlc_maximum_msat: 50_000,
5367 fee_proportional_millionths: 0,
5368 excess_data: Vec::new()
5371 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
5372 // (total limit 60).
5373 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5374 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5375 short_channel_id: 12,
5378 cltv_expiry_delta: 0,
5379 htlc_minimum_msat: 0,
5380 htlc_maximum_msat: 60_000,
5382 fee_proportional_millionths: 0,
5383 excess_data: Vec::new()
5385 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5386 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5387 short_channel_id: 13,
5390 cltv_expiry_delta: 0,
5391 htlc_minimum_msat: 0,
5392 htlc_maximum_msat: 60_000,
5394 fee_proportional_millionths: 0,
5395 excess_data: Vec::new()
5398 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5399 // (total capacity 180 sats).
5400 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5401 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5402 short_channel_id: 2,
5405 cltv_expiry_delta: 0,
5406 htlc_minimum_msat: 0,
5407 htlc_maximum_msat: 200_000,
5409 fee_proportional_millionths: 0,
5410 excess_data: Vec::new()
5412 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5413 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5414 short_channel_id: 4,
5417 cltv_expiry_delta: 0,
5418 htlc_minimum_msat: 0,
5419 htlc_maximum_msat: 180_000,
5421 fee_proportional_millionths: 0,
5422 excess_data: Vec::new()
5426 // Attempt to route more than available results in a failure.
5427 let route_params = RouteParameters::from_payment_params_and_value(
5428 payment_params.clone(), 300_000);
5429 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5430 &our_id, &route_params, &network_graph.read_only(), None,
5431 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5432 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5433 } else { panic!(); }
5437 // Attempt to route while setting max_path_count to 0 results in a failure.
5438 let zero_payment_params = payment_params.clone().with_max_path_count(0);
5439 let route_params = RouteParameters::from_payment_params_and_value(
5440 zero_payment_params, 100);
5441 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5442 &our_id, &route_params, &network_graph.read_only(), None,
5443 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5444 assert_eq!(err, "Can't find a route with no paths allowed.");
5445 } else { panic!(); }
5449 // Attempt to route while setting max_path_count to 3 results in a failure.
5450 // This is the case because the minimal_value_contribution_msat would require each path
5451 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5452 let fail_payment_params = payment_params.clone().with_max_path_count(3);
5453 let route_params = RouteParameters::from_payment_params_and_value(
5454 fail_payment_params, 250_000);
5455 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5456 &our_id, &route_params, &network_graph.read_only(), None,
5457 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5458 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5459 } else { panic!(); }
5463 // Now, attempt to route 250 sats (just a bit below the capacity).
5464 // Our algorithm should provide us with these 3 paths.
5465 let route_params = RouteParameters::from_payment_params_and_value(
5466 payment_params.clone(), 250_000);
5467 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5468 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5469 assert_eq!(route.paths.len(), 3);
5470 let mut total_amount_paid_msat = 0;
5471 for path in &route.paths {
5472 if let Some(bt) = &path.blinded_tail {
5473 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5475 assert_eq!(path.hops.len(), 2);
5476 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5478 total_amount_paid_msat += path.final_value_msat();
5480 assert_eq!(total_amount_paid_msat, 250_000);
5484 // Attempt to route an exact amount is also fine
5485 let route_params = RouteParameters::from_payment_params_and_value(
5486 payment_params.clone(), 290_000);
5487 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5488 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5489 assert_eq!(route.paths.len(), 3);
5490 let mut total_amount_paid_msat = 0;
5491 for path in &route.paths {
5492 if payment_params.payee.blinded_route_hints().len() != 0 {
5493 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5494 if let Some(bt) = &path.blinded_tail {
5495 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5496 if bt.hops.len() > 1 {
5497 assert_eq!(path.hops.last().unwrap().pubkey,
5498 payment_params.payee.blinded_route_hints().iter()
5499 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5500 .map(|(_, p)| p.introduction_node_id).unwrap());
5502 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5505 assert_eq!(path.hops.len(), 2);
5506 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5508 total_amount_paid_msat += path.final_value_msat();
5510 assert_eq!(total_amount_paid_msat, 290_000);
5515 fn long_mpp_route_test() {
5516 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5517 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5518 let scorer = ln_test_utils::TestScorer::new();
5519 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5520 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5521 let config = UserConfig::default();
5522 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5523 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5526 // We need a route consisting of 3 paths:
5527 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5528 // Note that these paths overlap (channels 5, 12, 13).
5529 // We will route 300 sats.
5530 // Each path will have 100 sats capacity, those channels which
5531 // are used twice will have 200 sats capacity.
5533 // Disable other potential paths.
5534 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5535 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5536 short_channel_id: 2,
5539 cltv_expiry_delta: 0,
5540 htlc_minimum_msat: 0,
5541 htlc_maximum_msat: 100_000,
5543 fee_proportional_millionths: 0,
5544 excess_data: Vec::new()
5546 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5547 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5548 short_channel_id: 7,
5551 cltv_expiry_delta: 0,
5552 htlc_minimum_msat: 0,
5553 htlc_maximum_msat: 100_000,
5555 fee_proportional_millionths: 0,
5556 excess_data: Vec::new()
5559 // Path via {node0, node2} is channels {1, 3, 5}.
5560 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5561 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5562 short_channel_id: 1,
5565 cltv_expiry_delta: 0,
5566 htlc_minimum_msat: 0,
5567 htlc_maximum_msat: 100_000,
5569 fee_proportional_millionths: 0,
5570 excess_data: Vec::new()
5572 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5573 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5574 short_channel_id: 3,
5577 cltv_expiry_delta: 0,
5578 htlc_minimum_msat: 0,
5579 htlc_maximum_msat: 100_000,
5581 fee_proportional_millionths: 0,
5582 excess_data: Vec::new()
5585 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5586 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5587 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5588 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5589 short_channel_id: 5,
5592 cltv_expiry_delta: 0,
5593 htlc_minimum_msat: 0,
5594 htlc_maximum_msat: 200_000,
5596 fee_proportional_millionths: 0,
5597 excess_data: Vec::new()
5600 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5601 // Add 100 sats to the capacities of {12, 13}, because these channels
5602 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5603 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5604 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5605 short_channel_id: 12,
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,
5620 cltv_expiry_delta: 0,
5621 htlc_minimum_msat: 0,
5622 htlc_maximum_msat: 200_000,
5624 fee_proportional_millionths: 0,
5625 excess_data: Vec::new()
5628 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5629 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5630 short_channel_id: 6,
5633 cltv_expiry_delta: 0,
5634 htlc_minimum_msat: 0,
5635 htlc_maximum_msat: 100_000,
5637 fee_proportional_millionths: 0,
5638 excess_data: Vec::new()
5640 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5641 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5642 short_channel_id: 11,
5645 cltv_expiry_delta: 0,
5646 htlc_minimum_msat: 0,
5647 htlc_maximum_msat: 100_000,
5649 fee_proportional_millionths: 0,
5650 excess_data: Vec::new()
5653 // Path via {node7, node2} is channels {12, 13, 5}.
5654 // We already limited them to 200 sats (they are used twice for 100 sats).
5655 // Nothing to do here.
5658 // Attempt to route more than available results in a failure.
5659 let route_params = RouteParameters::from_payment_params_and_value(
5660 payment_params.clone(), 350_000);
5661 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5662 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5663 &scorer, &Default::default(), &random_seed_bytes) {
5664 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5665 } else { panic!(); }
5669 // Now, attempt to route 300 sats (exact amount we can route).
5670 // Our algorithm should provide us with these 3 paths, 100 sats each.
5671 let route_params = RouteParameters::from_payment_params_and_value(
5672 payment_params, 300_000);
5673 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5674 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5675 assert_eq!(route.paths.len(), 3);
5677 let mut total_amount_paid_msat = 0;
5678 for path in &route.paths {
5679 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5680 total_amount_paid_msat += path.final_value_msat();
5682 assert_eq!(total_amount_paid_msat, 300_000);
5688 fn mpp_cheaper_route_test() {
5689 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5690 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5691 let scorer = ln_test_utils::TestScorer::new();
5692 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5693 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5694 let config = UserConfig::default();
5695 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5696 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5699 // This test checks that if we have two cheaper paths and one more expensive path,
5700 // so that liquidity-wise any 2 of 3 combination is sufficient,
5701 // two cheaper paths will be taken.
5702 // These paths have equal available liquidity.
5704 // We need a combination of 3 paths:
5705 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5706 // Note that these paths overlap (channels 5, 12, 13).
5707 // Each path will have 100 sats capacity, those channels which
5708 // are used twice will have 200 sats capacity.
5710 // Disable other potential paths.
5711 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5712 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5713 short_channel_id: 2,
5716 cltv_expiry_delta: 0,
5717 htlc_minimum_msat: 0,
5718 htlc_maximum_msat: 100_000,
5720 fee_proportional_millionths: 0,
5721 excess_data: Vec::new()
5723 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5724 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5725 short_channel_id: 7,
5728 cltv_expiry_delta: 0,
5729 htlc_minimum_msat: 0,
5730 htlc_maximum_msat: 100_000,
5732 fee_proportional_millionths: 0,
5733 excess_data: Vec::new()
5736 // Path via {node0, node2} is channels {1, 3, 5}.
5737 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5738 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5739 short_channel_id: 1,
5742 cltv_expiry_delta: 0,
5743 htlc_minimum_msat: 0,
5744 htlc_maximum_msat: 100_000,
5746 fee_proportional_millionths: 0,
5747 excess_data: Vec::new()
5749 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5750 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5751 short_channel_id: 3,
5754 cltv_expiry_delta: 0,
5755 htlc_minimum_msat: 0,
5756 htlc_maximum_msat: 100_000,
5758 fee_proportional_millionths: 0,
5759 excess_data: Vec::new()
5762 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5763 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5764 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5765 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5766 short_channel_id: 5,
5769 cltv_expiry_delta: 0,
5770 htlc_minimum_msat: 0,
5771 htlc_maximum_msat: 200_000,
5773 fee_proportional_millionths: 0,
5774 excess_data: Vec::new()
5777 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5778 // Add 100 sats to the capacities of {12, 13}, because these channels
5779 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5780 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5781 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5782 short_channel_id: 12,
5785 cltv_expiry_delta: 0,
5786 htlc_minimum_msat: 0,
5787 htlc_maximum_msat: 200_000,
5789 fee_proportional_millionths: 0,
5790 excess_data: Vec::new()
5792 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5793 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5794 short_channel_id: 13,
5797 cltv_expiry_delta: 0,
5798 htlc_minimum_msat: 0,
5799 htlc_maximum_msat: 200_000,
5801 fee_proportional_millionths: 0,
5802 excess_data: Vec::new()
5805 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5806 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5807 short_channel_id: 6,
5810 cltv_expiry_delta: 0,
5811 htlc_minimum_msat: 0,
5812 htlc_maximum_msat: 100_000,
5813 fee_base_msat: 1_000,
5814 fee_proportional_millionths: 0,
5815 excess_data: Vec::new()
5817 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5818 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5819 short_channel_id: 11,
5822 cltv_expiry_delta: 0,
5823 htlc_minimum_msat: 0,
5824 htlc_maximum_msat: 100_000,
5826 fee_proportional_millionths: 0,
5827 excess_data: Vec::new()
5830 // Path via {node7, node2} is channels {12, 13, 5}.
5831 // We already limited them to 200 sats (they are used twice for 100 sats).
5832 // Nothing to do here.
5835 // Now, attempt to route 180 sats.
5836 // Our algorithm should provide us with these 2 paths.
5837 let route_params = RouteParameters::from_payment_params_and_value(
5838 payment_params, 180_000);
5839 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5840 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5841 assert_eq!(route.paths.len(), 2);
5843 let mut total_value_transferred_msat = 0;
5844 let mut total_paid_msat = 0;
5845 for path in &route.paths {
5846 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5847 total_value_transferred_msat += path.final_value_msat();
5848 for hop in &path.hops {
5849 total_paid_msat += hop.fee_msat;
5852 // If we paid fee, this would be higher.
5853 assert_eq!(total_value_transferred_msat, 180_000);
5854 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5855 assert_eq!(total_fees_paid, 0);
5860 fn fees_on_mpp_route_test() {
5861 // This test makes sure that MPP algorithm properly takes into account
5862 // fees charged on the channels, by making the fees impactful:
5863 // if the fee is not properly accounted for, the behavior is different.
5864 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5865 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5866 let scorer = ln_test_utils::TestScorer::new();
5867 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5868 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5869 let config = UserConfig::default();
5870 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5871 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5874 // We need a route consisting of 2 paths:
5875 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5876 // We will route 200 sats, Each path will have 100 sats capacity.
5878 // This test is not particularly stable: e.g.,
5879 // there's a way to route via {node0, node2, node4}.
5880 // It works while pathfinding is deterministic, but can be broken otherwise.
5881 // It's fine to ignore this concern for now.
5883 // Disable other potential paths.
5884 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5885 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5886 short_channel_id: 2,
5889 cltv_expiry_delta: 0,
5890 htlc_minimum_msat: 0,
5891 htlc_maximum_msat: 100_000,
5893 fee_proportional_millionths: 0,
5894 excess_data: Vec::new()
5897 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5898 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5899 short_channel_id: 7,
5902 cltv_expiry_delta: 0,
5903 htlc_minimum_msat: 0,
5904 htlc_maximum_msat: 100_000,
5906 fee_proportional_millionths: 0,
5907 excess_data: Vec::new()
5910 // Path via {node0, node2} is channels {1, 3, 5}.
5911 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5912 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5913 short_channel_id: 1,
5916 cltv_expiry_delta: 0,
5917 htlc_minimum_msat: 0,
5918 htlc_maximum_msat: 100_000,
5920 fee_proportional_millionths: 0,
5921 excess_data: Vec::new()
5923 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5924 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5925 short_channel_id: 3,
5928 cltv_expiry_delta: 0,
5929 htlc_minimum_msat: 0,
5930 htlc_maximum_msat: 100_000,
5932 fee_proportional_millionths: 0,
5933 excess_data: Vec::new()
5936 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5937 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5938 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5939 short_channel_id: 5,
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()
5950 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5951 // All channels should be 100 sats capacity. But for the fee experiment,
5952 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5953 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5954 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5955 // so no matter how large are other channels,
5956 // the whole path will be limited by 100 sats with just these 2 conditions:
5957 // - channel 12 capacity is 250 sats
5958 // - fee for channel 6 is 150 sats
5959 // Let's test this by enforcing these 2 conditions and removing other limits.
5960 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5961 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5962 short_channel_id: 12,
5965 cltv_expiry_delta: 0,
5966 htlc_minimum_msat: 0,
5967 htlc_maximum_msat: 250_000,
5969 fee_proportional_millionths: 0,
5970 excess_data: Vec::new()
5972 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5973 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5974 short_channel_id: 13,
5977 cltv_expiry_delta: 0,
5978 htlc_minimum_msat: 0,
5979 htlc_maximum_msat: MAX_VALUE_MSAT,
5981 fee_proportional_millionths: 0,
5982 excess_data: Vec::new()
5985 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5986 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5987 short_channel_id: 6,
5990 cltv_expiry_delta: 0,
5991 htlc_minimum_msat: 0,
5992 htlc_maximum_msat: MAX_VALUE_MSAT,
5993 fee_base_msat: 150_000,
5994 fee_proportional_millionths: 0,
5995 excess_data: Vec::new()
5997 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5998 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5999 short_channel_id: 11,
6002 cltv_expiry_delta: 0,
6003 htlc_minimum_msat: 0,
6004 htlc_maximum_msat: MAX_VALUE_MSAT,
6006 fee_proportional_millionths: 0,
6007 excess_data: Vec::new()
6011 // Attempt to route more than available results in a failure.
6012 let route_params = RouteParameters::from_payment_params_and_value(
6013 payment_params.clone(), 210_000);
6014 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6015 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6016 &scorer, &Default::default(), &random_seed_bytes) {
6017 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6018 } else { panic!(); }
6022 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
6023 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
6024 max_total_routing_fee_msat: Some(149_999) };
6025 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6026 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6027 &scorer, &Default::default(), &random_seed_bytes) {
6028 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6029 } else { panic!(); }
6033 // Now, attempt to route 200 sats (exact amount we can route).
6034 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
6035 max_total_routing_fee_msat: Some(150_000) };
6036 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6037 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6038 assert_eq!(route.paths.len(), 2);
6040 let mut total_amount_paid_msat = 0;
6041 for path in &route.paths {
6042 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
6043 total_amount_paid_msat += path.final_value_msat();
6045 assert_eq!(total_amount_paid_msat, 200_000);
6046 assert_eq!(route.get_total_fees(), 150_000);
6051 fn mpp_with_last_hops() {
6052 // Previously, if we tried to send an MPP payment to a destination which was only reachable
6053 // via a single last-hop route hint, we'd fail to route if we first collected routes
6054 // totaling close but not quite enough to fund the full payment.
6056 // This was because we considered last-hop hints to have exactly the sought payment amount
6057 // instead of the amount we were trying to collect, needlessly limiting our path searching
6058 // at the very first hop.
6060 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
6061 // criterion to cause us to refuse all routes at the last hop hint which would be considered
6062 // to only have the remaining to-collect amount in available liquidity.
6064 // This bug appeared in production in some specific channel configurations.
6065 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6066 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6067 let scorer = ln_test_utils::TestScorer::new();
6068 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6069 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6070 let config = UserConfig::default();
6071 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
6072 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
6073 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
6074 src_node_id: nodes[2],
6075 short_channel_id: 42,
6076 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
6077 cltv_expiry_delta: 42,
6078 htlc_minimum_msat: None,
6079 htlc_maximum_msat: None,
6080 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
6082 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
6083 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
6084 // would first use the no-fee route and then fail to find a path along the second route as
6085 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
6086 // under 5% of our payment amount.
6087 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6088 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6089 short_channel_id: 1,
6092 cltv_expiry_delta: (5 << 4) | 5,
6093 htlc_minimum_msat: 0,
6094 htlc_maximum_msat: 99_000,
6095 fee_base_msat: u32::max_value(),
6096 fee_proportional_millionths: u32::max_value(),
6097 excess_data: Vec::new()
6099 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6100 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6101 short_channel_id: 2,
6104 cltv_expiry_delta: (5 << 4) | 3,
6105 htlc_minimum_msat: 0,
6106 htlc_maximum_msat: 99_000,
6107 fee_base_msat: u32::max_value(),
6108 fee_proportional_millionths: u32::max_value(),
6109 excess_data: Vec::new()
6111 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6112 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6113 short_channel_id: 4,
6116 cltv_expiry_delta: (4 << 4) | 1,
6117 htlc_minimum_msat: 0,
6118 htlc_maximum_msat: MAX_VALUE_MSAT,
6120 fee_proportional_millionths: 0,
6121 excess_data: Vec::new()
6123 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6124 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6125 short_channel_id: 13,
6127 flags: 0|2, // Channel disabled
6128 cltv_expiry_delta: (13 << 4) | 1,
6129 htlc_minimum_msat: 0,
6130 htlc_maximum_msat: MAX_VALUE_MSAT,
6132 fee_proportional_millionths: 2000000,
6133 excess_data: Vec::new()
6136 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
6138 let route_params = RouteParameters::from_payment_params_and_value(
6139 payment_params, 100_000);
6140 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6141 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6142 assert_eq!(route.paths.len(), 2);
6143 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
6144 // Paths are manually ordered ordered by SCID, so:
6145 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
6146 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
6147 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
6148 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
6149 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
6150 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
6151 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
6152 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
6153 assert_eq!(route.get_total_fees(), 1);
6154 assert_eq!(route.get_total_amount(), 100_000);
6158 fn drop_lowest_channel_mpp_route_test() {
6159 // This test checks that low-capacity channel is dropped when after
6160 // path finding we realize that we found more capacity than we need.
6161 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6162 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6163 let scorer = ln_test_utils::TestScorer::new();
6164 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6165 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6166 let config = UserConfig::default();
6167 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6168 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6170 .with_max_channel_saturation_power_of_half(0);
6172 // We need a route consisting of 3 paths:
6173 // From our node to node2 via node0, node7, node1 (three paths one hop each).
6175 // The first and the second paths should be sufficient, but the third should be
6176 // cheaper, so that we select it but drop later.
6178 // First, we set limits on these (previously unlimited) channels.
6179 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
6181 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
6182 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6183 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6184 short_channel_id: 1,
6187 cltv_expiry_delta: 0,
6188 htlc_minimum_msat: 0,
6189 htlc_maximum_msat: 100_000,
6191 fee_proportional_millionths: 0,
6192 excess_data: Vec::new()
6194 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6195 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6196 short_channel_id: 3,
6199 cltv_expiry_delta: 0,
6200 htlc_minimum_msat: 0,
6201 htlc_maximum_msat: 50_000,
6203 fee_proportional_millionths: 0,
6204 excess_data: Vec::new()
6207 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
6208 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6209 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6210 short_channel_id: 12,
6213 cltv_expiry_delta: 0,
6214 htlc_minimum_msat: 0,
6215 htlc_maximum_msat: 60_000,
6217 fee_proportional_millionths: 0,
6218 excess_data: Vec::new()
6220 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6221 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6222 short_channel_id: 13,
6225 cltv_expiry_delta: 0,
6226 htlc_minimum_msat: 0,
6227 htlc_maximum_msat: 60_000,
6229 fee_proportional_millionths: 0,
6230 excess_data: Vec::new()
6233 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
6234 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6235 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6236 short_channel_id: 2,
6239 cltv_expiry_delta: 0,
6240 htlc_minimum_msat: 0,
6241 htlc_maximum_msat: 20_000,
6243 fee_proportional_millionths: 0,
6244 excess_data: Vec::new()
6246 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6247 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6248 short_channel_id: 4,
6251 cltv_expiry_delta: 0,
6252 htlc_minimum_msat: 0,
6253 htlc_maximum_msat: 20_000,
6255 fee_proportional_millionths: 0,
6256 excess_data: Vec::new()
6260 // Attempt to route more than available results in a failure.
6261 let route_params = RouteParameters::from_payment_params_and_value(
6262 payment_params.clone(), 150_000);
6263 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6264 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6265 &scorer, &Default::default(), &random_seed_bytes) {
6266 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6267 } else { panic!(); }
6271 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
6272 // Our algorithm should provide us with these 3 paths.
6273 let route_params = RouteParameters::from_payment_params_and_value(
6274 payment_params.clone(), 125_000);
6275 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6276 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6277 assert_eq!(route.paths.len(), 3);
6278 let mut total_amount_paid_msat = 0;
6279 for path in &route.paths {
6280 assert_eq!(path.hops.len(), 2);
6281 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6282 total_amount_paid_msat += path.final_value_msat();
6284 assert_eq!(total_amount_paid_msat, 125_000);
6288 // Attempt to route without the last small cheap channel
6289 let route_params = RouteParameters::from_payment_params_and_value(
6290 payment_params, 90_000);
6291 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6292 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6293 assert_eq!(route.paths.len(), 2);
6294 let mut total_amount_paid_msat = 0;
6295 for path in &route.paths {
6296 assert_eq!(path.hops.len(), 2);
6297 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6298 total_amount_paid_msat += path.final_value_msat();
6300 assert_eq!(total_amount_paid_msat, 90_000);
6305 fn min_criteria_consistency() {
6306 // Test that we don't use an inconsistent metric between updating and walking nodes during
6307 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
6308 // was updated with a different criterion from the heap sorting, resulting in loops in
6309 // calculated paths. We test for that specific case here.
6311 // We construct a network that looks like this:
6313 // node2 -1(3)2- node3
6317 // node1 -1(5)2- node4 -1(1)2- node6
6323 // We create a loop on the side of our real path - our destination is node 6, with a
6324 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
6325 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
6326 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
6327 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
6328 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
6329 // "previous hop" being set to node 3, creating a loop in the path.
6330 let secp_ctx = Secp256k1::new();
6331 let logger = Arc::new(ln_test_utils::TestLogger::new());
6332 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6333 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
6334 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6335 let scorer = ln_test_utils::TestScorer::new();
6336 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6337 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6338 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
6340 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
6341 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6342 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6343 short_channel_id: 6,
6346 cltv_expiry_delta: (6 << 4) | 0,
6347 htlc_minimum_msat: 0,
6348 htlc_maximum_msat: MAX_VALUE_MSAT,
6350 fee_proportional_millionths: 0,
6351 excess_data: Vec::new()
6353 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
6355 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6356 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6357 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6358 short_channel_id: 5,
6361 cltv_expiry_delta: (5 << 4) | 0,
6362 htlc_minimum_msat: 0,
6363 htlc_maximum_msat: MAX_VALUE_MSAT,
6365 fee_proportional_millionths: 0,
6366 excess_data: Vec::new()
6368 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
6370 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
6371 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6372 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6373 short_channel_id: 4,
6376 cltv_expiry_delta: (4 << 4) | 0,
6377 htlc_minimum_msat: 0,
6378 htlc_maximum_msat: MAX_VALUE_MSAT,
6380 fee_proportional_millionths: 0,
6381 excess_data: Vec::new()
6383 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6385 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6386 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
6387 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6388 short_channel_id: 3,
6391 cltv_expiry_delta: (3 << 4) | 0,
6392 htlc_minimum_msat: 0,
6393 htlc_maximum_msat: MAX_VALUE_MSAT,
6395 fee_proportional_millionths: 0,
6396 excess_data: Vec::new()
6398 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6400 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6401 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
6402 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6403 short_channel_id: 2,
6406 cltv_expiry_delta: (2 << 4) | 0,
6407 htlc_minimum_msat: 0,
6408 htlc_maximum_msat: MAX_VALUE_MSAT,
6410 fee_proportional_millionths: 0,
6411 excess_data: Vec::new()
6414 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6415 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6416 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6417 short_channel_id: 1,
6420 cltv_expiry_delta: (1 << 4) | 0,
6421 htlc_minimum_msat: 100,
6422 htlc_maximum_msat: MAX_VALUE_MSAT,
6424 fee_proportional_millionths: 0,
6425 excess_data: Vec::new()
6427 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6430 // Now ensure the route flows simply over nodes 1 and 4 to 6.
6431 let route_params = RouteParameters::from_payment_params_and_value(
6432 payment_params, 10_000);
6433 let route = get_route(&our_id, &route_params, &network.read_only(), None,
6434 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6435 assert_eq!(route.paths.len(), 1);
6436 assert_eq!(route.paths[0].hops.len(), 3);
6438 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6439 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6440 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6441 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6442 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6443 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6445 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6446 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6447 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6448 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6449 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6450 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6452 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6453 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6454 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6455 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6456 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6457 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6463 fn exact_fee_liquidity_limit() {
6464 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6465 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6466 // we calculated fees on a higher value, resulting in us ignoring such paths.
6467 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6468 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6469 let scorer = ln_test_utils::TestScorer::new();
6470 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6471 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6472 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6474 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6476 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6477 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6478 short_channel_id: 2,
6481 cltv_expiry_delta: 0,
6482 htlc_minimum_msat: 0,
6483 htlc_maximum_msat: 85_000,
6485 fee_proportional_millionths: 0,
6486 excess_data: Vec::new()
6489 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6490 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6491 short_channel_id: 12,
6494 cltv_expiry_delta: (4 << 4) | 1,
6495 htlc_minimum_msat: 0,
6496 htlc_maximum_msat: 270_000,
6498 fee_proportional_millionths: 1000000,
6499 excess_data: Vec::new()
6503 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6504 // 200% fee charged channel 13 in the 1-to-2 direction.
6505 let mut route_params = RouteParameters::from_payment_params_and_value(
6506 payment_params, 90_000);
6507 route_params.max_total_routing_fee_msat = Some(90_000*2);
6508 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6509 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6510 assert_eq!(route.paths.len(), 1);
6511 assert_eq!(route.paths[0].hops.len(), 2);
6513 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6514 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6515 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6516 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6517 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6518 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6520 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6521 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6522 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6523 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6524 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6525 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6530 fn htlc_max_reduction_below_min() {
6531 // Test that if, while walking the graph, we reduce the value being sent to meet an
6532 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6533 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6534 // resulting in us thinking there is no possible path, even if other paths exist.
6535 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6536 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6537 let scorer = ln_test_utils::TestScorer::new();
6538 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6539 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6540 let config = UserConfig::default();
6541 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6542 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6545 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6546 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6547 // then try to send 90_000.
6548 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6549 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6550 short_channel_id: 2,
6553 cltv_expiry_delta: 0,
6554 htlc_minimum_msat: 0,
6555 htlc_maximum_msat: 80_000,
6557 fee_proportional_millionths: 0,
6558 excess_data: Vec::new()
6560 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6561 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6562 short_channel_id: 4,
6565 cltv_expiry_delta: (4 << 4) | 1,
6566 htlc_minimum_msat: 90_000,
6567 htlc_maximum_msat: MAX_VALUE_MSAT,
6569 fee_proportional_millionths: 0,
6570 excess_data: Vec::new()
6574 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6575 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6576 // expensive) channels 12-13 path.
6577 let mut route_params = RouteParameters::from_payment_params_and_value(
6578 payment_params, 90_000);
6579 route_params.max_total_routing_fee_msat = Some(90_000*2);
6580 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6581 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6582 assert_eq!(route.paths.len(), 1);
6583 assert_eq!(route.paths[0].hops.len(), 2);
6585 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6586 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6587 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6588 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6589 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6590 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6592 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6593 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6594 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6595 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6596 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6597 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6602 fn multiple_direct_first_hops() {
6603 // Previously we'd only ever considered one first hop path per counterparty.
6604 // However, as we don't restrict users to one channel per peer, we really need to support
6605 // looking at all first hop paths.
6606 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6607 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6608 // route over multiple channels with the same first hop.
6609 let secp_ctx = Secp256k1::new();
6610 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6611 let logger = Arc::new(ln_test_utils::TestLogger::new());
6612 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6613 let scorer = ln_test_utils::TestScorer::new();
6614 let config = UserConfig::default();
6615 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6616 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6618 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6619 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6622 let route_params = RouteParameters::from_payment_params_and_value(
6623 payment_params.clone(), 100_000);
6624 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6625 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6626 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6627 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6628 assert_eq!(route.paths.len(), 1);
6629 assert_eq!(route.paths[0].hops.len(), 1);
6631 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6632 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6633 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6636 let route_params = RouteParameters::from_payment_params_and_value(
6637 payment_params.clone(), 100_000);
6638 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6639 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6640 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6641 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6642 assert_eq!(route.paths.len(), 2);
6643 assert_eq!(route.paths[0].hops.len(), 1);
6644 assert_eq!(route.paths[1].hops.len(), 1);
6646 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6647 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6649 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6650 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6652 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6653 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6657 // If we have a bunch of outbound channels to the same node, where most are not
6658 // sufficient to pay the full payment, but one is, we should default to just using the
6659 // one single channel that has sufficient balance, avoiding MPP.
6661 // If we have several options above the 3xpayment value threshold, we should pick the
6662 // smallest of them, avoiding further fragmenting our available outbound balance to
6664 let route_params = RouteParameters::from_payment_params_and_value(
6665 payment_params, 100_000);
6666 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6667 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6668 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6669 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6670 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6671 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6672 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6673 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6674 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6675 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6676 assert_eq!(route.paths.len(), 1);
6677 assert_eq!(route.paths[0].hops.len(), 1);
6679 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6680 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6681 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6686 fn prefers_shorter_route_with_higher_fees() {
6687 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6688 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6689 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6691 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6692 let scorer = ln_test_utils::TestScorer::new();
6693 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6694 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6695 let route_params = RouteParameters::from_payment_params_and_value(
6696 payment_params.clone(), 100);
6697 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6698 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6699 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6701 assert_eq!(route.get_total_fees(), 100);
6702 assert_eq!(route.get_total_amount(), 100);
6703 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6705 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6706 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6707 let scorer = FixedPenaltyScorer::with_penalty(100);
6708 let route_params = RouteParameters::from_payment_params_and_value(
6709 payment_params, 100);
6710 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6711 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6712 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6714 assert_eq!(route.get_total_fees(), 300);
6715 assert_eq!(route.get_total_amount(), 100);
6716 assert_eq!(path, vec![2, 4, 7, 10]);
6719 struct BadChannelScorer {
6720 short_channel_id: u64,
6724 impl Writeable for BadChannelScorer {
6725 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6727 impl ScoreLookUp for BadChannelScorer {
6728 type ScoreParams = ();
6729 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6730 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6734 struct BadNodeScorer {
6739 impl Writeable for BadNodeScorer {
6740 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6743 impl ScoreLookUp for BadNodeScorer {
6744 type ScoreParams = ();
6745 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6746 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6751 fn avoids_routing_through_bad_channels_and_nodes() {
6752 let (secp_ctx, network, _, _, logger) = build_graph();
6753 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6754 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6755 let network_graph = network.read_only();
6757 // A path to nodes[6] exists when no penalties are applied to any channel.
6758 let scorer = ln_test_utils::TestScorer::new();
6759 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6760 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6761 let route_params = RouteParameters::from_payment_params_and_value(
6762 payment_params, 100);
6763 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6764 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6765 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6767 assert_eq!(route.get_total_fees(), 100);
6768 assert_eq!(route.get_total_amount(), 100);
6769 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6771 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6772 let scorer = BadChannelScorer { short_channel_id: 6 };
6773 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6774 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6775 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6777 assert_eq!(route.get_total_fees(), 300);
6778 assert_eq!(route.get_total_amount(), 100);
6779 assert_eq!(path, vec![2, 4, 7, 10]);
6781 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6782 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6783 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6784 &scorer, &Default::default(), &random_seed_bytes) {
6785 Err(LightningError { err, .. } ) => {
6786 assert_eq!(err, "Failed to find a path to the given destination");
6788 Ok(_) => panic!("Expected error"),
6793 fn total_fees_single_path() {
6795 paths: vec![Path { hops: vec![
6797 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6798 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6799 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6802 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6803 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6804 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6807 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6808 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6809 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6811 ], blinded_tail: None }],
6815 assert_eq!(route.get_total_fees(), 250);
6816 assert_eq!(route.get_total_amount(), 225);
6820 fn total_fees_multi_path() {
6822 paths: vec![Path { hops: vec![
6824 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6825 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6826 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6829 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6830 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6831 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6833 ], blinded_tail: None }, Path { hops: vec![
6835 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6836 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6837 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6840 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6841 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6842 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6844 ], blinded_tail: None }],
6848 assert_eq!(route.get_total_fees(), 200);
6849 assert_eq!(route.get_total_amount(), 300);
6853 fn total_empty_route_no_panic() {
6854 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6855 // would both panic if the route was completely empty. We test to ensure they return 0
6856 // here, even though its somewhat nonsensical as a route.
6857 let route = Route { paths: Vec::new(), route_params: None };
6859 assert_eq!(route.get_total_fees(), 0);
6860 assert_eq!(route.get_total_amount(), 0);
6864 fn limits_total_cltv_delta() {
6865 let (secp_ctx, network, _, _, logger) = build_graph();
6866 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6867 let network_graph = network.read_only();
6869 let scorer = ln_test_utils::TestScorer::new();
6871 // Make sure that generally there is at least one route available
6872 let feasible_max_total_cltv_delta = 1008;
6873 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6874 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6875 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6876 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6877 let route_params = RouteParameters::from_payment_params_and_value(
6878 feasible_payment_params, 100);
6879 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6880 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6881 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6882 assert_ne!(path.len(), 0);
6884 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6885 let fail_max_total_cltv_delta = 23;
6886 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6887 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6888 let route_params = RouteParameters::from_payment_params_and_value(
6889 fail_payment_params, 100);
6890 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6891 &Default::default(), &random_seed_bytes)
6893 Err(LightningError { err, .. } ) => {
6894 assert_eq!(err, "Failed to find a path to the given destination");
6896 Ok(_) => panic!("Expected error"),
6901 fn avoids_recently_failed_paths() {
6902 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6903 // randomly inserting channels into it until we can't find a route anymore.
6904 let (secp_ctx, network, _, _, logger) = build_graph();
6905 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6906 let network_graph = network.read_only();
6908 let scorer = ln_test_utils::TestScorer::new();
6909 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6910 .with_max_path_count(1);
6911 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6912 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6914 // We should be able to find a route initially, and then after we fail a few random
6915 // channels eventually we won't be able to any longer.
6916 let route_params = RouteParameters::from_payment_params_and_value(
6917 payment_params.clone(), 100);
6918 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6919 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6921 let route_params = RouteParameters::from_payment_params_and_value(
6922 payment_params.clone(), 100);
6923 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6924 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6926 for chan in route.paths[0].hops.iter() {
6927 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6929 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6930 % route.paths[0].hops.len();
6931 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6937 fn limits_path_length() {
6938 let (secp_ctx, network, _, _, logger) = build_line_graph();
6939 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6940 let network_graph = network.read_only();
6942 let scorer = ln_test_utils::TestScorer::new();
6943 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6944 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6946 // First check we can actually create a long route on this graph.
6947 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6948 let route_params = RouteParameters::from_payment_params_and_value(
6949 feasible_payment_params, 100);
6950 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6951 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6952 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6953 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6955 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6956 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6957 let route_params = RouteParameters::from_payment_params_and_value(
6958 fail_payment_params, 100);
6959 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6960 &Default::default(), &random_seed_bytes)
6962 Err(LightningError { err, .. } ) => {
6963 assert_eq!(err, "Failed to find a path to the given destination");
6965 Ok(_) => panic!("Expected error"),
6970 fn adds_and_limits_cltv_offset() {
6971 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6972 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6974 let scorer = ln_test_utils::TestScorer::new();
6976 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6977 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6978 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6979 let route_params = RouteParameters::from_payment_params_and_value(
6980 payment_params.clone(), 100);
6981 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6982 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6983 assert_eq!(route.paths.len(), 1);
6985 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6987 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6988 let mut route_default = route.clone();
6989 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6990 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6991 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6992 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6993 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6995 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6996 let mut route_limited = route.clone();
6997 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6998 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6999 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
7000 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
7001 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
7005 fn adds_plausible_cltv_offset() {
7006 let (secp_ctx, network, _, _, logger) = build_graph();
7007 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7008 let network_graph = network.read_only();
7009 let network_nodes = network_graph.nodes();
7010 let network_channels = network_graph.channels();
7011 let scorer = ln_test_utils::TestScorer::new();
7012 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
7013 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
7014 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7016 let route_params = RouteParameters::from_payment_params_and_value(
7017 payment_params.clone(), 100);
7018 let mut route = get_route(&our_id, &route_params, &network_graph, None,
7019 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
7020 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
7022 let mut path_plausibility = vec![];
7024 for p in route.paths {
7025 // 1. Select random observation point
7026 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
7027 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
7029 prng.process_in_place(&mut random_bytes);
7030 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
7031 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
7033 // 2. Calculate what CLTV expiry delta we would observe there
7034 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
7036 // 3. Starting from the observation point, find candidate paths
7037 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
7038 candidates.push_back((observation_point, vec![]));
7040 let mut found_plausible_candidate = false;
7042 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
7043 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
7044 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
7045 found_plausible_candidate = true;
7046 break 'candidate_loop;
7050 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
7051 for channel_id in &cur_node.channels {
7052 if let Some(channel_info) = network_channels.get(&channel_id) {
7053 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
7054 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
7055 if cur_path_cltv_deltas.iter().sum::<u32>()
7056 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
7057 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
7058 new_path_cltv_deltas.push(next_cltv_expiry_delta);
7059 candidates.push_back((*next_id, new_path_cltv_deltas));
7067 path_plausibility.push(found_plausible_candidate);
7069 assert!(path_plausibility.iter().all(|x| *x));
7073 fn builds_correct_path_from_hops() {
7074 let (secp_ctx, network, _, _, logger) = build_graph();
7075 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7076 let network_graph = network.read_only();
7078 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7079 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7081 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
7082 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
7083 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
7084 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
7085 Arc::clone(&logger), &random_seed_bytes).unwrap();
7086 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
7087 assert_eq!(hops.len(), route.paths[0].hops.len());
7088 for (idx, hop_pubkey) in hops.iter().enumerate() {
7089 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
7094 fn avoids_saturating_channels() {
7095 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
7096 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
7097 let decay_params = ProbabilisticScoringDecayParameters::default();
7098 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
7100 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
7101 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
7102 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7103 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7104 short_channel_id: 4,
7107 cltv_expiry_delta: (4 << 4) | 1,
7108 htlc_minimum_msat: 0,
7109 htlc_maximum_msat: 250_000_000,
7111 fee_proportional_millionths: 0,
7112 excess_data: Vec::new()
7114 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
7115 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7116 short_channel_id: 13,
7119 cltv_expiry_delta: (13 << 4) | 1,
7120 htlc_minimum_msat: 0,
7121 htlc_maximum_msat: 250_000_000,
7123 fee_proportional_millionths: 0,
7124 excess_data: Vec::new()
7127 let config = UserConfig::default();
7128 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
7129 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7131 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7132 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7133 // 100,000 sats is less than the available liquidity on each channel, set above.
7134 let route_params = RouteParameters::from_payment_params_and_value(
7135 payment_params, 100_000_000);
7136 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
7137 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
7138 assert_eq!(route.paths.len(), 2);
7139 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
7140 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
7143 #[cfg(feature = "std")]
7144 pub(super) fn random_init_seed() -> u64 {
7145 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
7146 use core::hash::{BuildHasher, Hasher};
7147 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
7148 println!("Using seed of {}", seed);
7153 #[cfg(feature = "std")]
7154 fn generate_routes() {
7155 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7157 let logger = ln_test_utils::TestLogger::new();
7158 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7166 let params = ProbabilisticScoringFeeParameters::default();
7167 let features = super::Bolt11InvoiceFeatures::empty();
7169 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7173 #[cfg(feature = "std")]
7174 fn generate_routes_mpp() {
7175 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7177 let logger = ln_test_utils::TestLogger::new();
7178 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7186 let params = ProbabilisticScoringFeeParameters::default();
7187 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7189 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7193 #[cfg(feature = "std")]
7194 fn generate_large_mpp_routes() {
7195 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
7197 let logger = ln_test_utils::TestLogger::new();
7198 let (graph, scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7206 let params = ProbabilisticScoringFeeParameters::default();
7207 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &*graph, &logger);
7208 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7210 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
7214 fn honors_manual_penalties() {
7215 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
7216 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7218 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7219 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7221 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
7222 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
7224 // First check set manual penalties are returned by the scorer.
7225 let usage = ChannelUsage {
7227 inflight_htlc_msat: 0,
7228 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
7230 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
7231 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
7232 let network_graph = network_graph.read_only();
7233 let channels = network_graph.channels();
7234 let channel = channels.get(&5).unwrap();
7235 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
7236 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop(PublicHopCandidate {
7238 short_channel_id: 5,
7240 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
7242 // Then check we can get a normal route
7243 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
7244 let route_params = RouteParameters::from_payment_params_and_value(
7245 payment_params, 100);
7246 let route = get_route(&our_id, &route_params, &network_graph, None,
7247 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
7248 assert!(route.is_ok());
7250 // Then check that we can't get a route if we ban an intermediate node.
7251 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
7252 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7253 assert!(route.is_err());
7255 // Finally make sure we can route again, when we remove the ban.
7256 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
7257 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7258 assert!(route.is_ok());
7262 fn abide_by_route_hint_max_htlc() {
7263 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
7264 // params in the final route.
7265 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7266 let netgraph = network_graph.read_only();
7267 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7268 let scorer = ln_test_utils::TestScorer::new();
7269 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7270 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7271 let config = UserConfig::default();
7273 let max_htlc_msat = 50_000;
7274 let route_hint_1 = RouteHint(vec![RouteHintHop {
7275 src_node_id: nodes[2],
7276 short_channel_id: 42,
7279 proportional_millionths: 0,
7281 cltv_expiry_delta: 10,
7282 htlc_minimum_msat: None,
7283 htlc_maximum_msat: Some(max_htlc_msat),
7285 let dest_node_id = ln_test_utils::pubkey(42);
7286 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7287 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
7288 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7291 // Make sure we'll error if our route hints don't have enough liquidity according to their
7292 // htlc_maximum_msat.
7293 let mut route_params = RouteParameters::from_payment_params_and_value(
7294 payment_params, max_htlc_msat + 1);
7295 route_params.max_total_routing_fee_msat = None;
7296 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
7297 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
7300 assert_eq!(err, "Failed to find a sufficient route to the given destination");
7301 } else { panic!(); }
7303 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
7304 let mut route_hint_2 = route_hint_1.clone();
7305 route_hint_2.0[0].short_channel_id = 43;
7306 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7307 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7308 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7310 let mut route_params = RouteParameters::from_payment_params_and_value(
7311 payment_params, max_htlc_msat + 1);
7312 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
7313 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
7314 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7315 assert_eq!(route.paths.len(), 2);
7316 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7317 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7321 fn direct_channel_to_hints_with_max_htlc() {
7322 // Check that if we have a first hop channel peer that's connected to multiple provided route
7323 // hints, that we properly split the payment between the route hints if needed.
7324 let logger = Arc::new(ln_test_utils::TestLogger::new());
7325 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7326 let scorer = ln_test_utils::TestScorer::new();
7327 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7328 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7329 let config = UserConfig::default();
7331 let our_node_id = ln_test_utils::pubkey(42);
7332 let intermed_node_id = ln_test_utils::pubkey(43);
7333 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7335 let amt_msat = 900_000;
7336 let max_htlc_msat = 500_000;
7337 let route_hint_1 = RouteHint(vec![RouteHintHop {
7338 src_node_id: intermed_node_id,
7339 short_channel_id: 44,
7342 proportional_millionths: 0,
7344 cltv_expiry_delta: 10,
7345 htlc_minimum_msat: None,
7346 htlc_maximum_msat: Some(max_htlc_msat),
7348 src_node_id: intermed_node_id,
7349 short_channel_id: 45,
7352 proportional_millionths: 0,
7354 cltv_expiry_delta: 10,
7355 htlc_minimum_msat: None,
7356 // Check that later route hint max htlcs don't override earlier ones
7357 htlc_maximum_msat: Some(max_htlc_msat - 50),
7359 let mut route_hint_2 = route_hint_1.clone();
7360 route_hint_2.0[0].short_channel_id = 46;
7361 route_hint_2.0[1].short_channel_id = 47;
7362 let dest_node_id = ln_test_utils::pubkey(44);
7363 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7364 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7365 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7368 let route_params = RouteParameters::from_payment_params_and_value(
7369 payment_params, amt_msat);
7370 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7371 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7372 &Default::default(), &random_seed_bytes).unwrap();
7373 assert_eq!(route.paths.len(), 2);
7374 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7375 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7376 assert_eq!(route.get_total_amount(), amt_msat);
7378 // Re-run but with two first hop channels connected to the same route hint peers that must be
7380 let first_hops = vec![
7381 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7382 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7384 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7385 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7386 &Default::default(), &random_seed_bytes).unwrap();
7387 assert_eq!(route.paths.len(), 2);
7388 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7389 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7390 assert_eq!(route.get_total_amount(), amt_msat);
7392 // Make sure this works for blinded route hints.
7393 let blinded_path = BlindedPath {
7394 introduction_node_id: intermed_node_id,
7395 blinding_point: ln_test_utils::pubkey(42),
7397 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
7398 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
7401 let blinded_payinfo = BlindedPayInfo {
7403 fee_proportional_millionths: 0,
7404 htlc_minimum_msat: 1,
7405 htlc_maximum_msat: max_htlc_msat,
7406 cltv_expiry_delta: 10,
7407 features: BlindedHopFeatures::empty(),
7409 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7410 let payment_params = PaymentParameters::blinded(vec![
7411 (blinded_payinfo.clone(), blinded_path.clone()),
7412 (blinded_payinfo.clone(), blinded_path.clone())])
7413 .with_bolt12_features(bolt12_features).unwrap();
7414 let route_params = RouteParameters::from_payment_params_and_value(
7415 payment_params, amt_msat);
7416 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7417 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7418 &Default::default(), &random_seed_bytes).unwrap();
7419 assert_eq!(route.paths.len(), 2);
7420 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7421 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7422 assert_eq!(route.get_total_amount(), amt_msat);
7426 fn blinded_route_ser() {
7427 let blinded_path_1 = BlindedPath {
7428 introduction_node_id: ln_test_utils::pubkey(42),
7429 blinding_point: ln_test_utils::pubkey(43),
7431 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7432 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7435 let blinded_path_2 = BlindedPath {
7436 introduction_node_id: ln_test_utils::pubkey(46),
7437 blinding_point: ln_test_utils::pubkey(47),
7439 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7440 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7443 // (De)serialize a Route with 1 blinded path out of two total paths.
7444 let mut route = Route { paths: vec![Path {
7445 hops: vec![RouteHop {
7446 pubkey: ln_test_utils::pubkey(50),
7447 node_features: NodeFeatures::empty(),
7448 short_channel_id: 42,
7449 channel_features: ChannelFeatures::empty(),
7451 cltv_expiry_delta: 0,
7452 maybe_announced_channel: true,
7454 blinded_tail: Some(BlindedTail {
7455 hops: blinded_path_1.blinded_hops,
7456 blinding_point: blinded_path_1.blinding_point,
7457 excess_final_cltv_expiry_delta: 40,
7458 final_value_msat: 100,
7460 hops: vec![RouteHop {
7461 pubkey: ln_test_utils::pubkey(51),
7462 node_features: NodeFeatures::empty(),
7463 short_channel_id: 43,
7464 channel_features: ChannelFeatures::empty(),
7466 cltv_expiry_delta: 0,
7467 maybe_announced_channel: true,
7468 }], blinded_tail: None }],
7471 let encoded_route = route.encode();
7472 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7473 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7474 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7476 // (De)serialize a Route with two paths, each containing a blinded tail.
7477 route.paths[1].blinded_tail = Some(BlindedTail {
7478 hops: blinded_path_2.blinded_hops,
7479 blinding_point: blinded_path_2.blinding_point,
7480 excess_final_cltv_expiry_delta: 41,
7481 final_value_msat: 101,
7483 let encoded_route = route.encode();
7484 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7485 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7486 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7490 fn blinded_path_inflight_processing() {
7491 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7492 // account for the blinded tail's final amount_msat.
7493 let mut inflight_htlcs = InFlightHtlcs::new();
7494 let blinded_path = BlindedPath {
7495 introduction_node_id: ln_test_utils::pubkey(43),
7496 blinding_point: ln_test_utils::pubkey(48),
7497 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7500 hops: vec![RouteHop {
7501 pubkey: ln_test_utils::pubkey(42),
7502 node_features: NodeFeatures::empty(),
7503 short_channel_id: 42,
7504 channel_features: ChannelFeatures::empty(),
7506 cltv_expiry_delta: 0,
7507 maybe_announced_channel: false,
7510 pubkey: blinded_path.introduction_node_id,
7511 node_features: NodeFeatures::empty(),
7512 short_channel_id: 43,
7513 channel_features: ChannelFeatures::empty(),
7515 cltv_expiry_delta: 0,
7516 maybe_announced_channel: false,
7518 blinded_tail: Some(BlindedTail {
7519 hops: blinded_path.blinded_hops,
7520 blinding_point: blinded_path.blinding_point,
7521 excess_final_cltv_expiry_delta: 0,
7522 final_value_msat: 200,
7525 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7526 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7527 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7531 fn blinded_path_cltv_shadow_offset() {
7532 // Make sure we add a shadow offset when sending to blinded paths.
7533 let blinded_path = BlindedPath {
7534 introduction_node_id: ln_test_utils::pubkey(43),
7535 blinding_point: ln_test_utils::pubkey(44),
7537 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7538 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7541 let mut route = Route { paths: vec![Path {
7542 hops: vec![RouteHop {
7543 pubkey: ln_test_utils::pubkey(42),
7544 node_features: NodeFeatures::empty(),
7545 short_channel_id: 42,
7546 channel_features: ChannelFeatures::empty(),
7548 cltv_expiry_delta: 0,
7549 maybe_announced_channel: false,
7552 pubkey: blinded_path.introduction_node_id,
7553 node_features: NodeFeatures::empty(),
7554 short_channel_id: 43,
7555 channel_features: ChannelFeatures::empty(),
7557 cltv_expiry_delta: 0,
7558 maybe_announced_channel: false,
7561 blinded_tail: Some(BlindedTail {
7562 hops: blinded_path.blinded_hops,
7563 blinding_point: blinded_path.blinding_point,
7564 excess_final_cltv_expiry_delta: 0,
7565 final_value_msat: 200,
7567 }], route_params: None};
7569 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7570 let (_, network_graph, _, _, _) = build_line_graph();
7571 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7572 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7573 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7577 fn simple_blinded_route_hints() {
7578 do_simple_blinded_route_hints(1);
7579 do_simple_blinded_route_hints(2);
7580 do_simple_blinded_route_hints(3);
7583 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7584 // Check that we can generate a route to a blinded path with the expected hops.
7585 let (secp_ctx, network, _, _, logger) = build_graph();
7586 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7587 let network_graph = network.read_only();
7589 let scorer = ln_test_utils::TestScorer::new();
7590 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7591 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7593 let mut blinded_path = BlindedPath {
7594 introduction_node_id: nodes[2],
7595 blinding_point: ln_test_utils::pubkey(42),
7596 blinded_hops: Vec::with_capacity(num_blinded_hops),
7598 for i in 0..num_blinded_hops {
7599 blinded_path.blinded_hops.push(
7600 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7603 let blinded_payinfo = BlindedPayInfo {
7605 fee_proportional_millionths: 500,
7606 htlc_minimum_msat: 1000,
7607 htlc_maximum_msat: 100_000_000,
7608 cltv_expiry_delta: 15,
7609 features: BlindedHopFeatures::empty(),
7612 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7613 let route_params = RouteParameters::from_payment_params_and_value(
7614 payment_params, 1001);
7615 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7616 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7617 assert_eq!(route.paths.len(), 1);
7618 assert_eq!(route.paths[0].hops.len(), 2);
7620 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7621 assert_eq!(tail.hops, blinded_path.blinded_hops);
7622 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7623 assert_eq!(tail.final_value_msat, 1001);
7625 let final_hop = route.paths[0].hops.last().unwrap();
7626 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
7627 if tail.hops.len() > 1 {
7628 assert_eq!(final_hop.fee_msat,
7629 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7630 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7632 assert_eq!(final_hop.fee_msat, 0);
7633 assert_eq!(final_hop.cltv_expiry_delta, 0);
7638 fn blinded_path_routing_errors() {
7639 // Check that we can generate a route to a blinded path with the expected hops.
7640 let (secp_ctx, network, _, _, logger) = build_graph();
7641 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7642 let network_graph = network.read_only();
7644 let scorer = ln_test_utils::TestScorer::new();
7645 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7646 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7648 let mut invalid_blinded_path = BlindedPath {
7649 introduction_node_id: nodes[2],
7650 blinding_point: ln_test_utils::pubkey(42),
7652 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7655 let blinded_payinfo = BlindedPayInfo {
7657 fee_proportional_millionths: 500,
7658 htlc_minimum_msat: 1000,
7659 htlc_maximum_msat: 100_000_000,
7660 cltv_expiry_delta: 15,
7661 features: BlindedHopFeatures::empty(),
7664 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7665 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
7666 let payment_params = PaymentParameters::blinded(vec![
7667 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7668 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7669 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7670 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7671 &scorer, &Default::default(), &random_seed_bytes)
7673 Err(LightningError { err, .. }) => {
7674 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7676 _ => panic!("Expected error")
7679 invalid_blinded_path.introduction_node_id = our_id;
7680 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7681 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7682 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7683 &Default::default(), &random_seed_bytes)
7685 Err(LightningError { err, .. }) => {
7686 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7688 _ => panic!("Expected error")
7691 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
7692 invalid_blinded_path.blinded_hops.clear();
7693 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7694 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7695 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7696 &Default::default(), &random_seed_bytes)
7698 Err(LightningError { err, .. }) => {
7699 assert_eq!(err, "0-hop blinded path provided");
7701 _ => panic!("Expected error")
7706 fn matching_intro_node_paths_provided() {
7707 // Check that if multiple blinded paths with the same intro node are provided in payment
7708 // parameters, we'll return the correct paths in the resulting MPP route.
7709 let (secp_ctx, network, _, _, logger) = build_graph();
7710 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7711 let network_graph = network.read_only();
7713 let scorer = ln_test_utils::TestScorer::new();
7714 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7715 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7716 let config = UserConfig::default();
7718 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7719 let blinded_path_1 = BlindedPath {
7720 introduction_node_id: nodes[2],
7721 blinding_point: ln_test_utils::pubkey(42),
7723 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7724 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7727 let blinded_payinfo_1 = BlindedPayInfo {
7729 fee_proportional_millionths: 0,
7730 htlc_minimum_msat: 0,
7731 htlc_maximum_msat: 30_000,
7732 cltv_expiry_delta: 0,
7733 features: BlindedHopFeatures::empty(),
7736 let mut blinded_path_2 = blinded_path_1.clone();
7737 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7738 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7739 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7741 let blinded_hints = vec![
7742 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7743 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7745 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7746 .with_bolt12_features(bolt12_features).unwrap();
7748 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7749 route_params.max_total_routing_fee_msat = Some(100_000);
7750 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7751 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7752 assert_eq!(route.paths.len(), 2);
7753 let mut total_amount_paid_msat = 0;
7754 for path in route.paths.into_iter() {
7755 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7756 if let Some(bt) = &path.blinded_tail {
7757 assert_eq!(bt.blinding_point,
7758 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7759 .map(|(_, bp)| bp.blinding_point).unwrap());
7760 } else { panic!(); }
7761 total_amount_paid_msat += path.final_value_msat();
7763 assert_eq!(total_amount_paid_msat, 100_000);
7767 fn direct_to_intro_node() {
7768 // This previously caused a debug panic in the router when asserting
7769 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7770 // direct channels we failed to account for the fee charged for use of the blinded path.
7773 // node0 -1(1)2 - node1
7774 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7775 // doesn't account for the blinded path fee.
7777 let secp_ctx = Secp256k1::new();
7778 let logger = Arc::new(ln_test_utils::TestLogger::new());
7779 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7780 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7781 let scorer = ln_test_utils::TestScorer::new();
7782 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7783 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7785 let amt_msat = 10_000_000;
7786 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7787 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7788 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7789 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7790 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7791 short_channel_id: 1,
7794 cltv_expiry_delta: 42,
7795 htlc_minimum_msat: 1_000,
7796 htlc_maximum_msat: 10_000_000,
7798 fee_proportional_millionths: 0,
7799 excess_data: Vec::new()
7801 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7802 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7803 short_channel_id: 1,
7806 cltv_expiry_delta: 42,
7807 htlc_minimum_msat: 1_000,
7808 htlc_maximum_msat: 10_000_000,
7810 fee_proportional_millionths: 0,
7811 excess_data: Vec::new()
7813 let first_hops = vec![
7814 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7816 let blinded_path = BlindedPath {
7817 introduction_node_id: nodes[1],
7818 blinding_point: ln_test_utils::pubkey(42),
7820 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7821 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7824 let blinded_payinfo = BlindedPayInfo {
7825 fee_base_msat: 1000,
7826 fee_proportional_millionths: 0,
7827 htlc_minimum_msat: 1000,
7828 htlc_maximum_msat: MAX_VALUE_MSAT,
7829 cltv_expiry_delta: 0,
7830 features: BlindedHopFeatures::empty(),
7832 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7834 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7836 let netgraph = network_graph.read_only();
7837 let route_params = RouteParameters::from_payment_params_and_value(
7838 payment_params.clone(), amt_msat);
7839 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7840 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7841 &Default::default(), &random_seed_bytes) {
7842 assert_eq!(err, "Failed to find a path to the given destination");
7843 } else { panic!("Expected error") }
7845 // Sending an exact amount accounting for the blinded path fee works.
7846 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7847 let route_params = RouteParameters::from_payment_params_and_value(
7848 payment_params, amt_minus_blinded_path_fee);
7849 let route = get_route(&nodes[0], &route_params, &netgraph,
7850 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7851 &Default::default(), &random_seed_bytes).unwrap();
7852 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7853 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7857 fn direct_to_matching_intro_nodes() {
7858 // This previously caused us to enter `unreachable` code in the following situation:
7859 // 1. We add a route candidate for intro_node contributing a high amount
7860 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7861 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7862 // amount, and update our route candidate for intro_node for the lower amount
7863 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7864 // lower contribution amount, but fail (this was previously caused by failure to account for
7865 // blinded path fees when adding first_hop<>intro_node candidates)
7866 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7867 // candidate still thinks its path is contributing the original higher amount. This caused us
7868 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7870 let secp_ctx = Secp256k1::new();
7871 let logger = Arc::new(ln_test_utils::TestLogger::new());
7872 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7873 let scorer = ln_test_utils::TestScorer::new();
7874 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7875 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7876 let config = UserConfig::default();
7878 // Values are taken from the fuzz input that uncovered this panic.
7879 let amt_msat = 21_7020_5185_1403_2640;
7880 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7881 let first_hops = vec![
7882 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7883 18446744073709551615)];
7885 let blinded_path = BlindedPath {
7886 introduction_node_id: nodes[1],
7887 blinding_point: ln_test_utils::pubkey(42),
7889 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7890 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7893 let blinded_payinfo = BlindedPayInfo {
7894 fee_base_msat: 5046_2720,
7895 fee_proportional_millionths: 0,
7896 htlc_minimum_msat: 4503_5996_2737_0496,
7897 htlc_maximum_msat: 45_0359_9627_3704_9600,
7898 cltv_expiry_delta: 0,
7899 features: BlindedHopFeatures::empty(),
7901 let mut blinded_hints = vec![
7902 (blinded_payinfo.clone(), blinded_path.clone()),
7903 (blinded_payinfo.clone(), blinded_path.clone()),
7905 blinded_hints[1].0.fee_base_msat = 419_4304;
7906 blinded_hints[1].0.fee_proportional_millionths = 257;
7907 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7908 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7909 blinded_hints[1].0.cltv_expiry_delta = 0;
7911 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7912 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7913 .with_bolt12_features(bolt12_features).unwrap();
7915 let netgraph = network_graph.read_only();
7916 let route_params = RouteParameters::from_payment_params_and_value(
7917 payment_params, amt_msat);
7918 let route = get_route(&nodes[0], &route_params, &netgraph,
7919 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7920 &Default::default(), &random_seed_bytes).unwrap();
7921 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7922 assert_eq!(route.get_total_amount(), amt_msat);
7926 fn we_are_intro_node_candidate_hops() {
7927 // This previously led to a panic in the router because we'd generate a Path with only a
7928 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7929 // where the origin node is the intro node. We now fully disallow considering candidate hops
7930 // where the origin node is the intro node.
7931 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7932 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7933 let scorer = ln_test_utils::TestScorer::new();
7934 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7935 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7936 let config = UserConfig::default();
7938 // Values are taken from the fuzz input that uncovered this panic.
7939 let amt_msat = 21_7020_5185_1423_0019;
7941 let blinded_path = BlindedPath {
7942 introduction_node_id: our_id,
7943 blinding_point: ln_test_utils::pubkey(42),
7945 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7946 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7949 let blinded_payinfo = BlindedPayInfo {
7950 fee_base_msat: 5052_9027,
7951 fee_proportional_millionths: 0,
7952 htlc_minimum_msat: 21_7020_5185_1423_0019,
7953 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7954 cltv_expiry_delta: 0,
7955 features: BlindedHopFeatures::empty(),
7957 let mut blinded_hints = vec![
7958 (blinded_payinfo.clone(), blinded_path.clone()),
7959 (blinded_payinfo.clone(), blinded_path.clone()),
7961 blinded_hints[1].1.introduction_node_id = nodes[6];
7963 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7964 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7965 .with_bolt12_features(bolt12_features.clone()).unwrap();
7967 let netgraph = network_graph.read_only();
7968 let route_params = RouteParameters::from_payment_params_and_value(
7969 payment_params, amt_msat);
7970 if let Err(LightningError { err, .. }) = get_route(
7971 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7973 assert_eq!(err, "Failed to find a path to the given destination");
7978 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7979 // This previously led to a debug panic in the router because we'd find an invalid Path with
7980 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7981 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7982 // the payment, when it was intended to only include the final value of the payment.
7983 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7984 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7985 let scorer = ln_test_utils::TestScorer::new();
7986 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7987 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7988 let config = UserConfig::default();
7990 // Values are taken from the fuzz input that uncovered this panic.
7991 let amt_msat = 21_7020_5185_1423_0019;
7993 let blinded_path = BlindedPath {
7994 introduction_node_id: our_id,
7995 blinding_point: ln_test_utils::pubkey(42),
7997 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7998 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8001 let blinded_payinfo = BlindedPayInfo {
8002 fee_base_msat: 10_4425_1395,
8003 fee_proportional_millionths: 0,
8004 htlc_minimum_msat: 21_7301_9934_9094_0931,
8005 htlc_maximum_msat: 1844_6744_0737_0955_1615,
8006 cltv_expiry_delta: 0,
8007 features: BlindedHopFeatures::empty(),
8009 let mut blinded_hints = vec![
8010 (blinded_payinfo.clone(), blinded_path.clone()),
8011 (blinded_payinfo.clone(), blinded_path.clone()),
8012 (blinded_payinfo.clone(), blinded_path.clone()),
8014 blinded_hints[1].0.fee_base_msat = 5052_9027;
8015 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
8016 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
8018 blinded_hints[2].1.introduction_node_id = nodes[6];
8020 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8021 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8022 .with_bolt12_features(bolt12_features.clone()).unwrap();
8024 let netgraph = network_graph.read_only();
8025 let route_params = RouteParameters::from_payment_params_and_value(
8026 payment_params, amt_msat);
8027 if let Err(LightningError { err, .. }) = get_route(
8028 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8030 assert_eq!(err, "Failed to find a path to the given destination");
8035 fn min_htlc_overpay_violates_max_htlc() {
8036 do_min_htlc_overpay_violates_max_htlc(true);
8037 do_min_htlc_overpay_violates_max_htlc(false);
8039 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
8040 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
8041 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
8042 // to `targets` and build an invalid path with it, and subsequently hit a debug panic asserting
8043 // that the used liquidity for a hop was less than its available liquidity limit.
8044 let secp_ctx = Secp256k1::new();
8045 let logger = Arc::new(ln_test_utils::TestLogger::new());
8046 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8047 let scorer = ln_test_utils::TestScorer::new();
8048 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8049 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8050 let config = UserConfig::default();
8052 // Values are taken from the fuzz input that uncovered this panic.
8053 let amt_msat = 7_4009_8048;
8054 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8055 let first_hop_outbound_capacity = 2_7345_2000;
8056 let first_hops = vec![get_channel_details(
8057 Some(200), nodes[0], channelmanager::provided_init_features(&config),
8058 first_hop_outbound_capacity
8061 let base_fee = 1_6778_3453;
8062 let htlc_min = 2_5165_8240;
8063 let payment_params = if blinded_payee {
8064 let blinded_path = BlindedPath {
8065 introduction_node_id: nodes[0],
8066 blinding_point: ln_test_utils::pubkey(42),
8068 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8069 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8072 let blinded_payinfo = BlindedPayInfo {
8073 fee_base_msat: base_fee,
8074 fee_proportional_millionths: 0,
8075 htlc_minimum_msat: htlc_min,
8076 htlc_maximum_msat: htlc_min * 1000,
8077 cltv_expiry_delta: 0,
8078 features: BlindedHopFeatures::empty(),
8080 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8081 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
8082 .with_bolt12_features(bolt12_features.clone()).unwrap()
8084 let route_hint = RouteHint(vec![RouteHintHop {
8085 src_node_id: nodes[0],
8086 short_channel_id: 42,
8088 base_msat: base_fee,
8089 proportional_millionths: 0,
8091 cltv_expiry_delta: 10,
8092 htlc_minimum_msat: Some(htlc_min),
8093 htlc_maximum_msat: None,
8096 PaymentParameters::from_node_id(nodes[1], 42)
8097 .with_route_hints(vec![route_hint]).unwrap()
8098 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8101 let netgraph = network_graph.read_only();
8102 let route_params = RouteParameters::from_payment_params_and_value(
8103 payment_params, amt_msat);
8104 if let Err(LightningError { err, .. }) = get_route(
8105 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8106 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8108 assert_eq!(err, "Failed to find a path to the given destination");
8113 fn previously_used_liquidity_violates_max_htlc() {
8114 do_previously_used_liquidity_violates_max_htlc(true);
8115 do_previously_used_liquidity_violates_max_htlc(false);
8118 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
8119 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
8120 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
8121 // candidate. In this case, the candidate does not have enough due to a previous path taking up
8122 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
8123 // asserting that the used liquidity for a hop was less than its available liquidity limit.
8124 let secp_ctx = Secp256k1::new();
8125 let logger = Arc::new(ln_test_utils::TestLogger::new());
8126 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8127 let scorer = ln_test_utils::TestScorer::new();
8128 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8129 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8130 let config = UserConfig::default();
8132 // Values are taken from the fuzz input that uncovered this panic.
8133 let amt_msat = 52_4288;
8134 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8135 let first_hops = vec![get_channel_details(
8136 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
8137 ), get_channel_details(
8138 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
8141 let base_fees = [0, 425_9840, 0, 0];
8142 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
8143 let payment_params = if blinded_payee {
8144 let blinded_path = BlindedPath {
8145 introduction_node_id: nodes[0],
8146 blinding_point: ln_test_utils::pubkey(42),
8148 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8149 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8152 let mut blinded_hints = Vec::new();
8153 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
8154 blinded_hints.push((BlindedPayInfo {
8155 fee_base_msat: *base_fee,
8156 fee_proportional_millionths: 0,
8157 htlc_minimum_msat: *htlc_min,
8158 htlc_maximum_msat: htlc_min * 100,
8159 cltv_expiry_delta: 10,
8160 features: BlindedHopFeatures::empty(),
8161 }, blinded_path.clone()));
8163 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8164 PaymentParameters::blinded(blinded_hints.clone())
8165 .with_bolt12_features(bolt12_features.clone()).unwrap()
8167 let mut route_hints = Vec::new();
8168 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
8169 route_hints.push(RouteHint(vec![RouteHintHop {
8170 src_node_id: nodes[0],
8171 short_channel_id: 42 + idx as u64,
8173 base_msat: *base_fee,
8174 proportional_millionths: 0,
8176 cltv_expiry_delta: 10,
8177 htlc_minimum_msat: Some(*htlc_min),
8178 htlc_maximum_msat: Some(htlc_min * 100),
8181 PaymentParameters::from_node_id(nodes[1], 42)
8182 .with_route_hints(route_hints).unwrap()
8183 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8186 let netgraph = network_graph.read_only();
8187 let route_params = RouteParameters::from_payment_params_and_value(
8188 payment_params, amt_msat);
8190 let route = get_route(
8191 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8192 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8194 assert_eq!(route.paths.len(), 1);
8195 assert_eq!(route.get_total_amount(), amt_msat);
8199 fn candidate_path_min() {
8200 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
8201 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
8202 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
8203 // would add a connecting first_hop node that did not have enough contribution amount, leading
8204 // to a debug panic upon invalid path construction.
8205 let secp_ctx = Secp256k1::new();
8206 let logger = Arc::new(ln_test_utils::TestLogger::new());
8207 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8208 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
8209 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8210 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8211 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8212 let config = UserConfig::default();
8214 // Values are taken from the fuzz input that uncovered this panic.
8215 let amt_msat = 7_4009_8048;
8216 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
8217 let first_hops = vec![get_channel_details(
8218 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
8221 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
8222 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8223 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8224 short_channel_id: 6,
8227 cltv_expiry_delta: (6 << 4) | 0,
8228 htlc_minimum_msat: 0,
8229 htlc_maximum_msat: MAX_VALUE_MSAT,
8231 fee_proportional_millionths: 0,
8232 excess_data: Vec::new()
8234 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
8236 let htlc_min = 2_5165_8240;
8237 let blinded_hints = vec![
8239 fee_base_msat: 1_6778_3453,
8240 fee_proportional_millionths: 0,
8241 htlc_minimum_msat: htlc_min,
8242 htlc_maximum_msat: htlc_min * 100,
8243 cltv_expiry_delta: 10,
8244 features: BlindedHopFeatures::empty(),
8246 introduction_node_id: nodes[0],
8247 blinding_point: ln_test_utils::pubkey(42),
8249 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8250 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8254 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8255 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8256 .with_bolt12_features(bolt12_features.clone()).unwrap();
8257 let route_params = RouteParameters::from_payment_params_and_value(
8258 payment_params, amt_msat);
8259 let netgraph = network_graph.read_only();
8261 if let Err(LightningError { err, .. }) = get_route(
8262 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8263 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8266 assert_eq!(err, "Failed to find a path to the given destination");
8271 fn path_contribution_includes_min_htlc_overpay() {
8272 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
8273 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
8274 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
8275 // selection, both tested here.
8276 let secp_ctx = Secp256k1::new();
8277 let logger = Arc::new(ln_test_utils::TestLogger::new());
8278 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8279 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8280 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8281 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8282 let config = UserConfig::default();
8284 // Values are taken from the fuzz input that uncovered this panic.
8285 let amt_msat = 562_0000;
8286 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8287 let first_hops = vec![
8288 get_channel_details(
8289 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
8293 let htlc_mins = [49_0000, 1125_0000];
8294 let payment_params = {
8295 let blinded_path = BlindedPath {
8296 introduction_node_id: nodes[0],
8297 blinding_point: ln_test_utils::pubkey(42),
8299 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8300 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8303 let mut blinded_hints = Vec::new();
8304 for htlc_min in htlc_mins.iter() {
8305 blinded_hints.push((BlindedPayInfo {
8307 fee_proportional_millionths: 0,
8308 htlc_minimum_msat: *htlc_min,
8309 htlc_maximum_msat: *htlc_min * 100,
8310 cltv_expiry_delta: 10,
8311 features: BlindedHopFeatures::empty(),
8312 }, blinded_path.clone()));
8314 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8315 PaymentParameters::blinded(blinded_hints.clone())
8316 .with_bolt12_features(bolt12_features.clone()).unwrap()
8319 let netgraph = network_graph.read_only();
8320 let route_params = RouteParameters::from_payment_params_and_value(
8321 payment_params, amt_msat);
8322 let route = get_route(
8323 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8324 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8327 assert_eq!(route.paths.len(), 1);
8328 assert_eq!(route.get_total_amount(), amt_msat);
8332 fn first_hop_preferred_over_hint() {
8333 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
8334 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
8335 let secp_ctx = Secp256k1::new();
8336 let logger = Arc::new(ln_test_utils::TestLogger::new());
8337 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8338 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
8339 let scorer = ln_test_utils::TestScorer::new();
8340 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8341 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8342 let config = UserConfig::default();
8344 let amt_msat = 1_000_000;
8345 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
8347 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
8348 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
8349 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8350 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8351 short_channel_id: 1,
8354 cltv_expiry_delta: 42,
8355 htlc_minimum_msat: 1_000,
8356 htlc_maximum_msat: 10_000_000,
8358 fee_proportional_millionths: 0,
8359 excess_data: Vec::new()
8361 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8362 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8363 short_channel_id: 1,
8366 cltv_expiry_delta: 42,
8367 htlc_minimum_msat: 1_000,
8368 htlc_maximum_msat: 10_000_000,
8370 fee_proportional_millionths: 0,
8371 excess_data: Vec::new()
8374 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
8375 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
8376 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8377 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8378 short_channel_id: 2,
8381 cltv_expiry_delta: 42,
8382 htlc_minimum_msat: 1_000,
8383 htlc_maximum_msat: 10_000_000,
8385 fee_proportional_millionths: 0,
8386 excess_data: Vec::new()
8388 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8389 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8390 short_channel_id: 2,
8393 cltv_expiry_delta: 42,
8394 htlc_minimum_msat: 1_000,
8395 htlc_maximum_msat: 10_000_000,
8397 fee_proportional_millionths: 0,
8398 excess_data: Vec::new()
8401 let dest_node_id = nodes[2];
8403 let route_hint = RouteHint(vec![RouteHintHop {
8404 src_node_id: our_node_id,
8405 short_channel_id: 44,
8408 proportional_millionths: 0,
8410 cltv_expiry_delta: 10,
8411 htlc_minimum_msat: None,
8412 htlc_maximum_msat: Some(5_000_000),
8415 src_node_id: nodes[0],
8416 short_channel_id: 45,
8419 proportional_millionths: 0,
8421 cltv_expiry_delta: 10,
8422 htlc_minimum_msat: None,
8423 htlc_maximum_msat: None,
8426 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8427 .with_route_hints(vec![route_hint]).unwrap()
8428 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8429 let route_params = RouteParameters::from_payment_params_and_value(
8430 payment_params, amt_msat);
8432 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8434 let first_hop = get_channel_details(Some(1), nodes[0],
8435 channelmanager::provided_init_features(&config), 999_999);
8436 let first_hops = vec![first_hop];
8438 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8439 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8440 &Default::default(), &random_seed_bytes).unwrap();
8441 assert_eq!(route.paths.len(), 1);
8442 assert_eq!(route.get_total_amount(), amt_msat);
8443 assert_eq!(route.paths[0].hops.len(), 2);
8444 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8445 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8446 assert_eq!(route.get_total_fees(), 123);
8448 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8449 // for a first hop channel.
8450 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8451 first_hop.outbound_scid_alias = Some(44);
8452 let first_hops = vec![first_hop];
8454 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8455 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8456 &Default::default(), &random_seed_bytes);
8457 assert!(route_res.is_err());
8459 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8460 // use the cheaper second hop of the route hint.
8461 let mut first_hop = get_channel_details(Some(1), nodes[0],
8462 channelmanager::provided_init_features(&config), 10_000_000);
8463 first_hop.outbound_scid_alias = Some(44);
8464 let first_hops = vec![first_hop];
8466 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8467 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8468 &Default::default(), &random_seed_bytes).unwrap();
8469 assert_eq!(route.paths.len(), 1);
8470 assert_eq!(route.get_total_amount(), amt_msat);
8471 assert_eq!(route.paths[0].hops.len(), 2);
8472 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8473 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8474 assert_eq!(route.get_total_fees(), 123);
8478 fn allow_us_being_first_hint() {
8479 // Check that we consider a route hint even if we are the src of the first hop.
8480 let secp_ctx = Secp256k1::new();
8481 let logger = Arc::new(ln_test_utils::TestLogger::new());
8482 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8483 let scorer = ln_test_utils::TestScorer::new();
8484 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8485 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8486 let config = UserConfig::default();
8488 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8490 let amt_msat = 1_000_000;
8491 let dest_node_id = nodes[1];
8493 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8494 let first_hops = vec![first_hop];
8496 let route_hint = RouteHint(vec![RouteHintHop {
8497 src_node_id: our_node_id,
8498 short_channel_id: 44,
8501 proportional_millionths: 0,
8503 cltv_expiry_delta: 10,
8504 htlc_minimum_msat: None,
8505 htlc_maximum_msat: None,
8508 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8509 .with_route_hints(vec![route_hint]).unwrap()
8510 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8512 let route_params = RouteParameters::from_payment_params_and_value(
8513 payment_params, amt_msat);
8516 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8517 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8518 &Default::default(), &random_seed_bytes).unwrap();
8520 assert_eq!(route.paths.len(), 1);
8521 assert_eq!(route.get_total_amount(), amt_msat);
8522 assert_eq!(route.get_total_fees(), 0);
8523 assert_eq!(route.paths[0].hops.len(), 1);
8525 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8529 #[cfg(all(any(test, ldk_bench), feature = "std"))]
8530 pub(crate) mod bench_utils {
8534 use bitcoin::hashes::Hash;
8535 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
8537 use crate::chain::transaction::OutPoint;
8538 use crate::routing::scoring::ScoreUpdate;
8539 use crate::sign::{EntropySource, KeysManager};
8540 use crate::ln::ChannelId;
8541 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
8542 use crate::ln::features::Bolt11InvoiceFeatures;
8543 use crate::routing::gossip::NetworkGraph;
8544 use crate::routing::scoring::ProbabilisticScorer;
8545 use crate::util::config::UserConfig;
8546 use crate::util::ser::ReadableArgs;
8547 use crate::util::test_utils::TestLogger;
8548 use crate::sync::Arc;
8550 /// Tries to open a network graph file, or panics with a URL to fetch it.
8551 pub(crate) fn get_graph_scorer_file() -> Result<(std::fs::File, std::fs::File), &'static str> {
8552 let load_file = |fname, err_str| {
8553 File::open(fname) // By default we're run in RL/lightning
8554 .or_else(|_| File::open(&format!("lightning/{}", fname))) // We may be run manually in RL/
8555 .or_else(|_| { // Fall back to guessing based on the binary location
8556 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8557 let mut path = std::env::current_exe().unwrap();
8558 path.pop(); // lightning-...
8560 path.pop(); // debug
8561 path.pop(); // target
8562 path.push("lightning");
8566 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8567 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8568 let mut path = std::env::current_exe().unwrap();
8569 path.pop(); // bench...
8571 path.pop(); // debug
8572 path.pop(); // target
8573 path.pop(); // bench
8574 path.push("lightning");
8578 .map_err(|_| err_str)
8580 let graph_res = load_file(
8581 "net_graph-2023-12-10.bin",
8582 "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"
8584 let scorer_res = load_file(
8585 "scorer-2023-12-10.bin",
8586 "Please fetch https://bitcoin.ninja/ldk-scorer-v0.0.118-2023-12-10.bin and place it at scorer-2023-12-10.bin"
8588 #[cfg(require_route_graph_test)]
8589 return Ok((graph_res.unwrap(), scorer_res.unwrap()));
8590 #[cfg(not(require_route_graph_test))]
8591 return Ok((graph_res?, scorer_res?));
8594 pub(crate) fn read_graph_scorer(logger: &TestLogger)
8595 -> Result<(Arc<NetworkGraph<&TestLogger>>, ProbabilisticScorer<Arc<NetworkGraph<&TestLogger>>, &TestLogger>), &'static str> {
8596 let (mut graph_file, mut scorer_file) = get_graph_scorer_file()?;
8597 let graph = Arc::new(NetworkGraph::read(&mut graph_file, logger).unwrap());
8598 let scorer_args = (Default::default(), Arc::clone(&graph), logger);
8599 let scorer = ProbabilisticScorer::read(&mut scorer_file, scorer_args).unwrap();
8603 pub(crate) fn payer_pubkey() -> PublicKey {
8604 let secp_ctx = Secp256k1::new();
8605 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8609 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8611 channel_id: ChannelId::new_zero(),
8612 counterparty: ChannelCounterparty {
8613 features: channelmanager::provided_init_features(&UserConfig::default()),
8615 unspendable_punishment_reserve: 0,
8616 forwarding_info: None,
8617 outbound_htlc_minimum_msat: None,
8618 outbound_htlc_maximum_msat: None,
8620 funding_txo: Some(OutPoint {
8621 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8624 short_channel_id: Some(1),
8625 inbound_scid_alias: None,
8626 outbound_scid_alias: None,
8627 channel_value_satoshis: 10_000_000_000,
8629 balance_msat: 10_000_000_000,
8630 outbound_capacity_msat: 10_000_000_000,
8631 next_outbound_htlc_minimum_msat: 0,
8632 next_outbound_htlc_limit_msat: 10_000_000_000,
8633 inbound_capacity_msat: 0,
8634 unspendable_punishment_reserve: None,
8635 confirmations_required: None,
8636 confirmations: None,
8637 force_close_spend_delay: None,
8639 is_channel_ready: true,
8642 inbound_htlc_minimum_msat: None,
8643 inbound_htlc_maximum_msat: None,
8645 feerate_sat_per_1000_weight: None,
8646 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
8647 pending_inbound_htlcs: Vec::new(),
8648 pending_outbound_htlcs: Vec::new(),
8652 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8653 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8654 starting_amount: u64, route_count: usize,
8655 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8656 let payer = payer_pubkey();
8657 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8658 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8660 let nodes = graph.read_only().nodes().clone();
8661 let mut route_endpoints = Vec::new();
8662 for _ in 0..route_count {
8664 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8665 let src = PublicKey::from_slice(nodes.unordered_keys()
8666 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8667 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8668 let dst = PublicKey::from_slice(nodes.unordered_keys()
8669 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8670 let params = PaymentParameters::from_node_id(dst, 42)
8671 .with_bolt11_features(features.clone()).unwrap();
8672 let first_hop = first_hop(src);
8673 let amt_msat = starting_amount + seed % 1_000_000;
8674 let route_params = RouteParameters::from_payment_params_and_value(
8675 params.clone(), amt_msat);
8677 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8678 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8680 route_endpoints.push((first_hop, params, amt_msat));
8686 // Because we've changed channel scores, it's possible we'll take different routes to the
8687 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
8688 // requires a too-high CLTV delta.
8689 route_endpoints.retain(|(first_hop, params, amt_msat)| {
8690 let route_params = RouteParameters::from_payment_params_and_value(
8691 params.clone(), *amt_msat);
8692 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8693 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
8695 route_endpoints.truncate(route_count);
8696 assert_eq!(route_endpoints.len(), route_count);
8704 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8705 use crate::sign::{EntropySource, KeysManager};
8706 use crate::ln::channelmanager;
8707 use crate::ln::features::Bolt11InvoiceFeatures;
8708 use crate::routing::gossip::NetworkGraph;
8709 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScoringFeeParameters};
8710 use crate::util::config::UserConfig;
8711 use crate::util::logger::{Logger, Record};
8712 use crate::util::test_utils::TestLogger;
8714 use criterion::Criterion;
8716 struct DummyLogger {}
8717 impl Logger for DummyLogger {
8718 fn log(&self, _record: Record) {}
8721 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8722 let logger = TestLogger::new();
8723 let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap();
8724 let scorer = FixedPenaltyScorer::with_penalty(0);
8725 generate_routes(bench, &network_graph, scorer, &Default::default(),
8726 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8729 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8730 let logger = TestLogger::new();
8731 let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap();
8732 let scorer = FixedPenaltyScorer::with_penalty(0);
8733 generate_routes(bench, &network_graph, scorer, &Default::default(),
8734 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8735 "generate_mpp_routes_with_zero_penalty_scorer");
8738 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8739 let logger = TestLogger::new();
8740 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8741 let params = ProbabilisticScoringFeeParameters::default();
8742 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8743 "generate_routes_with_probabilistic_scorer");
8746 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8747 let logger = TestLogger::new();
8748 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8749 let params = ProbabilisticScoringFeeParameters::default();
8750 generate_routes(bench, &network_graph, scorer, ¶ms,
8751 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8752 "generate_mpp_routes_with_probabilistic_scorer");
8755 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8756 let logger = TestLogger::new();
8757 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8758 let params = ProbabilisticScoringFeeParameters::default();
8759 generate_routes(bench, &network_graph, scorer, ¶ms,
8760 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8761 "generate_large_mpp_routes_with_probabilistic_scorer");
8764 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8765 let logger = TestLogger::new();
8766 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8767 let mut params = ProbabilisticScoringFeeParameters::default();
8768 params.linear_success_probability = false;
8769 generate_routes(bench, &network_graph, scorer, ¶ms,
8770 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8771 "generate_routes_with_nonlinear_probabilistic_scorer");
8774 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8775 let logger = TestLogger::new();
8776 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8777 let mut params = ProbabilisticScoringFeeParameters::default();
8778 params.linear_success_probability = false;
8779 generate_routes(bench, &network_graph, scorer, ¶ms,
8780 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8781 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8784 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8785 let logger = TestLogger::new();
8786 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8787 let mut params = ProbabilisticScoringFeeParameters::default();
8788 params.linear_success_probability = false;
8789 generate_routes(bench, &network_graph, scorer, ¶ms,
8790 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8791 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8794 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8795 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8796 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8797 bench_name: &'static str,
8799 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8800 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8802 // ...then benchmark finding paths between the nodes we learned.
8803 do_route_bench(bench, graph, scorer, score_params, bench_name, route_endpoints);
8807 fn do_route_bench<S: ScoreLookUp + ScoreUpdate>(
8808 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, scorer: S,
8809 score_params: &S::ScoreParams, bench_name: &'static str,
8810 route_endpoints: Vec<(ChannelDetails, PaymentParameters, u64)>,
8812 let payer = bench_utils::payer_pubkey();
8813 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8814 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8817 bench.bench_function(bench_name, |b| b.iter(|| {
8818 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8819 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8820 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8821 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());