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.
1130 // Thus, we use `#[repr(C)]` on the struct to force a suboptimal layout and check that it stays 64
1132 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1133 const _GRAPH_NODE_SMALL: usize = 64 - core::mem::size_of::<RouteGraphNode>();
1134 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1135 const _GRAPH_NODE_FIXED_SIZE: usize = core::mem::size_of::<RouteGraphNode>() - 64;
1137 /// A [`CandidateRouteHop::FirstHop`] entry.
1138 #[derive(Clone, Debug)]
1139 pub struct FirstHopCandidate<'a> {
1140 /// Channel details of the first hop
1142 /// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1143 /// has been funded and is able to pay), and accessor methods may panic otherwise.
1145 /// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1147 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1148 pub details: &'a ChannelDetails,
1149 /// The node id of the payer, which is also the source side of this candidate route hop.
1151 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1152 pub payer_node_id: &'a NodeId,
1155 /// A [`CandidateRouteHop::PublicHop`] entry.
1156 #[derive(Clone, Debug)]
1157 pub struct PublicHopCandidate<'a> {
1158 /// Information about the channel, including potentially its capacity and
1159 /// direction-specific information.
1161 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1162 pub info: DirectedChannelInfo<'a>,
1163 /// The short channel ID of the channel, i.e. the identifier by which we refer to this
1165 pub short_channel_id: u64,
1168 /// A [`CandidateRouteHop::PrivateHop`] entry.
1169 #[derive(Clone, Debug)]
1170 pub struct PrivateHopCandidate<'a> {
1171 /// Information about the private hop communicated via BOLT 11.
1173 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1174 pub hint: &'a RouteHintHop,
1175 /// Node id of the next hop in BOLT 11 route hint.
1177 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1178 pub target_node_id: &'a NodeId
1181 /// A [`CandidateRouteHop::Blinded`] entry.
1182 #[derive(Clone, Debug)]
1183 pub struct BlindedPathCandidate<'a> {
1184 /// Information about the blinded path including the fee, HTLC amount limits, and
1185 /// cryptographic material required to build an HTLC through the given path.
1187 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1188 pub hint: &'a (BlindedPayInfo, BlindedPath),
1189 /// Index of the hint in the original list of blinded hints.
1191 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1192 /// a short channel ID for this hop.
1196 /// A [`CandidateRouteHop::OneHopBlinded`] entry.
1197 #[derive(Clone, Debug)]
1198 pub struct OneHopBlindedPathCandidate<'a> {
1199 /// Information about the blinded path including the fee, HTLC amount limits, and
1200 /// cryptographic material required to build an HTLC terminating with the given path.
1202 /// Note that the [`BlindedPayInfo`] is ignored here.
1204 /// This is not exported to bindings users as lifetimes are not expressable in most languages.
1205 pub hint: &'a (BlindedPayInfo, BlindedPath),
1206 /// Index of the hint in the original list of blinded hints.
1208 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1209 /// a short channel ID for this hop.
1213 /// A wrapper around the various hop representations.
1215 /// Can be used to examine the properties of a hop,
1216 /// potentially to decide whether to include it in a route.
1217 #[derive(Clone, Debug)]
1218 pub enum CandidateRouteHop<'a> {
1219 /// A hop from the payer, where the outbound liquidity is known.
1220 FirstHop(FirstHopCandidate<'a>),
1221 /// A hop found in the [`ReadOnlyNetworkGraph`].
1222 PublicHop(PublicHopCandidate<'a>),
1223 /// A private hop communicated by the payee, generally via a BOLT 11 invoice.
1225 /// Because BOLT 11 route hints can take multiple hops to get to the destination, this may not
1226 /// terminate at the payee.
1227 PrivateHop(PrivateHopCandidate<'a>),
1228 /// A blinded path which starts with an introduction point and ultimately terminates with the
1231 /// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1232 /// `None` in this state.
1234 /// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1235 /// path, the full path is treated as a single [`CandidateRouteHop`].
1236 Blinded(BlindedPathCandidate<'a>),
1237 /// Similar to [`Self::Blinded`], but the path here only has one hop.
1239 /// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1240 /// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1241 /// payee's identity - it's the introduction point!
1243 /// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1244 /// to the hops *between* the introduction node and the destination.
1246 /// This primarily exists to track that we need to included a blinded path at the end of our
1247 /// [`Route`], even though it doesn't actually add an additional hop in the payment.
1248 OneHopBlinded(OneHopBlindedPathCandidate<'a>),
1251 impl<'a> CandidateRouteHop<'a> {
1252 /// Returns the short channel ID for this hop, if one is known.
1254 /// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1255 /// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1257 /// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1258 /// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1259 /// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1260 /// (which is always true for channels which are funded and ready for use).
1262 /// In other words, this should always return `Some` as long as the candidate hop is not a
1263 /// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1265 /// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1266 /// define a global namespace.
1268 fn short_channel_id(&self) -> Option<u64> {
1270 CandidateRouteHop::FirstHop(hop) => hop.details.get_outbound_payment_scid(),
1271 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1272 CandidateRouteHop::PrivateHop(hop) => Some(hop.hint.short_channel_id),
1273 CandidateRouteHop::Blinded(_) => None,
1274 CandidateRouteHop::OneHopBlinded(_) => None,
1278 /// Returns the globally unique short channel ID for this hop, if one is known.
1280 /// This only returns `Some` if the channel is public (either our own, or one we've learned
1281 /// from the public network graph), and thus the short channel ID we have for this channel is
1282 /// globally unique and identifies this channel in a global namespace.
1284 pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1286 CandidateRouteHop::FirstHop(hop) => if hop.details.is_public { hop.details.short_channel_id } else { None },
1287 CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1288 CandidateRouteHop::PrivateHop(_) => None,
1289 CandidateRouteHop::Blinded(_) => None,
1290 CandidateRouteHop::OneHopBlinded(_) => None,
1294 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1295 fn features(&self) -> ChannelFeatures {
1297 CandidateRouteHop::FirstHop(hop) => hop.details.counterparty.features.to_context(),
1298 CandidateRouteHop::PublicHop(hop) => hop.info.channel().features.clone(),
1299 CandidateRouteHop::PrivateHop(_) => ChannelFeatures::empty(),
1300 CandidateRouteHop::Blinded(_) => ChannelFeatures::empty(),
1301 CandidateRouteHop::OneHopBlinded(_) => ChannelFeatures::empty(),
1305 /// Returns the required difference in HTLC CLTV expiry between the [`Self::source`] and the
1306 /// next-hop for an HTLC taking this hop.
1308 /// This is the time that the node(s) in this hop have to claim the HTLC on-chain if the
1309 /// next-hop goes on chain with a payment preimage.
1311 pub fn cltv_expiry_delta(&self) -> u32 {
1313 CandidateRouteHop::FirstHop(_) => 0,
1314 CandidateRouteHop::PublicHop(hop) => hop.info.direction().cltv_expiry_delta as u32,
1315 CandidateRouteHop::PrivateHop(hop) => hop.hint.cltv_expiry_delta as u32,
1316 CandidateRouteHop::Blinded(hop) => hop.hint.0.cltv_expiry_delta as u32,
1317 CandidateRouteHop::OneHopBlinded(_) => 0,
1321 /// Returns the minimum amount that can be sent over this hop, in millisatoshis.
1323 pub fn htlc_minimum_msat(&self) -> u64 {
1325 CandidateRouteHop::FirstHop(hop) => hop.details.next_outbound_htlc_minimum_msat,
1326 CandidateRouteHop::PublicHop(hop) => hop.info.direction().htlc_minimum_msat,
1327 CandidateRouteHop::PrivateHop(hop) => hop.hint.htlc_minimum_msat.unwrap_or(0),
1328 CandidateRouteHop::Blinded(hop) => hop.hint.0.htlc_minimum_msat,
1329 CandidateRouteHop::OneHopBlinded { .. } => 0,
1333 /// Returns the fees that must be paid to route an HTLC over this channel.
1335 pub fn fees(&self) -> RoutingFees {
1337 CandidateRouteHop::FirstHop(_) => RoutingFees {
1338 base_msat: 0, proportional_millionths: 0,
1340 CandidateRouteHop::PublicHop(hop) => hop.info.direction().fees,
1341 CandidateRouteHop::PrivateHop(hop) => hop.hint.fees,
1342 CandidateRouteHop::Blinded(hop) => {
1344 base_msat: hop.hint.0.fee_base_msat,
1345 proportional_millionths: hop.hint.0.fee_proportional_millionths
1348 CandidateRouteHop::OneHopBlinded(_) =>
1349 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1353 /// Fetch the effective capacity of this hop.
1355 /// Note that this may be somewhat expensive, so calls to this should be limited and results
1357 fn effective_capacity(&self) -> EffectiveCapacity {
1359 CandidateRouteHop::FirstHop(hop) => EffectiveCapacity::ExactLiquidity {
1360 liquidity_msat: hop.details.next_outbound_htlc_limit_msat,
1362 CandidateRouteHop::PublicHop(hop) => hop.info.effective_capacity(),
1363 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. }) =>
1364 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1365 CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. }) =>
1366 EffectiveCapacity::Infinite,
1367 CandidateRouteHop::Blinded(hop) =>
1368 EffectiveCapacity::HintMaxHTLC { amount_msat: hop.hint.0.htlc_maximum_msat },
1369 CandidateRouteHop::OneHopBlinded(_) => EffectiveCapacity::Infinite,
1373 /// Returns an ID describing the given hop.
1375 /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1377 fn id(&self) -> CandidateHopId {
1379 CandidateRouteHop::Blinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1380 CandidateRouteHop::OneHopBlinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1381 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1384 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1386 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1392 fn blinded_hint_idx(&self) -> Option<usize> {
1394 Self::Blinded(BlindedPathCandidate { hint_idx, .. }) |
1395 Self::OneHopBlinded(OneHopBlindedPathCandidate { hint_idx, .. }) => {
1401 /// Returns the source node id of current hop.
1403 /// Source node id refers to the node forwarding the HTLC through this hop.
1405 /// For [`Self::FirstHop`] we return payer's node id.
1407 pub fn source(&self) -> NodeId {
1409 CandidateRouteHop::FirstHop(hop) => *hop.payer_node_id,
1410 CandidateRouteHop::PublicHop(hop) => *hop.info.source(),
1411 CandidateRouteHop::PrivateHop(hop) => hop.hint.src_node_id.into(),
1412 CandidateRouteHop::Blinded(hop) => hop.hint.1.introduction_node_id.into(),
1413 CandidateRouteHop::OneHopBlinded(hop) => hop.hint.1.introduction_node_id.into(),
1416 /// Returns the target node id of this hop, if known.
1418 /// Target node id refers to the node receiving the HTLC after this hop.
1420 /// For [`Self::Blinded`] we return `None` because the ultimate destination after the blinded
1421 /// path is unknown.
1423 /// For [`Self::OneHopBlinded`] we return `None` because the target is the same as the source,
1424 /// and such a return value would be somewhat nonsensical.
1426 pub fn target(&self) -> Option<NodeId> {
1428 CandidateRouteHop::FirstHop(hop) => Some(hop.details.counterparty.node_id.into()),
1429 CandidateRouteHop::PublicHop(hop) => Some(*hop.info.target()),
1430 CandidateRouteHop::PrivateHop(hop) => Some(*hop.target_node_id),
1431 CandidateRouteHop::Blinded(_) => None,
1432 CandidateRouteHop::OneHopBlinded(_) => None,
1437 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1439 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1441 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1442 /// isn't guaranteed to be unique at all.
1444 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1445 /// difficult-to-use API.
1446 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1447 enum CandidateHopId {
1448 /// Contains (scid, src_node_id < target_node_id)
1450 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1455 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1456 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1458 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1459 EffectiveCapacity::Infinite => u64::max_value(),
1460 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1461 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1462 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1463 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1464 // expected to have been generated from up-to-date capacity information.
1465 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1466 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1467 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1471 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1472 -> bool where I1::Item: PartialEq<I2::Item> {
1474 let a = iter_a.next();
1475 let b = iter_b.next();
1476 if a.is_none() && b.is_none() { return true; }
1477 if a.is_none() || b.is_none() { return false; }
1478 if a.unwrap().ne(&b.unwrap()) { return false; }
1482 /// It's useful to keep track of the hops associated with the fees required to use them,
1483 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1484 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1485 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1487 #[repr(C)] // Force fields to appear in the order we define them.
1488 struct PathBuildingHop<'a> {
1489 candidate: CandidateRouteHop<'a>,
1490 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1491 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1492 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1493 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1494 /// avoid processing them again.
1495 was_processed: bool,
1496 /// Used to compare channels when choosing the for routing.
1497 /// Includes paying for the use of a hop and the following hops, as well as
1498 /// an estimated cost of reaching this hop.
1499 /// Might get stale when fees are recomputed. Primarily for internal use.
1500 total_fee_msat: u64,
1501 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1502 /// walk and may be invalid thereafter.
1503 path_htlc_minimum_msat: u64,
1504 /// All penalties incurred from this channel on the way to the destination, as calculated using
1505 /// channel scoring.
1506 path_penalty_msat: u64,
1508 // The last 16 bytes are on the next cache line by default in glibc's malloc. Thus, we should
1509 // only place fields which are not hot there. Luckily, the next three fields are only read if
1510 // we end up on the selected path, and only in the final path layout phase, so we don't care
1511 // too much if reading them is slow.
1515 /// All the fees paid *after* this channel on the way to the destination
1516 next_hops_fee_msat: u64,
1517 /// Fee paid for the use of the current channel (see candidate.fees()).
1518 /// The value will be actually deducted from the counterparty balance on the previous link.
1519 hop_use_fee_msat: u64,
1521 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1522 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1523 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1524 // value_contribution_msat, which requires tracking it here. See comments below where it is
1525 // used for more info.
1526 value_contribution_msat: u64,
1529 // Checks that the entries in the `find_route` `dist` map fit in (exactly) two standard x86-64
1530 // cache lines. Sadly, they're not guaranteed to actually lie on a cache line (and in fact,
1531 // generally won't, because at least glibc's malloc will align to a nice, big, round
1532 // boundary...plus 16), but at least it will reduce the amount of data we'll need to load.
1534 // Note that these assertions only pass on somewhat recent rustc, and thus are gated on the
1537 const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::<(NodeId, PathBuildingHop)>();
1539 const _NODE_MAP_SIZE_EXACTLY_CACHE_LINES: usize = core::mem::size_of::<(NodeId, PathBuildingHop)>() - 128;
1541 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1542 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1543 let mut debug_struct = f.debug_struct("PathBuildingHop");
1545 .field("node_id", &self.candidate.target())
1546 .field("short_channel_id", &self.candidate.short_channel_id())
1547 .field("total_fee_msat", &self.total_fee_msat)
1548 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1549 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1550 .field("total_fee_msat - (next_hops_fee_msat + hop_use_fee_msat)", &(&self.total_fee_msat - (&self.next_hops_fee_msat + &self.hop_use_fee_msat)))
1551 .field("path_penalty_msat", &self.path_penalty_msat)
1552 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1553 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1554 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1555 let debug_struct = debug_struct
1556 .field("value_contribution_msat", &self.value_contribution_msat);
1557 debug_struct.finish()
1561 // Instantiated with a list of hops with correct data in them collected during path finding,
1562 // an instance of this struct should be further modified only via given methods.
1564 struct PaymentPath<'a> {
1565 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1568 impl<'a> PaymentPath<'a> {
1569 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1570 fn get_value_msat(&self) -> u64 {
1571 self.hops.last().unwrap().0.fee_msat
1574 fn get_path_penalty_msat(&self) -> u64 {
1575 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1578 fn get_total_fee_paid_msat(&self) -> u64 {
1579 if self.hops.len() < 1 {
1583 // Can't use next_hops_fee_msat because it gets outdated.
1584 for (i, (hop, _)) in self.hops.iter().enumerate() {
1585 if i != self.hops.len() - 1 {
1586 result += hop.fee_msat;
1592 fn get_cost_msat(&self) -> u64 {
1593 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1596 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1597 // to change fees may result in an inconsistency.
1599 // Sometimes we call this function right after constructing a path which is inconsistent in
1600 // that it the value being transferred has decreased while we were doing path finding, leading
1601 // to the fees being paid not lining up with the actual limits.
1603 // Note that this function is not aware of the available_liquidity limit, and thus does not
1604 // support increasing the value being transferred beyond what was selected during the initial
1607 // Returns the amount that this path contributes to the total payment value, which may be greater
1608 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1609 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1610 let mut extra_contribution_msat = 0;
1611 let mut total_fee_paid_msat = 0 as u64;
1612 for i in (0..self.hops.len()).rev() {
1613 let last_hop = i == self.hops.len() - 1;
1615 // For non-last-hop, this value will represent the fees paid on the current hop. It
1616 // will consist of the fees for the use of the next hop, and extra fees to match
1617 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1618 let mut cur_hop_fees_msat = 0;
1620 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1623 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1624 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1625 cur_hop.path_penalty_msat += extra_contribution_msat;
1626 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1627 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1628 // set it too high just to maliciously take more fees by exploiting this
1629 // match htlc_minimum_msat logic.
1630 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1631 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1632 // Note that there is a risk that *previous hops* (those closer to us, as we go
1633 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1635 // This might make us end up with a broken route, although this should be super-rare
1636 // in practice, both because of how healthy channels look like, and how we pick
1637 // channels in add_entry.
1638 // Also, this can't be exploited more heavily than *announce a free path and fail
1640 cur_hop_transferred_amount_msat += extra_fees_msat;
1642 // We remember and return the extra fees on the final hop to allow accounting for
1643 // them in the path's value contribution.
1645 extra_contribution_msat = extra_fees_msat;
1647 total_fee_paid_msat += extra_fees_msat;
1648 cur_hop_fees_msat += extra_fees_msat;
1653 // Final hop is a special case: it usually has just value_msat (by design), but also
1654 // it still could overpay for the htlc_minimum_msat.
1655 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1657 // Propagate updated fees for the use of the channels to one hop back, where they
1658 // will be actually paid (fee_msat). The last hop is handled above separately.
1659 cur_hop.fee_msat = cur_hop_fees_msat;
1662 // Fee for the use of the current hop which will be deducted on the previous hop.
1663 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1664 // this channel is free for us.
1666 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1667 cur_hop.hop_use_fee_msat = new_fee;
1668 total_fee_paid_msat += new_fee;
1670 // It should not be possible because this function is called only to reduce the
1671 // value. In that case, compute_fee was already called with the same fees for
1672 // larger amount and there was no overflow.
1677 value_msat + extra_contribution_msat
1682 /// Calculate the fees required to route the given amount over a channel with the given fees.
1683 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1684 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1685 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1689 /// Calculate the fees required to route the given amount over a channel with the given fees,
1690 /// saturating to [`u64::max_value`].
1691 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1692 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1693 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1694 .saturating_add(channel_fees.base_msat as u64)
1697 /// The default `features` we assume for a node in a route, when no `features` are known about that
1700 /// Default features are:
1701 /// * variable_length_onion_optional
1702 fn default_node_features() -> NodeFeatures {
1703 let mut features = NodeFeatures::empty();
1704 features.set_variable_length_onion_optional();
1708 struct LoggedPayeePubkey(Option<PublicKey>);
1709 impl fmt::Display for LoggedPayeePubkey {
1710 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1713 "payee node id ".fmt(f)?;
1717 "blinded payee".fmt(f)
1723 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1724 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1725 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1727 CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1728 "blinded route hint with introduction node id ".fmt(f)?;
1729 hint.1.introduction_node_id.fmt(f)?;
1730 " and blinding point ".fmt(f)?;
1731 hint.1.blinding_point.fmt(f)
1733 CandidateRouteHop::FirstHop(_) => {
1734 "first hop with SCID ".fmt(f)?;
1735 self.0.short_channel_id().unwrap().fmt(f)
1737 CandidateRouteHop::PrivateHop(_) => {
1738 "route hint with SCID ".fmt(f)?;
1739 self.0.short_channel_id().unwrap().fmt(f)
1743 self.0.short_channel_id().unwrap().fmt(f)
1750 fn sort_first_hop_channels(
1751 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1752 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1754 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1755 // most like to use.
1757 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1758 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1761 // Second, because simply always sorting in descending order would always use our largest
1762 // available outbound capacity, needlessly fragmenting our available channel capacities,
1763 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1764 // which have enough, but not too much, capacity for the payment.
1766 // Available outbound balances factor in liquidity already reserved for previously found paths.
1767 channels.sort_unstable_by(|chan_a, chan_b| {
1768 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1769 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1770 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1771 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1772 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1773 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1774 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1775 // Sort in descending order
1776 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1778 // Sort in ascending order
1779 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1784 /// Finds a route from us (payer) to the given target node (payee).
1786 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1787 /// in the given [`RouteParameters::payment_params`].
1788 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1790 /// Private routing paths between a public node and the target may be included in the `payee` field
1791 /// of [`RouteParameters::payment_params`].
1793 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1794 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1795 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1797 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1798 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1799 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1803 /// Panics if first_hops contains channels without `short_channel_id`s;
1804 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1806 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1807 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1808 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1809 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1810 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1811 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1812 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1813 ) -> Result<Route, LightningError>
1814 where L::Target: Logger, GL::Target: Logger {
1815 let graph_lock = network_graph.read_only();
1816 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1817 scorer, score_params, random_seed_bytes)?;
1818 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1822 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1823 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1824 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1825 _random_seed_bytes: &[u8; 32]
1826 ) -> Result<Route, LightningError>
1827 where L::Target: Logger {
1829 let payment_params = &route_params.payment_params;
1830 let final_value_msat = route_params.final_value_msat;
1831 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1832 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1833 // so use a dummy id for this in the blinded case.
1834 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1835 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1836 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1837 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1838 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1840 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1841 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1843 if our_node_id == maybe_dummy_payee_node_id {
1844 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1847 if final_value_msat > MAX_VALUE_MSAT {
1848 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1851 if final_value_msat == 0 {
1852 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1855 match &payment_params.payee {
1856 Payee::Clear { route_hints, node_id, .. } => {
1857 for route in route_hints.iter() {
1858 for hop in &route.0 {
1859 if hop.src_node_id == *node_id {
1860 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1865 Payee::Blinded { route_hints, .. } => {
1866 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1867 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});
1869 for (_, blinded_path) in route_hints.iter() {
1870 if blinded_path.blinded_hops.len() == 0 {
1871 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1872 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1873 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1874 } else if blinded_path.blinded_hops.len() == 1 &&
1875 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1876 && p.introduction_node_id != blinded_path.introduction_node_id)
1878 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1883 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1884 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1885 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});
1888 // The general routing idea is the following:
1889 // 1. Fill first/last hops communicated by the caller.
1890 // 2. Attempt to construct a path from payer to payee for transferring
1891 // any ~sufficient (described later) value.
1892 // If succeed, remember which channels were used and how much liquidity they have available,
1893 // so that future paths don't rely on the same liquidity.
1894 // 3. Proceed to the next step if:
1895 // - we hit the recommended target value;
1896 // - OR if we could not construct a new path. Any next attempt will fail too.
1897 // Otherwise, repeat step 2.
1898 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1899 // (not recommended value).
1900 // 5. If yes, proceed. If not, fail routing.
1901 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1902 // transferred up to the transfer target value.
1903 // 7. Reduce the value of the last path until we are sending only the target value.
1904 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1905 // them so that we're not sending two HTLCs along the same path.
1907 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1908 // distance from the payee
1910 // We are not a faithful Dijkstra's implementation because we can change values which impact
1911 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1912 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1913 // the value we are currently attempting to send over a path, we simply reduce the value being
1914 // sent along the path for any hops after that channel. This may imply that later fees (which
1915 // we've already tabulated) are lower because a smaller value is passing through the channels
1916 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1917 // channels which were selected earlier (and which may still be used for other paths without a
1918 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1921 // One potentially problematic case for this algorithm would be if there are many
1922 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1923 // graph walking), we may never find a path which is not liquidity-limited and has lower
1924 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1925 // Because we only consider paths with at least 5% of the total value being sent, the damage
1926 // from such a case should be limited, however this could be further reduced in the future by
1927 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1928 // limits for the purposes of fee calculation.
1930 // Alternatively, we could store more detailed path information in the heap (targets, below)
1931 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1932 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1933 // and practically (as we would need to store dynamically-allocated path information in heap
1934 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1935 // results of such an algorithm would likely be biased towards lower-value paths.
1937 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1938 // outside of our current search value, running a path search more times to gather candidate
1939 // paths at different values. While this may be acceptable, further path searches may increase
1940 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1941 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1942 // the same time, remaining generic across different payment values.
1944 let network_channels = network_graph.channels();
1945 let network_nodes = network_graph.nodes();
1947 if payment_params.max_path_count == 0 {
1948 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1951 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1952 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1954 let allow_mpp = if payment_params.max_path_count == 1 {
1956 } else if payment_params.payee.supports_basic_mpp() {
1958 } else if let Some(payee) = payee_node_id_opt {
1959 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1960 |info| info.features.supports_basic_mpp()))
1963 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1965 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph with a fee limit of {} msat",
1966 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
1967 if allow_mpp { "with" } else { "without" },
1968 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " },
1969 max_total_routing_fee_msat);
1972 // Prepare the data we'll use for payee-to-payer search by
1973 // inserting first hops suggested by the caller as targets.
1974 // Our search will then attempt to reach them while traversing from the payee node.
1975 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1976 hash_map_with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1977 if let Some(hops) = first_hops {
1979 if chan.get_outbound_payment_scid().is_none() {
1980 panic!("first_hops should be filled in with usable channels, not pending ones");
1982 if chan.counterparty.node_id == *our_node_pubkey {
1983 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1986 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1987 .or_insert(Vec::new())
1990 if first_hop_targets.is_empty() {
1991 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1995 let mut private_hop_key_cache = hash_map_with_capacity(
1996 payment_params.payee.unblinded_route_hints().iter().map(|path| path.0.len()).sum()
1999 // Because we store references to private hop node_ids in `dist`, below, we need them to exist
2000 // (as `NodeId`, not `PublicKey`) for the lifetime of `dist`. Thus, we calculate all the keys
2001 // we'll need here and simply fetch them when routing.
2002 private_hop_key_cache.insert(maybe_dummy_payee_pk, NodeId::from_pubkey(&maybe_dummy_payee_pk));
2003 for route in payment_params.payee.unblinded_route_hints().iter() {
2004 for hop in route.0.iter() {
2005 private_hop_key_cache.insert(hop.src_node_id, NodeId::from_pubkey(&hop.src_node_id));
2009 // The main heap containing all candidate next-hops sorted by their score (max(fee,
2010 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
2011 // adding duplicate entries when we find a better path to a given node.
2012 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
2014 // Map from node_id to information about the best current path to that node, including feerate
2016 let mut dist: HashMap<NodeId, PathBuildingHop> = hash_map_with_capacity(network_nodes.len());
2018 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
2019 // indicating that we may wish to try again with a higher value, potentially paying to meet an
2020 // htlc_minimum with extra fees while still finding a cheaper path.
2021 let mut hit_minimum_limit;
2023 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
2024 // We start with a path_value of the exact amount we want, and if that generates a route we may
2025 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
2026 // amount we want in total across paths, selecting the best subset at the end.
2027 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
2028 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
2029 let mut path_value_msat = final_value_msat;
2031 // Routing Fragmentation Mitigation heuristic:
2033 // Routing fragmentation across many payment paths increases the overall routing
2034 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
2035 // Taking too many smaller paths also increases the chance of payment failure.
2036 // Thus to avoid this effect, we require from our collected links to provide
2037 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
2038 // This requirement is currently set to be 1/max_path_count of the payment
2039 // value to ensure we only ever return routes that do not violate this limit.
2040 let minimal_value_contribution_msat: u64 = if allow_mpp {
2041 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
2046 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
2047 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
2048 // drop the requirement by setting this to 0.
2049 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
2051 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
2052 // determine if the channel can be used by additional MPP paths or to inform path finding
2053 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
2054 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
2056 let mut used_liquidities: HashMap<CandidateHopId, u64> =
2057 hash_map_with_capacity(network_nodes.len());
2059 // Keeping track of how much value we already collected across other paths. Helps to decide
2060 // when we want to stop looking for new paths.
2061 let mut already_collected_value_msat = 0;
2063 for (_, channels) in first_hop_targets.iter_mut() {
2064 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
2068 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
2069 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
2071 // Remember how many candidates we ignored to allow for some logging afterwards.
2072 let mut num_ignored_value_contribution: u32 = 0;
2073 let mut num_ignored_path_length_limit: u32 = 0;
2074 let mut num_ignored_cltv_delta_limit: u32 = 0;
2075 let mut num_ignored_previously_failed: u32 = 0;
2076 let mut num_ignored_total_fee_limit: u32 = 0;
2077 let mut num_ignored_avoid_overpayment: u32 = 0;
2078 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
2080 macro_rules! add_entry {
2081 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
2082 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
2083 // since that value has to be transferred over this channel.
2084 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
2085 ( $candidate: expr, $next_hops_fee_msat: expr,
2086 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
2087 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
2088 // We "return" whether we updated the path at the end, and how much we can route via
2089 // this channel, via this:
2090 let mut hop_contribution_amt_msat = None;
2091 // Channels to self should not be used. This is more of belt-and-suspenders, because in
2092 // practice these cases should be caught earlier:
2093 // - for regular channels at channel announcement (TODO)
2094 // - for first and last hops early in get_route
2095 let src_node_id = $candidate.source();
2096 if Some(src_node_id) != $candidate.target() {
2097 let scid_opt = $candidate.short_channel_id();
2098 let effective_capacity = $candidate.effective_capacity();
2099 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
2101 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
2102 // It may be misleading because we might later choose to reduce the value transferred
2103 // over these channels, and the channel which was insufficient might become sufficient.
2104 // Worst case: we drop a good channel here because it can't cover the high following
2105 // fees caused by one expensive channel, but then this channel could have been used
2106 // if the amount being transferred over this path is lower.
2107 // We do this for now, but this is a subject for removal.
2108 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
2109 let used_liquidity_msat = used_liquidities
2110 .get(&$candidate.id())
2111 .map_or(0, |used_liquidity_msat| {
2112 available_value_contribution_msat = available_value_contribution_msat
2113 .saturating_sub(*used_liquidity_msat);
2114 *used_liquidity_msat
2117 // Verify the liquidity offered by this channel complies to the minimal contribution.
2118 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
2119 // Do not consider candidate hops that would exceed the maximum path length.
2120 let path_length_to_node = $next_hops_path_length + 1;
2121 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
2123 // Do not consider candidates that exceed the maximum total cltv expiry limit.
2124 // In order to already account for some of the privacy enhancing random CLTV
2125 // expiry delta offset we add on top later, we subtract a rough estimate
2126 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
2127 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
2128 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
2129 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
2130 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
2131 .saturating_add($candidate.cltv_expiry_delta());
2132 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
2134 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
2135 // Includes paying fees for the use of the following channels.
2136 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
2137 Some(result) => result,
2138 // Can't overflow due to how the values were computed right above.
2139 None => unreachable!(),
2141 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2142 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
2143 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
2145 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2146 let may_overpay_to_meet_path_minimum_msat =
2147 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
2148 recommended_value_msat >= $candidate.htlc_minimum_msat()) ||
2149 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
2150 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
2152 let payment_failed_on_this_channel = match scid_opt {
2153 Some(scid) => payment_params.previously_failed_channels.contains(&scid),
2154 None => match $candidate.blinded_hint_idx() {
2156 payment_params.previously_failed_blinded_path_idxs.contains(&(idx as u64))
2162 let (should_log_candidate, first_hop_details) = match $candidate {
2163 CandidateRouteHop::FirstHop(hop) => (true, Some(hop.details)),
2164 CandidateRouteHop::PrivateHop(_) => (true, None),
2165 CandidateRouteHop::Blinded(_) => (true, None),
2166 CandidateRouteHop::OneHopBlinded(_) => (true, None),
2170 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
2171 // bother considering this channel. If retrying with recommended_value_msat may
2172 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
2173 // around again with a higher amount.
2174 if !contributes_sufficient_value {
2175 if should_log_candidate {
2176 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
2178 if let Some(details) = first_hop_details {
2180 "First hop candidate next_outbound_htlc_limit_msat: {}",
2181 details.next_outbound_htlc_limit_msat,
2185 num_ignored_value_contribution += 1;
2186 } else if exceeds_max_path_length {
2187 if should_log_candidate {
2188 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
2190 num_ignored_path_length_limit += 1;
2191 } else if exceeds_cltv_delta_limit {
2192 if should_log_candidate {
2193 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
2195 if let Some(_) = first_hop_details {
2197 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
2198 hop_total_cltv_delta,
2199 max_total_cltv_expiry_delta,
2203 num_ignored_cltv_delta_limit += 1;
2204 } else if payment_failed_on_this_channel {
2205 if should_log_candidate {
2206 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
2208 num_ignored_previously_failed += 1;
2209 } else if may_overpay_to_meet_path_minimum_msat {
2210 if should_log_candidate {
2212 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit.",
2213 LoggedCandidateHop(&$candidate));
2215 if let Some(details) = first_hop_details {
2217 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2218 details.next_outbound_htlc_minimum_msat,
2222 num_ignored_avoid_overpayment += 1;
2223 hit_minimum_limit = true;
2224 } else if over_path_minimum_msat {
2225 // Note that low contribution here (limited by available_liquidity_msat)
2226 // might violate htlc_minimum_msat on the hops which are next along the
2227 // payment path (upstream to the payee). To avoid that, we recompute
2228 // path fees knowing the final path contribution after constructing it.
2229 let curr_min = cmp::max(
2230 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
2232 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
2233 .saturating_add(curr_min);
2234 let hm_entry = dist.entry(src_node_id);
2235 let old_entry = hm_entry.or_insert_with(|| {
2236 // If there was previously no known way to access the source node
2237 // (recall it goes payee-to-payer) of short_channel_id, first add a
2238 // semi-dummy record just to compute the fees to reach the source node.
2239 // This will affect our decision on selecting short_channel_id
2240 // as a way to reach the $candidate.target() node.
2242 candidate: $candidate.clone(),
2244 next_hops_fee_msat: u64::max_value(),
2245 hop_use_fee_msat: u64::max_value(),
2246 total_fee_msat: u64::max_value(),
2247 path_htlc_minimum_msat,
2248 path_penalty_msat: u64::max_value(),
2249 was_processed: false,
2250 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2251 value_contribution_msat,
2255 #[allow(unused_mut)] // We only use the mut in cfg(test)
2256 let mut should_process = !old_entry.was_processed;
2257 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2259 // In test/fuzzing builds, we do extra checks to make sure the skipping
2260 // of already-seen nodes only happens in cases we expect (see below).
2261 if !should_process { should_process = true; }
2265 let mut hop_use_fee_msat = 0;
2266 let mut total_fee_msat: u64 = $next_hops_fee_msat;
2268 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2269 // will have the same effective-fee
2270 if src_node_id != our_node_id {
2271 // Note that `u64::max_value` means we'll always fail the
2272 // `old_entry.total_fee_msat > total_fee_msat` check below
2273 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
2274 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2277 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2278 if total_fee_msat > max_total_routing_fee_msat {
2279 if should_log_candidate {
2280 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2282 if let Some(_) = first_hop_details {
2284 "First hop candidate routing fee: {}. Limit: {}",
2286 max_total_routing_fee_msat,
2290 num_ignored_total_fee_limit += 1;
2292 let channel_usage = ChannelUsage {
2293 amount_msat: amount_to_transfer_over_msat,
2294 inflight_htlc_msat: used_liquidity_msat,
2297 let channel_penalty_msat =
2298 scorer.channel_penalty_msat($candidate,
2301 let path_penalty_msat = $next_hops_path_penalty_msat
2302 .saturating_add(channel_penalty_msat);
2304 // Update the way of reaching $candidate.source()
2305 // with the given short_channel_id (from $candidate.target()),
2306 // if this way is cheaper than the already known
2307 // (considering the cost to "reach" this channel from the route destination,
2308 // the cost of using this channel,
2309 // and the cost of routing to the source node of this channel).
2310 // Also, consider that htlc_minimum_msat_difference, because we might end up
2311 // paying it. Consider the following exploit:
2312 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2313 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2314 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2315 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2317 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2318 // but it may require additional tracking - we don't want to double-count
2319 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2320 // can't use something that may decrease on future hops.
2321 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2322 .saturating_add(old_entry.path_penalty_msat);
2323 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2324 .saturating_add(path_penalty_msat);
2326 if !old_entry.was_processed && new_cost < old_cost {
2327 let new_graph_node = RouteGraphNode {
2328 node_id: src_node_id,
2329 score: cmp::max(total_fee_msat, path_htlc_minimum_msat).saturating_add(path_penalty_msat),
2330 total_cltv_delta: hop_total_cltv_delta,
2331 value_contribution_msat,
2332 path_length_to_node,
2334 targets.push(new_graph_node);
2335 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2336 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2337 old_entry.total_fee_msat = total_fee_msat;
2338 old_entry.candidate = $candidate.clone();
2339 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2340 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2341 old_entry.path_penalty_msat = path_penalty_msat;
2342 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2344 old_entry.value_contribution_msat = value_contribution_msat;
2346 hop_contribution_amt_msat = Some(value_contribution_msat);
2347 } else if old_entry.was_processed && new_cost < old_cost {
2348 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2350 // If we're skipping processing a node which was previously
2351 // processed even though we found another path to it with a
2352 // cheaper fee, check that it was because the second path we
2353 // found (which we are processing now) has a lower value
2354 // contribution due to an HTLC minimum limit.
2356 // e.g. take a graph with two paths from node 1 to node 2, one
2357 // through channel A, and one through channel B. Channel A and
2358 // B are both in the to-process heap, with their scores set by
2359 // a higher htlc_minimum than fee.
2360 // Channel A is processed first, and the channels onwards from
2361 // node 1 are added to the to-process heap. Thereafter, we pop
2362 // Channel B off of the heap, note that it has a much more
2363 // restrictive htlc_maximum_msat, and recalculate the fees for
2364 // all of node 1's channels using the new, reduced, amount.
2366 // This would be bogus - we'd be selecting a higher-fee path
2367 // with a lower htlc_maximum_msat instead of the one we'd
2368 // already decided to use.
2369 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2371 value_contribution_msat + path_penalty_msat <
2372 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2379 if should_log_candidate {
2381 "Ignoring {} due to its htlc_minimum_msat limit.",
2382 LoggedCandidateHop(&$candidate));
2384 if let Some(details) = first_hop_details {
2386 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2387 details.next_outbound_htlc_minimum_msat,
2391 num_ignored_htlc_minimum_msat_limit += 1;
2395 hop_contribution_amt_msat
2399 let default_node_features = default_node_features();
2401 // Find ways (channels with destination) to reach a given node and store them
2402 // in the corresponding data structures (routing graph etc).
2403 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2404 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2405 // This data can later be helpful to optimize routing (pay lower fees).
2406 macro_rules! add_entries_to_cheapest_to_target_node {
2407 ( $node: expr, $node_id: expr, $next_hops_value_contribution: expr,
2408 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2409 let fee_to_target_msat;
2410 let next_hops_path_htlc_minimum_msat;
2411 let next_hops_path_penalty_msat;
2412 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
2413 let was_processed = elem.was_processed;
2414 elem.was_processed = true;
2415 fee_to_target_msat = elem.total_fee_msat;
2416 next_hops_path_htlc_minimum_msat = elem.path_htlc_minimum_msat;
2417 next_hops_path_penalty_msat = elem.path_penalty_msat;
2420 // Entries are added to dist in add_entry!() when there is a channel from a node.
2421 // Because there are no channels from payee, it will not have a dist entry at this point.
2422 // If we're processing any other node, it is always be the result of a channel from it.
2423 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2424 fee_to_target_msat = 0;
2425 next_hops_path_htlc_minimum_msat = 0;
2426 next_hops_path_penalty_msat = 0;
2431 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
2432 for details in first_channels {
2433 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2434 details, payer_node_id: &our_node_id,
2436 add_entry!(&candidate, fee_to_target_msat,
2437 $next_hops_value_contribution,
2438 next_hops_path_htlc_minimum_msat, next_hops_path_penalty_msat,
2439 $next_hops_cltv_delta, $next_hops_path_length);
2443 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2446 &default_node_features
2449 if !features.requires_unknown_bits() {
2450 for chan_id in $node.channels.iter() {
2451 let chan = network_channels.get(chan_id).unwrap();
2452 if !chan.features.requires_unknown_bits() {
2453 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2454 if first_hops.is_none() || *source != our_node_id {
2455 if directed_channel.direction().enabled {
2456 let candidate = CandidateRouteHop::PublicHop(PublicHopCandidate {
2457 info: directed_channel,
2458 short_channel_id: *chan_id,
2460 add_entry!(&candidate,
2462 $next_hops_value_contribution,
2463 next_hops_path_htlc_minimum_msat,
2464 next_hops_path_penalty_msat,
2465 $next_hops_cltv_delta, $next_hops_path_length);
2476 let mut payment_paths = Vec::<PaymentPath>::new();
2478 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2479 'paths_collection: loop {
2480 // For every new path, start from scratch, except for used_liquidities, which
2481 // helps to avoid reusing previously selected paths in future iterations.
2484 hit_minimum_limit = false;
2486 // If first hop is a private channel and the only way to reach the payee, this is the only
2487 // place where it could be added.
2488 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2489 for details in first_channels {
2490 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2491 details, payer_node_id: &our_node_id,
2493 let added = add_entry!(&candidate, 0, path_value_msat,
2494 0, 0u64, 0, 0).is_some();
2495 log_trace!(logger, "{} direct route to payee via {}",
2496 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2500 // Add the payee as a target, so that the payee-to-payer
2501 // search algorithm knows what to start with.
2502 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2503 // The payee is not in our network graph, so nothing to add here.
2504 // There is still a chance of reaching them via last_hops though,
2505 // so don't yet fail the payment here.
2506 // If not, targets.pop() will not even let us enter the loop in step 2.
2509 add_entries_to_cheapest_to_target_node!(node, payee, path_value_msat, 0, 0);
2514 // If a caller provided us with last hops, add them to routing targets. Since this happens
2515 // earlier than general path finding, they will be somewhat prioritized, although currently
2516 // it matters only if the fees are exactly the same.
2517 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2518 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2519 let have_intro_node_in_graph =
2520 // Only add the hops in this route to our candidate set if either
2521 // we have a direct channel to the first hop or the first hop is
2522 // in the regular network graph.
2523 first_hop_targets.get(&intro_node_id).is_some() ||
2524 network_nodes.get(&intro_node_id).is_some();
2525 if !have_intro_node_in_graph || our_node_id == intro_node_id { continue }
2526 let candidate = if hint.1.blinded_hops.len() == 1 {
2527 CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, hint_idx })
2528 } else { CandidateRouteHop::Blinded(BlindedPathCandidate { hint, hint_idx }) };
2529 let mut path_contribution_msat = path_value_msat;
2530 if let Some(hop_used_msat) = add_entry!(&candidate,
2531 0, path_contribution_msat, 0, 0_u64, 0, 0)
2533 path_contribution_msat = hop_used_msat;
2535 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2536 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2538 for details in first_channels {
2539 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2540 details, payer_node_id: &our_node_id,
2542 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2546 let path_min = candidate.htlc_minimum_msat().saturating_add(
2547 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2548 add_entry!(&first_hop_candidate, blinded_path_fee,
2549 path_contribution_msat, path_min, 0_u64, candidate.cltv_expiry_delta(),
2550 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2554 for route in payment_params.payee.unblinded_route_hints().iter()
2555 .filter(|route| !route.0.is_empty())
2557 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2558 let first_hop_src_is_reachable =
2559 // Only add the hops in this route to our candidate set if either we are part of
2560 // the first hop, we have a direct channel to the first hop, or the first hop is in
2561 // the regular network graph.
2562 our_node_id == first_hop_src_id ||
2563 first_hop_targets.get(&first_hop_src_id).is_some() ||
2564 network_nodes.get(&first_hop_src_id).is_some();
2565 if first_hop_src_is_reachable {
2566 // We start building the path from reverse, i.e., from payee
2567 // to the first RouteHintHop in the path.
2568 let hop_iter = route.0.iter().rev();
2569 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2570 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2571 let mut hop_used = true;
2572 let mut aggregate_next_hops_fee_msat: u64 = 0;
2573 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2574 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2575 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2576 let mut aggregate_next_hops_path_length: u8 = 0;
2577 let mut aggregate_path_contribution_msat = path_value_msat;
2579 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2580 let target = private_hop_key_cache.get(prev_hop_id).unwrap();
2582 if let Some(first_channels) = first_hop_targets.get(target) {
2583 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2584 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2585 hop.short_channel_id);
2590 let candidate = network_channels
2591 .get(&hop.short_channel_id)
2592 .and_then(|channel| channel.as_directed_to(target))
2593 .map(|(info, _)| CandidateRouteHop::PublicHop(PublicHopCandidate {
2595 short_channel_id: hop.short_channel_id,
2597 .unwrap_or_else(|| CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: hop, target_node_id: target }));
2599 if let Some(hop_used_msat) = add_entry!(&candidate,
2600 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2601 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2602 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2604 aggregate_path_contribution_msat = hop_used_msat;
2606 // If this hop was not used then there is no use checking the preceding
2607 // hops in the RouteHint. We can break by just searching for a direct
2608 // channel between last checked hop and first_hop_targets.
2612 let used_liquidity_msat = used_liquidities
2613 .get(&candidate.id()).copied()
2615 let channel_usage = ChannelUsage {
2616 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2617 inflight_htlc_msat: used_liquidity_msat,
2618 effective_capacity: candidate.effective_capacity(),
2620 let channel_penalty_msat = scorer.channel_penalty_msat(
2621 &candidate, channel_usage, score_params
2623 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2624 .saturating_add(channel_penalty_msat);
2626 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2627 .saturating_add(hop.cltv_expiry_delta as u32);
2629 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2632 // Searching for a direct channel between last checked hop and first_hop_targets
2633 if let Some(first_channels) = first_hop_targets.get_mut(target) {
2634 sort_first_hop_channels(first_channels, &used_liquidities,
2635 recommended_value_msat, our_node_pubkey);
2636 for details in first_channels {
2637 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2638 details, payer_node_id: &our_node_id,
2640 add_entry!(&first_hop_candidate,
2641 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2642 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2643 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2651 // In the next values of the iterator, the aggregate fees already reflects
2652 // the sum of value sent from payer (final_value_msat) and routing fees
2653 // for the last node in the RouteHint. We need to just add the fees to
2654 // route through the current node so that the preceding node (next iteration)
2656 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2657 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2658 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2660 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2661 // this route hint's source node to forward said min over this channel.
2662 aggregate_next_hops_path_htlc_minimum_msat = {
2663 let curr_htlc_min = cmp::max(
2664 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2666 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2667 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2670 if idx == route.0.len() - 1 {
2671 // The last hop in this iterator is the first hop in
2672 // overall RouteHint.
2673 // If this hop connects to a node with which we have a direct channel,
2674 // ignore the network graph and, if the last hop was added, add our
2675 // direct channel to the candidate set.
2677 // Note that we *must* check if the last hop was added as `add_entry`
2678 // always assumes that the third argument is a node to which we have a
2680 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2681 sort_first_hop_channels(first_channels, &used_liquidities,
2682 recommended_value_msat, our_node_pubkey);
2683 for details in first_channels {
2684 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2685 details, payer_node_id: &our_node_id,
2687 add_entry!(&first_hop_candidate,
2688 aggregate_next_hops_fee_msat,
2689 aggregate_path_contribution_msat,
2690 aggregate_next_hops_path_htlc_minimum_msat,
2691 aggregate_next_hops_path_penalty_msat,
2692 aggregate_next_hops_cltv_delta,
2693 aggregate_next_hops_path_length);
2701 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2703 // At this point, targets are filled with the data from first and
2704 // last hops communicated by the caller, and the payment receiver.
2705 let mut found_new_path = false;
2708 // If this loop terminates due the exhaustion of targets, two situations are possible:
2709 // - not enough outgoing liquidity:
2710 // 0 < already_collected_value_msat < final_value_msat
2711 // - enough outgoing liquidity:
2712 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2713 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2714 // paths_collection will be stopped because found_new_path==false.
2715 // This is not necessarily a routing failure.
2716 'path_construction: while let Some(RouteGraphNode { node_id, total_cltv_delta, mut value_contribution_msat, path_length_to_node, .. }) = targets.pop() {
2718 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2719 // traversing the graph and arrange the path out of what we found.
2720 if node_id == our_node_id {
2721 let mut new_entry = dist.remove(&our_node_id).unwrap();
2722 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2725 let mut features_set = false;
2726 let target = ordered_hops.last().unwrap().0.candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2727 if let Some(first_channels) = first_hop_targets.get(&target) {
2728 for details in first_channels {
2729 if let CandidateRouteHop::FirstHop(FirstHopCandidate { details: last_hop_details, .. })
2730 = ordered_hops.last().unwrap().0.candidate
2732 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2733 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2734 features_set = true;
2741 if let Some(node) = network_nodes.get(&target) {
2742 if let Some(node_info) = node.announcement_info.as_ref() {
2743 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2745 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2748 // We can fill in features for everything except hops which were
2749 // provided via the invoice we're paying. We could guess based on the
2750 // recipient's features but for now we simply avoid guessing at all.
2754 // Means we successfully traversed from the payer to the payee, now
2755 // save this path for the payment route. Also, update the liquidity
2756 // remaining on the used hops, so that we take them into account
2757 // while looking for more paths.
2758 if target == maybe_dummy_payee_node_id {
2762 new_entry = match dist.remove(&target) {
2763 Some(payment_hop) => payment_hop,
2764 // We can't arrive at None because, if we ever add an entry to targets,
2765 // we also fill in the entry in dist (see add_entry!).
2766 None => unreachable!(),
2768 // We "propagate" the fees one hop backward (topologically) here,
2769 // so that fees paid for a HTLC forwarding on the current channel are
2770 // associated with the previous channel (where they will be subtracted).
2771 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2772 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2774 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2775 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2777 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2778 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2780 let mut payment_path = PaymentPath {hops: ordered_hops};
2782 // We could have possibly constructed a slightly inconsistent path: since we reduce
2783 // value being transferred along the way, we could have violated htlc_minimum_msat
2784 // on some channels we already passed (assuming dest->source direction). Here, we
2785 // recompute the fees again, so that if that's the case, we match the currently
2786 // underpaid htlc_minimum_msat with fees.
2787 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2788 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2789 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2791 // Since a path allows to transfer as much value as
2792 // the smallest channel it has ("bottleneck"), we should recompute
2793 // the fees so sender HTLC don't overpay fees when traversing
2794 // larger channels than the bottleneck. This may happen because
2795 // when we were selecting those channels we were not aware how much value
2796 // this path will transfer, and the relative fee for them
2797 // might have been computed considering a larger value.
2798 // Remember that we used these channels so that we don't rely
2799 // on the same liquidity in future paths.
2800 let mut prevented_redundant_path_selection = false;
2801 for (hop, _) in payment_path.hops.iter() {
2802 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2803 let used_liquidity_msat = used_liquidities
2804 .entry(hop.candidate.id())
2805 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2806 .or_insert(spent_on_hop_msat);
2807 let hop_capacity = hop.candidate.effective_capacity();
2808 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2809 if *used_liquidity_msat == hop_max_msat {
2810 // If this path used all of this channel's available liquidity, we know
2811 // this path will not be selected again in the next loop iteration.
2812 prevented_redundant_path_selection = true;
2814 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2816 if !prevented_redundant_path_selection {
2817 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2818 // we'll probably end up picking the same path again on the next iteration.
2819 // Decrease the available liquidity of a hop in the middle of the path.
2820 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2821 let exhausted = u64::max_value();
2823 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2824 LoggedCandidateHop(victim_candidate));
2825 if let Some(scid) = victim_candidate.short_channel_id() {
2826 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2827 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2831 // Track the total amount all our collected paths allow to send so that we know
2832 // when to stop looking for more paths
2833 already_collected_value_msat += value_contribution_msat;
2835 payment_paths.push(payment_path);
2836 found_new_path = true;
2837 break 'path_construction;
2840 // If we found a path back to the payee, we shouldn't try to process it again. This is
2841 // the equivalent of the `elem.was_processed` check in
2842 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2843 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2845 // Otherwise, since the current target node is not us,
2846 // keep "unrolling" the payment graph from payee to payer by
2847 // finding a way to reach the current target from the payer side.
2848 match network_nodes.get(&node_id) {
2851 add_entries_to_cheapest_to_target_node!(node, node_id,
2852 value_contribution_msat,
2853 total_cltv_delta, path_length_to_node);
2859 if !found_new_path && channel_saturation_pow_half != 0 {
2860 channel_saturation_pow_half = 0;
2861 continue 'paths_collection;
2863 // If we don't support MPP, no use trying to gather more value ever.
2864 break 'paths_collection;
2868 // Stop either when the recommended value is reached or if no new path was found in this
2870 // In the latter case, making another path finding attempt won't help,
2871 // because we deterministically terminated the search due to low liquidity.
2872 if !found_new_path && channel_saturation_pow_half != 0 {
2873 channel_saturation_pow_half = 0;
2874 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2875 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
2876 path_value_msat = recommended_value_msat;
2877 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2878 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2879 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2880 break 'paths_collection;
2881 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2882 // Further, if this was our first walk of the graph, and we weren't limited by an
2883 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2884 // limited by an htlc_minimum_msat value, find another path with a higher value,
2885 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2886 // still keeping a lower total fee than this path.
2887 if !hit_minimum_limit {
2888 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2889 break 'paths_collection;
2891 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.");
2892 path_value_msat = recommended_value_msat;
2896 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2897 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
2898 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
2899 num_ignored_total_fee_limit;
2900 if num_ignored_total > 0 {
2902 "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.",
2903 num_ignored_value_contribution, num_ignored_path_length_limit,
2904 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
2905 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
2906 num_ignored_total_fee_limit, num_ignored_total);
2910 if payment_paths.len() == 0 {
2911 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2914 if already_collected_value_msat < final_value_msat {
2915 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2919 let mut selected_route = payment_paths;
2921 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2922 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2924 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2925 // the value they contribute towards the payment amount.
2926 // We sort in descending order as we will remove from the front in `retain`, next.
2927 selected_route.sort_unstable_by(|a, b|
2928 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2929 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2932 // We should make sure that at least 1 path left.
2933 let mut paths_left = selected_route.len();
2934 selected_route.retain(|path| {
2935 if paths_left == 1 {
2938 let path_value_msat = path.get_value_msat();
2939 if path_value_msat <= overpaid_value_msat {
2940 overpaid_value_msat -= path_value_msat;
2946 debug_assert!(selected_route.len() > 0);
2948 if overpaid_value_msat != 0 {
2950 // Now, subtract the remaining overpaid value from the most-expensive path.
2951 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2952 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2953 selected_route.sort_unstable_by(|a, b| {
2954 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2955 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2956 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2958 let expensive_payment_path = selected_route.first_mut().unwrap();
2960 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2961 // can't go negative.
2962 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2963 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2967 // Sort by the path itself and combine redundant paths.
2968 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2969 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2971 selected_route.sort_unstable_by_key(|path| {
2972 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2973 debug_assert!(path.hops.len() <= key.len());
2974 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
2979 for idx in 0..(selected_route.len() - 1) {
2980 if idx + 1 >= selected_route.len() { break; }
2981 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
2982 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
2983 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2984 selected_route[idx].update_value_and_recompute_fees(new_value);
2985 selected_route.remove(idx + 1);
2989 let mut paths = Vec::new();
2990 for payment_path in selected_route {
2991 let mut hops = Vec::with_capacity(payment_path.hops.len());
2992 for (hop, node_features) in payment_path.hops.iter()
2993 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2995 let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
2996 let maybe_announced_channel = if let CandidateRouteHop::PublicHop(_) = hop.candidate {
2997 // If we sourced the hop from the graph we're sure the target node is announced.
2999 } else if let CandidateRouteHop::FirstHop(first_hop) = &hop.candidate {
3000 // If this is a first hop we also know if it's announced.
3001 first_hop.details.is_public
3003 // If we sourced it any other way, we double-check the network graph to see if
3004 // there are announced channels between the endpoints. If so, the hop might be
3005 // referring to any of the announced channels, as its `short_channel_id` might be
3006 // an alias, in which case we don't take any chances here.
3007 network_graph.node(&target).map_or(false, |hop_node|
3008 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
3009 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
3013 hops.push(RouteHop {
3014 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
3015 node_features: node_features.clone(),
3016 short_channel_id: hop.candidate.short_channel_id().unwrap(),
3017 channel_features: hop.candidate.features(),
3018 fee_msat: hop.fee_msat,
3019 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
3020 maybe_announced_channel,
3023 let mut final_cltv_delta = final_cltv_expiry_delta;
3024 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
3025 if let Some(blinded_path) = h.candidate.blinded_path() {
3026 final_cltv_delta = h.candidate.cltv_expiry_delta();
3028 hops: blinded_path.blinded_hops.clone(),
3029 blinding_point: blinded_path.blinding_point,
3030 excess_final_cltv_expiry_delta: 0,
3031 final_value_msat: h.fee_msat,
3035 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
3036 // applicable for the previous hop.
3037 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
3038 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
3041 paths.push(Path { hops, blinded_tail });
3043 // Make sure we would never create a route with more paths than we allow.
3044 debug_assert!(paths.len() <= payment_params.max_path_count.into());
3046 if let Some(node_features) = payment_params.payee.node_features() {
3047 for path in paths.iter_mut() {
3048 path.hops.last_mut().unwrap().node_features = node_features.clone();
3052 let route = Route { paths, route_params: Some(route_params.clone()) };
3054 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
3055 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
3056 if route.get_total_fees() > max_total_routing_fee_msat {
3057 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
3058 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
3062 log_info!(logger, "Got route: {}", log_route!(route));
3066 // When an adversarial intermediary node observes a payment, it may be able to infer its
3067 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
3068 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
3069 // payment path by adding a randomized 'shadow route' offset to the final hop.
3070 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
3071 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
3073 let network_channels = network_graph.channels();
3074 let network_nodes = network_graph.nodes();
3076 for path in route.paths.iter_mut() {
3077 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
3079 // Remember the last three nodes of the random walk and avoid looping back on them.
3080 // Init with the last three nodes from the actual path, if possible.
3081 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
3082 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
3083 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
3085 // Choose the last publicly known node as the starting point for the random walk.
3086 let mut cur_hop: Option<NodeId> = None;
3087 let mut path_nonce = [0u8; 12];
3088 if let Some(starting_hop) = path.hops.iter().rev()
3089 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
3090 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
3091 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
3094 // Init PRNG with the path-dependant nonce, which is static for private paths.
3095 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
3096 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
3098 // Pick a random path length in [1 .. 3]
3099 prng.process_in_place(&mut random_path_bytes);
3100 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
3102 for random_hop in 0..random_walk_length {
3103 // If we don't find a suitable offset in the public network graph, we default to
3104 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3105 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
3107 if let Some(cur_node_id) = cur_hop {
3108 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
3109 // Randomly choose the next unvisited hop.
3110 prng.process_in_place(&mut random_path_bytes);
3111 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
3112 .checked_rem(cur_node.channels.len())
3113 .and_then(|index| cur_node.channels.get(index))
3114 .and_then(|id| network_channels.get(id)) {
3115 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
3116 if !nodes_to_avoid.iter().any(|x| x == next_id) {
3117 nodes_to_avoid[random_hop] = *next_id;
3118 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
3119 cur_hop = Some(*next_id);
3126 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
3127 .checked_add(random_hop_offset)
3128 .unwrap_or(shadow_ctlv_expiry_delta_offset);
3131 // Limit the total offset to reduce the worst-case locked liquidity timevalue
3132 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
3133 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
3135 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
3136 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3137 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
3138 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
3139 max_path_offset = cmp::max(
3140 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
3141 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
3142 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
3144 // Add 'shadow' CLTV offset to the final hop
3145 if let Some(tail) = path.blinded_tail.as_mut() {
3146 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
3147 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
3149 if let Some(last_hop) = path.hops.last_mut() {
3150 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
3151 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
3156 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
3157 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
3159 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
3160 pub fn build_route_from_hops<L: Deref, GL: Deref>(
3161 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3162 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
3163 ) -> Result<Route, LightningError>
3164 where L::Target: Logger, GL::Target: Logger {
3165 let graph_lock = network_graph.read_only();
3166 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
3167 &graph_lock, logger, random_seed_bytes)?;
3168 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
3172 fn build_route_from_hops_internal<L: Deref>(
3173 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3174 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
3175 ) -> Result<Route, LightningError> where L::Target: Logger {
3178 our_node_id: NodeId,
3179 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
3182 impl ScoreLookUp for HopScorer {
3183 type ScoreParams = ();
3184 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
3185 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
3187 let mut cur_id = self.our_node_id;
3188 for i in 0..self.hop_ids.len() {
3189 if let Some(next_id) = self.hop_ids[i] {
3190 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
3202 impl<'a> Writeable for HopScorer {
3204 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
3209 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
3210 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
3213 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
3214 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
3215 for i in 0..hops.len() {
3216 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
3219 let scorer = HopScorer { our_node_id, hop_ids };
3221 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
3226 use crate::blinded_path::{BlindedHop, BlindedPath};
3227 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
3228 use crate::routing::utxo::UtxoResult;
3229 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
3230 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
3231 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop, PublicHopCandidate};
3232 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
3233 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
3234 use crate::chain::transaction::OutPoint;
3235 use crate::sign::EntropySource;
3236 use crate::ln::ChannelId;
3237 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
3238 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
3239 use crate::ln::channelmanager;
3240 use crate::offers::invoice::BlindedPayInfo;
3241 use crate::util::config::UserConfig;
3242 use crate::util::test_utils as ln_test_utils;
3243 use crate::crypto::chacha20::ChaCha20;
3244 use crate::util::ser::{Readable, Writeable};
3246 use crate::util::ser::Writer;
3248 use bitcoin::hashes::Hash;
3249 use bitcoin::network::constants::Network;
3250 use bitcoin::blockdata::constants::ChainHash;
3251 use bitcoin::blockdata::script::Builder;
3252 use bitcoin::blockdata::opcodes;
3253 use bitcoin::blockdata::transaction::TxOut;
3254 use bitcoin::hashes::hex::FromHex;
3255 use bitcoin::secp256k1::{PublicKey,SecretKey};
3256 use bitcoin::secp256k1::Secp256k1;
3258 use crate::io::Cursor;
3259 use crate::prelude::*;
3260 use crate::sync::Arc;
3262 use core::convert::TryInto;
3264 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3265 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
3266 channelmanager::ChannelDetails {
3267 channel_id: ChannelId::new_zero(),
3268 counterparty: channelmanager::ChannelCounterparty {
3271 unspendable_punishment_reserve: 0,
3272 forwarding_info: None,
3273 outbound_htlc_minimum_msat: None,
3274 outbound_htlc_maximum_msat: None,
3276 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3279 outbound_scid_alias: None,
3280 inbound_scid_alias: None,
3281 channel_value_satoshis: 0,
3284 outbound_capacity_msat,
3285 next_outbound_htlc_limit_msat: outbound_capacity_msat,
3286 next_outbound_htlc_minimum_msat: 0,
3287 inbound_capacity_msat: 42,
3288 unspendable_punishment_reserve: None,
3289 confirmations_required: None,
3290 confirmations: None,
3291 force_close_spend_delay: None,
3292 is_outbound: true, is_channel_ready: true,
3293 is_usable: true, is_public: true,
3294 inbound_htlc_minimum_msat: None,
3295 inbound_htlc_maximum_msat: None,
3297 feerate_sat_per_1000_weight: None,
3298 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
3299 pending_inbound_htlcs: Vec::new(),
3300 pending_outbound_htlcs: Vec::new(),
3305 fn simple_route_test() {
3306 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3307 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3308 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3309 let scorer = ln_test_utils::TestScorer::new();
3310 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3311 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3313 // Simple route to 2 via 1
3315 let route_params = RouteParameters::from_payment_params_and_value(
3316 payment_params.clone(), 0);
3317 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3318 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3319 &Default::default(), &random_seed_bytes) {
3320 assert_eq!(err, "Cannot send a payment of 0 msat");
3321 } else { panic!(); }
3323 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3324 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3325 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3326 assert_eq!(route.paths[0].hops.len(), 2);
3328 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3329 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3330 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3331 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3332 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3333 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3335 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3336 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3337 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3338 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3339 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3340 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3344 fn invalid_first_hop_test() {
3345 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3346 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3347 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3348 let scorer = ln_test_utils::TestScorer::new();
3349 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3350 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3352 // Simple route to 2 via 1
3354 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3356 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3357 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3358 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3359 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3360 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3361 } else { panic!(); }
3363 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3364 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3365 assert_eq!(route.paths[0].hops.len(), 2);
3369 fn htlc_minimum_test() {
3370 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3371 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3372 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3373 let scorer = ln_test_utils::TestScorer::new();
3374 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3375 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3377 // Simple route to 2 via 1
3379 // Disable other paths
3380 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3381 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3382 short_channel_id: 12,
3384 flags: 2, // to disable
3385 cltv_expiry_delta: 0,
3386 htlc_minimum_msat: 0,
3387 htlc_maximum_msat: MAX_VALUE_MSAT,
3389 fee_proportional_millionths: 0,
3390 excess_data: Vec::new()
3392 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3393 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3394 short_channel_id: 3,
3396 flags: 2, // to disable
3397 cltv_expiry_delta: 0,
3398 htlc_minimum_msat: 0,
3399 htlc_maximum_msat: MAX_VALUE_MSAT,
3401 fee_proportional_millionths: 0,
3402 excess_data: Vec::new()
3404 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3405 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3406 short_channel_id: 13,
3408 flags: 2, // to disable
3409 cltv_expiry_delta: 0,
3410 htlc_minimum_msat: 0,
3411 htlc_maximum_msat: MAX_VALUE_MSAT,
3413 fee_proportional_millionths: 0,
3414 excess_data: Vec::new()
3416 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3417 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3418 short_channel_id: 6,
3420 flags: 2, // to disable
3421 cltv_expiry_delta: 0,
3422 htlc_minimum_msat: 0,
3423 htlc_maximum_msat: MAX_VALUE_MSAT,
3425 fee_proportional_millionths: 0,
3426 excess_data: Vec::new()
3428 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3429 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3430 short_channel_id: 7,
3432 flags: 2, // to disable
3433 cltv_expiry_delta: 0,
3434 htlc_minimum_msat: 0,
3435 htlc_maximum_msat: MAX_VALUE_MSAT,
3437 fee_proportional_millionths: 0,
3438 excess_data: Vec::new()
3441 // Check against amount_to_transfer_over_msat.
3442 // Set minimal HTLC of 200_000_000 msat.
3443 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3444 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3445 short_channel_id: 2,
3448 cltv_expiry_delta: 0,
3449 htlc_minimum_msat: 200_000_000,
3450 htlc_maximum_msat: MAX_VALUE_MSAT,
3452 fee_proportional_millionths: 0,
3453 excess_data: Vec::new()
3456 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3458 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3459 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3460 short_channel_id: 4,
3463 cltv_expiry_delta: 0,
3464 htlc_minimum_msat: 0,
3465 htlc_maximum_msat: 199_999_999,
3467 fee_proportional_millionths: 0,
3468 excess_data: Vec::new()
3471 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3472 let route_params = RouteParameters::from_payment_params_and_value(
3473 payment_params, 199_999_999);
3474 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3475 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3476 &Default::default(), &random_seed_bytes) {
3477 assert_eq!(err, "Failed to find a path to the given destination");
3478 } else { panic!(); }
3480 // Lift the restriction on the first hop.
3481 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3482 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3483 short_channel_id: 2,
3486 cltv_expiry_delta: 0,
3487 htlc_minimum_msat: 0,
3488 htlc_maximum_msat: MAX_VALUE_MSAT,
3490 fee_proportional_millionths: 0,
3491 excess_data: Vec::new()
3494 // A payment above the minimum should pass
3495 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3496 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3497 assert_eq!(route.paths[0].hops.len(), 2);
3501 fn htlc_minimum_overpay_test() {
3502 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3503 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3504 let config = UserConfig::default();
3505 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3506 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3508 let scorer = ln_test_utils::TestScorer::new();
3509 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3510 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3512 // A route to node#2 via two paths.
3513 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3514 // Thus, they can't send 60 without overpaying.
3515 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3516 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3517 short_channel_id: 2,
3520 cltv_expiry_delta: 0,
3521 htlc_minimum_msat: 35_000,
3522 htlc_maximum_msat: 40_000,
3524 fee_proportional_millionths: 0,
3525 excess_data: Vec::new()
3527 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3528 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3529 short_channel_id: 12,
3532 cltv_expiry_delta: 0,
3533 htlc_minimum_msat: 35_000,
3534 htlc_maximum_msat: 40_000,
3536 fee_proportional_millionths: 0,
3537 excess_data: Vec::new()
3541 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3542 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3543 short_channel_id: 13,
3546 cltv_expiry_delta: 0,
3547 htlc_minimum_msat: 0,
3548 htlc_maximum_msat: MAX_VALUE_MSAT,
3550 fee_proportional_millionths: 0,
3551 excess_data: Vec::new()
3553 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3554 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3555 short_channel_id: 4,
3558 cltv_expiry_delta: 0,
3559 htlc_minimum_msat: 0,
3560 htlc_maximum_msat: MAX_VALUE_MSAT,
3562 fee_proportional_millionths: 0,
3563 excess_data: Vec::new()
3566 // Disable other paths
3567 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3568 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3569 short_channel_id: 1,
3571 flags: 2, // to disable
3572 cltv_expiry_delta: 0,
3573 htlc_minimum_msat: 0,
3574 htlc_maximum_msat: MAX_VALUE_MSAT,
3576 fee_proportional_millionths: 0,
3577 excess_data: Vec::new()
3580 let mut route_params = RouteParameters::from_payment_params_and_value(
3581 payment_params.clone(), 60_000);
3582 route_params.max_total_routing_fee_msat = Some(15_000);
3583 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3584 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3585 // Overpay fees to hit htlc_minimum_msat.
3586 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3587 // TODO: this could be better balanced to overpay 10k and not 15k.
3588 assert_eq!(overpaid_fees, 15_000);
3590 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3591 // while taking even more fee to match htlc_minimum_msat.
3592 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3593 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3594 short_channel_id: 12,
3597 cltv_expiry_delta: 0,
3598 htlc_minimum_msat: 65_000,
3599 htlc_maximum_msat: 80_000,
3601 fee_proportional_millionths: 0,
3602 excess_data: Vec::new()
3604 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3605 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3606 short_channel_id: 2,
3609 cltv_expiry_delta: 0,
3610 htlc_minimum_msat: 0,
3611 htlc_maximum_msat: MAX_VALUE_MSAT,
3613 fee_proportional_millionths: 0,
3614 excess_data: Vec::new()
3616 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3617 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3618 short_channel_id: 4,
3621 cltv_expiry_delta: 0,
3622 htlc_minimum_msat: 0,
3623 htlc_maximum_msat: MAX_VALUE_MSAT,
3625 fee_proportional_millionths: 100_000,
3626 excess_data: Vec::new()
3629 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3630 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3631 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3632 assert_eq!(route.paths.len(), 1);
3633 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3634 let fees = route.paths[0].hops[0].fee_msat;
3635 assert_eq!(fees, 5_000);
3637 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3638 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3639 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3640 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3641 // the other channel.
3642 assert_eq!(route.paths.len(), 1);
3643 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3644 let fees = route.paths[0].hops[0].fee_msat;
3645 assert_eq!(fees, 5_000);
3649 fn htlc_minimum_recipient_overpay_test() {
3650 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3651 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3652 let config = UserConfig::default();
3653 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3654 let scorer = ln_test_utils::TestScorer::new();
3655 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3656 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3658 // Route to node2 over a single path which requires overpaying the recipient themselves.
3660 // First disable all paths except the us -> node1 -> node2 path
3661 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3662 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3663 short_channel_id: 13,
3666 cltv_expiry_delta: 0,
3667 htlc_minimum_msat: 0,
3668 htlc_maximum_msat: 0,
3670 fee_proportional_millionths: 0,
3671 excess_data: Vec::new()
3674 // Set channel 4 to free but with a high htlc_minimum_msat
3675 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3676 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3677 short_channel_id: 4,
3680 cltv_expiry_delta: 0,
3681 htlc_minimum_msat: 15_000,
3682 htlc_maximum_msat: MAX_VALUE_MSAT,
3684 fee_proportional_millionths: 0,
3685 excess_data: Vec::new()
3688 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3689 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3690 // what we try to find a route for, so this test only just happens to work out to exactly
3692 let mut route_params = RouteParameters::from_payment_params_and_value(
3693 payment_params.clone(), 5_000);
3694 route_params.max_total_routing_fee_msat = Some(9_999);
3695 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3696 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3697 &Default::default(), &random_seed_bytes) {
3698 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3699 } else { panic!(); }
3701 let mut route_params = RouteParameters::from_payment_params_and_value(
3702 payment_params.clone(), 5_000);
3703 route_params.max_total_routing_fee_msat = Some(10_000);
3704 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3705 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3706 assert_eq!(route.get_total_fees(), 10_000);
3710 fn disable_channels_test() {
3711 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3712 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3713 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3714 let scorer = ln_test_utils::TestScorer::new();
3715 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3716 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3718 // // Disable channels 4 and 12 by flags=2
3719 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3720 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3721 short_channel_id: 4,
3723 flags: 2, // to disable
3724 cltv_expiry_delta: 0,
3725 htlc_minimum_msat: 0,
3726 htlc_maximum_msat: MAX_VALUE_MSAT,
3728 fee_proportional_millionths: 0,
3729 excess_data: Vec::new()
3731 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3732 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3733 short_channel_id: 12,
3735 flags: 2, // to disable
3736 cltv_expiry_delta: 0,
3737 htlc_minimum_msat: 0,
3738 htlc_maximum_msat: MAX_VALUE_MSAT,
3740 fee_proportional_millionths: 0,
3741 excess_data: Vec::new()
3744 // If all the channels require some features we don't understand, route should fail
3745 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3746 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3747 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3748 &Default::default(), &random_seed_bytes) {
3749 assert_eq!(err, "Failed to find a path to the given destination");
3750 } else { panic!(); }
3752 // If we specify a channel to node7, that overrides our local channel view and that gets used
3753 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3754 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3755 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3756 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3757 &Default::default(), &random_seed_bytes).unwrap();
3758 assert_eq!(route.paths[0].hops.len(), 2);
3760 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3761 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3762 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3763 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3764 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3765 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3767 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3768 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3769 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3770 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3771 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3772 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3776 fn disable_node_test() {
3777 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3778 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3779 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3780 let scorer = ln_test_utils::TestScorer::new();
3781 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3782 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3784 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3785 let mut unknown_features = NodeFeatures::empty();
3786 unknown_features.set_unknown_feature_required();
3787 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3788 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3789 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3791 // If all nodes require some features we don't understand, route should fail
3792 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3793 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3794 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3795 &Default::default(), &random_seed_bytes) {
3796 assert_eq!(err, "Failed to find a path to the given destination");
3797 } else { panic!(); }
3799 // If we specify a channel to node7, that overrides our local channel view and that gets used
3800 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3801 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3802 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3803 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3804 &Default::default(), &random_seed_bytes).unwrap();
3805 assert_eq!(route.paths[0].hops.len(), 2);
3807 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3808 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3809 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3810 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3811 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3812 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3814 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3815 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3816 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3817 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3818 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3819 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3821 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3822 // naively) assume that the user checked the feature bits on the invoice, which override
3823 // the node_announcement.
3827 fn our_chans_test() {
3828 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3829 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3830 let scorer = ln_test_utils::TestScorer::new();
3831 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3832 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3834 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3835 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3836 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3837 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3838 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3839 assert_eq!(route.paths[0].hops.len(), 3);
3841 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3842 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3843 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3844 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3845 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3846 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3848 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3849 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3850 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3851 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3852 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3853 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3855 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3856 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3857 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3858 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3859 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3860 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3862 // If we specify a channel to node7, that overrides our local channel view and that gets used
3863 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3864 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3865 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3866 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3867 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3868 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3869 &Default::default(), &random_seed_bytes).unwrap();
3870 assert_eq!(route.paths[0].hops.len(), 2);
3872 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3873 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3874 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3875 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3876 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3877 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3879 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3880 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3881 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3882 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3883 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3884 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3887 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3888 let zero_fees = RoutingFees {
3890 proportional_millionths: 0,
3892 vec![RouteHint(vec![RouteHintHop {
3893 src_node_id: nodes[3],
3894 short_channel_id: 8,
3896 cltv_expiry_delta: (8 << 4) | 1,
3897 htlc_minimum_msat: None,
3898 htlc_maximum_msat: None,
3900 ]), RouteHint(vec![RouteHintHop {
3901 src_node_id: nodes[4],
3902 short_channel_id: 9,
3905 proportional_millionths: 0,
3907 cltv_expiry_delta: (9 << 4) | 1,
3908 htlc_minimum_msat: None,
3909 htlc_maximum_msat: None,
3910 }]), RouteHint(vec![RouteHintHop {
3911 src_node_id: nodes[5],
3912 short_channel_id: 10,
3914 cltv_expiry_delta: (10 << 4) | 1,
3915 htlc_minimum_msat: None,
3916 htlc_maximum_msat: None,
3920 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3921 let zero_fees = RoutingFees {
3923 proportional_millionths: 0,
3925 vec![RouteHint(vec![RouteHintHop {
3926 src_node_id: nodes[2],
3927 short_channel_id: 5,
3930 proportional_millionths: 0,
3932 cltv_expiry_delta: (5 << 4) | 1,
3933 htlc_minimum_msat: None,
3934 htlc_maximum_msat: None,
3936 src_node_id: nodes[3],
3937 short_channel_id: 8,
3939 cltv_expiry_delta: (8 << 4) | 1,
3940 htlc_minimum_msat: None,
3941 htlc_maximum_msat: None,
3943 ]), RouteHint(vec![RouteHintHop {
3944 src_node_id: nodes[4],
3945 short_channel_id: 9,
3948 proportional_millionths: 0,
3950 cltv_expiry_delta: (9 << 4) | 1,
3951 htlc_minimum_msat: None,
3952 htlc_maximum_msat: None,
3953 }]), RouteHint(vec![RouteHintHop {
3954 src_node_id: nodes[5],
3955 short_channel_id: 10,
3957 cltv_expiry_delta: (10 << 4) | 1,
3958 htlc_minimum_msat: None,
3959 htlc_maximum_msat: None,
3964 fn partial_route_hint_test() {
3965 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3966 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3967 let scorer = ln_test_utils::TestScorer::new();
3968 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3969 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3971 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3972 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3973 // RouteHint may be partially used by the algo to build the best path.
3975 // First check that last hop can't have its source as the payee.
3976 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3977 src_node_id: nodes[6],
3978 short_channel_id: 8,
3981 proportional_millionths: 0,
3983 cltv_expiry_delta: (8 << 4) | 1,
3984 htlc_minimum_msat: None,
3985 htlc_maximum_msat: None,
3988 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3989 invalid_last_hops.push(invalid_last_hop);
3991 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3992 .with_route_hints(invalid_last_hops).unwrap();
3993 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3994 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3995 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3996 &Default::default(), &random_seed_bytes) {
3997 assert_eq!(err, "Route hint cannot have the payee as the source.");
3998 } else { panic!(); }
4001 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4002 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
4003 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4004 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4005 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4006 assert_eq!(route.paths[0].hops.len(), 5);
4008 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4009 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4010 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4011 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4012 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4013 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4015 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4016 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4017 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4018 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4019 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4020 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4022 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4023 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4024 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4025 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4026 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4027 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4029 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4030 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4031 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4032 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4033 // If we have a peer in the node map, we'll use their features here since we don't have
4034 // a way of figuring out their features from the invoice:
4035 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4036 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4038 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4039 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4040 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4041 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4042 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4043 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4046 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4047 let zero_fees = RoutingFees {
4049 proportional_millionths: 0,
4051 vec![RouteHint(vec![RouteHintHop {
4052 src_node_id: nodes[3],
4053 short_channel_id: 8,
4055 cltv_expiry_delta: (8 << 4) | 1,
4056 htlc_minimum_msat: None,
4057 htlc_maximum_msat: None,
4058 }]), RouteHint(vec![
4060 ]), RouteHint(vec![RouteHintHop {
4061 src_node_id: nodes[5],
4062 short_channel_id: 10,
4064 cltv_expiry_delta: (10 << 4) | 1,
4065 htlc_minimum_msat: None,
4066 htlc_maximum_msat: None,
4071 fn ignores_empty_last_hops_test() {
4072 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4073 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4074 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
4075 let scorer = ln_test_utils::TestScorer::new();
4076 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4077 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4079 // Test handling of an empty RouteHint passed in Invoice.
4080 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4081 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4082 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4083 assert_eq!(route.paths[0].hops.len(), 5);
4085 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4086 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4087 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4088 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4089 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4090 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4092 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4093 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4094 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4095 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4096 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4097 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4099 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4100 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4101 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4102 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4103 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4104 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4106 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4107 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4108 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4109 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4110 // If we have a peer in the node map, we'll use their features here since we don't have
4111 // a way of figuring out their features from the invoice:
4112 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4113 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4115 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4116 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4117 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4118 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4119 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4120 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4123 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
4125 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
4126 let zero_fees = RoutingFees {
4128 proportional_millionths: 0,
4130 vec![RouteHint(vec![RouteHintHop {
4131 src_node_id: hint_hops[0],
4132 short_channel_id: 0xff00,
4135 proportional_millionths: 0,
4137 cltv_expiry_delta: (5 << 4) | 1,
4138 htlc_minimum_msat: None,
4139 htlc_maximum_msat: None,
4141 src_node_id: hint_hops[1],
4142 short_channel_id: 0xff01,
4144 cltv_expiry_delta: (8 << 4) | 1,
4145 htlc_minimum_msat: None,
4146 htlc_maximum_msat: None,
4151 fn multi_hint_last_hops_test() {
4152 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4153 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4154 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
4155 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4156 let scorer = ln_test_utils::TestScorer::new();
4157 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4158 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4159 // Test through channels 2, 3, 0xff00, 0xff01.
4160 // Test shows that multiple hop hints are considered.
4162 // Disabling channels 6 & 7 by flags=2
4163 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4164 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4165 short_channel_id: 6,
4167 flags: 2, // to disable
4168 cltv_expiry_delta: 0,
4169 htlc_minimum_msat: 0,
4170 htlc_maximum_msat: MAX_VALUE_MSAT,
4172 fee_proportional_millionths: 0,
4173 excess_data: Vec::new()
4175 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4176 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4177 short_channel_id: 7,
4179 flags: 2, // to disable
4180 cltv_expiry_delta: 0,
4181 htlc_minimum_msat: 0,
4182 htlc_maximum_msat: MAX_VALUE_MSAT,
4184 fee_proportional_millionths: 0,
4185 excess_data: Vec::new()
4188 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4189 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4190 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4191 assert_eq!(route.paths[0].hops.len(), 4);
4193 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4194 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4195 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4196 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4197 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4198 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4200 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4201 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4202 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4203 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4204 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4205 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4207 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4208 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4209 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4210 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4211 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4212 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4214 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4215 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4216 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4217 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4218 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4219 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4223 fn private_multi_hint_last_hops_test() {
4224 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4225 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4227 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4228 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4230 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4231 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4232 let scorer = ln_test_utils::TestScorer::new();
4233 // Test through channels 2, 3, 0xff00, 0xff01.
4234 // Test shows that multiple hop hints are considered.
4236 // Disabling channels 6 & 7 by flags=2
4237 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4238 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4239 short_channel_id: 6,
4241 flags: 2, // to disable
4242 cltv_expiry_delta: 0,
4243 htlc_minimum_msat: 0,
4244 htlc_maximum_msat: MAX_VALUE_MSAT,
4246 fee_proportional_millionths: 0,
4247 excess_data: Vec::new()
4249 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4250 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4251 short_channel_id: 7,
4253 flags: 2, // to disable
4254 cltv_expiry_delta: 0,
4255 htlc_minimum_msat: 0,
4256 htlc_maximum_msat: MAX_VALUE_MSAT,
4258 fee_proportional_millionths: 0,
4259 excess_data: Vec::new()
4262 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4263 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4264 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4265 assert_eq!(route.paths[0].hops.len(), 4);
4267 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4268 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4269 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4270 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4271 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4272 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4274 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4275 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4276 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4277 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4278 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4279 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4281 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4282 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4283 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4284 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4285 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4286 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4288 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4289 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4290 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4291 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4292 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4293 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4296 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4297 let zero_fees = RoutingFees {
4299 proportional_millionths: 0,
4301 vec![RouteHint(vec![RouteHintHop {
4302 src_node_id: nodes[4],
4303 short_channel_id: 11,
4305 cltv_expiry_delta: (11 << 4) | 1,
4306 htlc_minimum_msat: None,
4307 htlc_maximum_msat: None,
4309 src_node_id: nodes[3],
4310 short_channel_id: 8,
4312 cltv_expiry_delta: (8 << 4) | 1,
4313 htlc_minimum_msat: None,
4314 htlc_maximum_msat: None,
4315 }]), RouteHint(vec![RouteHintHop {
4316 src_node_id: nodes[4],
4317 short_channel_id: 9,
4320 proportional_millionths: 0,
4322 cltv_expiry_delta: (9 << 4) | 1,
4323 htlc_minimum_msat: None,
4324 htlc_maximum_msat: None,
4325 }]), RouteHint(vec![RouteHintHop {
4326 src_node_id: nodes[5],
4327 short_channel_id: 10,
4329 cltv_expiry_delta: (10 << 4) | 1,
4330 htlc_minimum_msat: None,
4331 htlc_maximum_msat: None,
4336 fn last_hops_with_public_channel_test() {
4337 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4338 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4339 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4340 let scorer = ln_test_utils::TestScorer::new();
4341 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4342 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4343 // This test shows that public routes can be present in the invoice
4344 // which would be handled in the same manner.
4346 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4347 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4348 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4349 assert_eq!(route.paths[0].hops.len(), 5);
4351 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4352 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4353 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4354 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4355 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4356 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4358 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4359 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4360 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4361 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4362 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4363 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4365 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4366 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4367 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4368 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4369 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4370 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4372 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4373 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4374 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4375 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4376 // If we have a peer in the node map, we'll use their features here since we don't have
4377 // a way of figuring out their features from the invoice:
4378 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4379 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4381 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4382 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4383 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4384 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4385 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4386 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4390 fn our_chans_last_hop_connect_test() {
4391 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4392 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4393 let scorer = ln_test_utils::TestScorer::new();
4394 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4395 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4397 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4398 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4399 let mut last_hops = last_hops(&nodes);
4400 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4401 .with_route_hints(last_hops.clone()).unwrap();
4402 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4403 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4404 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4405 &Default::default(), &random_seed_bytes).unwrap();
4406 assert_eq!(route.paths[0].hops.len(), 2);
4408 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4409 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4410 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4411 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4412 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4413 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4415 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4416 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4417 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4418 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4419 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4420 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4422 last_hops[0].0[0].fees.base_msat = 1000;
4424 // Revert to via 6 as the fee on 8 goes up
4425 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4426 .with_route_hints(last_hops).unwrap();
4427 let route_params = RouteParameters::from_payment_params_and_value(
4428 payment_params.clone(), 100);
4429 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4430 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4431 assert_eq!(route.paths[0].hops.len(), 4);
4433 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4434 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4435 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4436 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4437 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4438 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4440 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4441 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4442 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4443 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4444 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4445 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4447 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4448 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4449 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4450 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4451 // If we have a peer in the node map, we'll use their features here since we don't have
4452 // a way of figuring out their features from the invoice:
4453 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4454 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4456 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4457 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4458 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4459 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4460 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4461 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4463 // ...but still use 8 for larger payments as 6 has a variable feerate
4464 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4465 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4466 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4467 assert_eq!(route.paths[0].hops.len(), 5);
4469 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4470 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4471 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4472 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4473 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4474 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4476 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4477 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4478 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4479 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4480 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4481 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4483 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4484 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4485 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4486 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4487 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4488 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4490 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4491 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4492 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4493 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4494 // If we have a peer in the node map, we'll use their features here since we don't have
4495 // a way of figuring out their features from the invoice:
4496 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4497 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4499 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4500 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4501 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4502 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4503 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4504 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4507 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> {
4508 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4509 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4510 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4512 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4513 let last_hops = RouteHint(vec![RouteHintHop {
4514 src_node_id: middle_node_id,
4515 short_channel_id: 8,
4518 proportional_millionths: last_hop_fee_prop,
4520 cltv_expiry_delta: (8 << 4) | 1,
4521 htlc_minimum_msat: None,
4522 htlc_maximum_msat: last_hop_htlc_max,
4524 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4525 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4526 let scorer = ln_test_utils::TestScorer::new();
4527 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4528 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4529 let logger = ln_test_utils::TestLogger::new();
4530 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4531 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4532 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4533 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4534 &random_seed_bytes);
4539 fn unannounced_path_test() {
4540 // We should be able to send a payment to a destination without any help of a routing graph
4541 // if we have a channel with a common counterparty that appears in the first and last hop
4543 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4545 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4546 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4547 assert_eq!(route.paths[0].hops.len(), 2);
4549 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4550 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4551 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4552 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4553 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4554 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4556 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4557 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4558 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4559 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4560 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4561 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4565 fn overflow_unannounced_path_test_liquidity_underflow() {
4566 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4567 // the last-hop had a fee which overflowed a u64, we'd panic.
4568 // This was due to us adding the first-hop from us unconditionally, causing us to think
4569 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4570 // In this test, we previously hit a subtraction underflow due to having less available
4571 // liquidity at the last hop than 0.
4572 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());
4576 fn overflow_unannounced_path_test_feerate_overflow() {
4577 // This tests for the same case as above, except instead of hitting a subtraction
4578 // underflow, we hit a case where the fee charged at a hop overflowed.
4579 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());
4583 fn available_amount_while_routing_test() {
4584 // Tests whether we choose the correct available channel amount while routing.
4586 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4587 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4588 let scorer = ln_test_utils::TestScorer::new();
4589 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4590 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4591 let config = UserConfig::default();
4592 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4593 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4596 // We will use a simple single-path route from
4597 // our node to node2 via node0: channels {1, 3}.
4599 // First disable all other paths.
4600 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4601 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4602 short_channel_id: 2,
4605 cltv_expiry_delta: 0,
4606 htlc_minimum_msat: 0,
4607 htlc_maximum_msat: 100_000,
4609 fee_proportional_millionths: 0,
4610 excess_data: Vec::new()
4612 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4613 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4614 short_channel_id: 12,
4617 cltv_expiry_delta: 0,
4618 htlc_minimum_msat: 0,
4619 htlc_maximum_msat: 100_000,
4621 fee_proportional_millionths: 0,
4622 excess_data: Vec::new()
4625 // Make the first channel (#1) very permissive,
4626 // and we will be testing all limits on the second channel.
4627 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4628 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4629 short_channel_id: 1,
4632 cltv_expiry_delta: 0,
4633 htlc_minimum_msat: 0,
4634 htlc_maximum_msat: 1_000_000_000,
4636 fee_proportional_millionths: 0,
4637 excess_data: Vec::new()
4640 // First, let's see if routing works if we have absolutely no idea about the available amount.
4641 // In this case, it should be set to 250_000 sats.
4642 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4643 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4644 short_channel_id: 3,
4647 cltv_expiry_delta: 0,
4648 htlc_minimum_msat: 0,
4649 htlc_maximum_msat: 250_000_000,
4651 fee_proportional_millionths: 0,
4652 excess_data: Vec::new()
4656 // Attempt to route more than available results in a failure.
4657 let route_params = RouteParameters::from_payment_params_and_value(
4658 payment_params.clone(), 250_000_001);
4659 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4660 &our_id, &route_params, &network_graph.read_only(), None,
4661 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4662 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4663 } else { panic!(); }
4667 // Now, attempt to route an exact amount we have should be fine.
4668 let route_params = RouteParameters::from_payment_params_and_value(
4669 payment_params.clone(), 250_000_000);
4670 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4671 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4672 assert_eq!(route.paths.len(), 1);
4673 let path = route.paths.last().unwrap();
4674 assert_eq!(path.hops.len(), 2);
4675 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4676 assert_eq!(path.final_value_msat(), 250_000_000);
4679 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4680 // Disable channel #1 and use another first hop.
4681 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4682 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4683 short_channel_id: 1,
4686 cltv_expiry_delta: 0,
4687 htlc_minimum_msat: 0,
4688 htlc_maximum_msat: 1_000_000_000,
4690 fee_proportional_millionths: 0,
4691 excess_data: Vec::new()
4694 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4695 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4698 // Attempt to route more than available results in a failure.
4699 let route_params = RouteParameters::from_payment_params_and_value(
4700 payment_params.clone(), 200_000_001);
4701 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4702 &our_id, &route_params, &network_graph.read_only(),
4703 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4704 &Default::default(), &random_seed_bytes) {
4705 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4706 } else { panic!(); }
4710 // Now, attempt to route an exact amount we have should be fine.
4711 let route_params = RouteParameters::from_payment_params_and_value(
4712 payment_params.clone(), 200_000_000);
4713 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4714 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4715 &Default::default(), &random_seed_bytes).unwrap();
4716 assert_eq!(route.paths.len(), 1);
4717 let path = route.paths.last().unwrap();
4718 assert_eq!(path.hops.len(), 2);
4719 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4720 assert_eq!(path.final_value_msat(), 200_000_000);
4723 // Enable channel #1 back.
4724 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4725 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4726 short_channel_id: 1,
4729 cltv_expiry_delta: 0,
4730 htlc_minimum_msat: 0,
4731 htlc_maximum_msat: 1_000_000_000,
4733 fee_proportional_millionths: 0,
4734 excess_data: Vec::new()
4738 // Now let's see if routing works if we know only htlc_maximum_msat.
4739 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4740 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4741 short_channel_id: 3,
4744 cltv_expiry_delta: 0,
4745 htlc_minimum_msat: 0,
4746 htlc_maximum_msat: 15_000,
4748 fee_proportional_millionths: 0,
4749 excess_data: Vec::new()
4753 // Attempt to route more than available results in a failure.
4754 let route_params = RouteParameters::from_payment_params_and_value(
4755 payment_params.clone(), 15_001);
4756 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4757 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4758 &scorer, &Default::default(), &random_seed_bytes) {
4759 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4760 } else { panic!(); }
4764 // Now, attempt to route an exact amount we have should be fine.
4765 let route_params = RouteParameters::from_payment_params_and_value(
4766 payment_params.clone(), 15_000);
4767 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4768 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4769 assert_eq!(route.paths.len(), 1);
4770 let path = route.paths.last().unwrap();
4771 assert_eq!(path.hops.len(), 2);
4772 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4773 assert_eq!(path.final_value_msat(), 15_000);
4776 // Now let's see if routing works if we know only capacity from the UTXO.
4778 // We can't change UTXO capacity on the fly, so we'll disable
4779 // the existing channel and add another one with the capacity we need.
4780 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4781 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4782 short_channel_id: 3,
4785 cltv_expiry_delta: 0,
4786 htlc_minimum_msat: 0,
4787 htlc_maximum_msat: MAX_VALUE_MSAT,
4789 fee_proportional_millionths: 0,
4790 excess_data: Vec::new()
4793 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4794 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4795 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4796 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4797 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4799 *chain_monitor.utxo_ret.lock().unwrap() =
4800 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4801 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4803 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4804 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4805 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4806 short_channel_id: 333,
4809 cltv_expiry_delta: (3 << 4) | 1,
4810 htlc_minimum_msat: 0,
4811 htlc_maximum_msat: 15_000,
4813 fee_proportional_millionths: 0,
4814 excess_data: Vec::new()
4816 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4817 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4818 short_channel_id: 333,
4821 cltv_expiry_delta: (3 << 4) | 2,
4822 htlc_minimum_msat: 0,
4823 htlc_maximum_msat: 15_000,
4825 fee_proportional_millionths: 0,
4826 excess_data: Vec::new()
4830 // Attempt to route more than available results in a failure.
4831 let route_params = RouteParameters::from_payment_params_and_value(
4832 payment_params.clone(), 15_001);
4833 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4834 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4835 &scorer, &Default::default(), &random_seed_bytes) {
4836 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4837 } else { panic!(); }
4841 // Now, attempt to route an exact amount we have should be fine.
4842 let route_params = RouteParameters::from_payment_params_and_value(
4843 payment_params.clone(), 15_000);
4844 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4845 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4846 assert_eq!(route.paths.len(), 1);
4847 let path = route.paths.last().unwrap();
4848 assert_eq!(path.hops.len(), 2);
4849 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4850 assert_eq!(path.final_value_msat(), 15_000);
4853 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4854 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4855 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4856 short_channel_id: 333,
4859 cltv_expiry_delta: 0,
4860 htlc_minimum_msat: 0,
4861 htlc_maximum_msat: 10_000,
4863 fee_proportional_millionths: 0,
4864 excess_data: Vec::new()
4868 // Attempt to route more than available results in a failure.
4869 let route_params = RouteParameters::from_payment_params_and_value(
4870 payment_params.clone(), 10_001);
4871 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4872 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4873 &scorer, &Default::default(), &random_seed_bytes) {
4874 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4875 } else { panic!(); }
4879 // Now, attempt to route an exact amount we have should be fine.
4880 let route_params = RouteParameters::from_payment_params_and_value(
4881 payment_params.clone(), 10_000);
4882 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4883 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4884 assert_eq!(route.paths.len(), 1);
4885 let path = route.paths.last().unwrap();
4886 assert_eq!(path.hops.len(), 2);
4887 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4888 assert_eq!(path.final_value_msat(), 10_000);
4893 fn available_liquidity_last_hop_test() {
4894 // Check that available liquidity properly limits the path even when only
4895 // one of the latter hops is limited.
4896 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4897 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4898 let scorer = ln_test_utils::TestScorer::new();
4899 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4900 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4901 let config = UserConfig::default();
4902 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4903 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4906 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4907 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4908 // Total capacity: 50 sats.
4910 // Disable other potential paths.
4911 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4912 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4913 short_channel_id: 2,
4916 cltv_expiry_delta: 0,
4917 htlc_minimum_msat: 0,
4918 htlc_maximum_msat: 100_000,
4920 fee_proportional_millionths: 0,
4921 excess_data: Vec::new()
4923 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4924 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4925 short_channel_id: 7,
4928 cltv_expiry_delta: 0,
4929 htlc_minimum_msat: 0,
4930 htlc_maximum_msat: 100_000,
4932 fee_proportional_millionths: 0,
4933 excess_data: Vec::new()
4938 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4939 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4940 short_channel_id: 12,
4943 cltv_expiry_delta: 0,
4944 htlc_minimum_msat: 0,
4945 htlc_maximum_msat: 100_000,
4947 fee_proportional_millionths: 0,
4948 excess_data: Vec::new()
4950 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4951 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4952 short_channel_id: 13,
4955 cltv_expiry_delta: 0,
4956 htlc_minimum_msat: 0,
4957 htlc_maximum_msat: 100_000,
4959 fee_proportional_millionths: 0,
4960 excess_data: Vec::new()
4963 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4964 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4965 short_channel_id: 6,
4968 cltv_expiry_delta: 0,
4969 htlc_minimum_msat: 0,
4970 htlc_maximum_msat: 50_000,
4972 fee_proportional_millionths: 0,
4973 excess_data: Vec::new()
4975 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4976 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4977 short_channel_id: 11,
4980 cltv_expiry_delta: 0,
4981 htlc_minimum_msat: 0,
4982 htlc_maximum_msat: 100_000,
4984 fee_proportional_millionths: 0,
4985 excess_data: Vec::new()
4988 // Attempt to route more than available results in a failure.
4989 let route_params = RouteParameters::from_payment_params_and_value(
4990 payment_params.clone(), 60_000);
4991 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4992 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4993 &scorer, &Default::default(), &random_seed_bytes) {
4994 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4995 } else { panic!(); }
4999 // Now, attempt to route 49 sats (just a bit below the capacity).
5000 let route_params = RouteParameters::from_payment_params_and_value(
5001 payment_params.clone(), 49_000);
5002 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5003 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5004 assert_eq!(route.paths.len(), 1);
5005 let mut total_amount_paid_msat = 0;
5006 for path in &route.paths {
5007 assert_eq!(path.hops.len(), 4);
5008 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5009 total_amount_paid_msat += path.final_value_msat();
5011 assert_eq!(total_amount_paid_msat, 49_000);
5015 // Attempt to route an exact amount is also fine
5016 let route_params = RouteParameters::from_payment_params_and_value(
5017 payment_params, 50_000);
5018 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5019 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5020 assert_eq!(route.paths.len(), 1);
5021 let mut total_amount_paid_msat = 0;
5022 for path in &route.paths {
5023 assert_eq!(path.hops.len(), 4);
5024 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5025 total_amount_paid_msat += path.final_value_msat();
5027 assert_eq!(total_amount_paid_msat, 50_000);
5032 fn ignore_fee_first_hop_test() {
5033 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5034 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5035 let scorer = ln_test_utils::TestScorer::new();
5036 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5037 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5038 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5040 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5041 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5042 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5043 short_channel_id: 1,
5046 cltv_expiry_delta: 0,
5047 htlc_minimum_msat: 0,
5048 htlc_maximum_msat: 100_000,
5049 fee_base_msat: 1_000_000,
5050 fee_proportional_millionths: 0,
5051 excess_data: Vec::new()
5053 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5054 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5055 short_channel_id: 3,
5058 cltv_expiry_delta: 0,
5059 htlc_minimum_msat: 0,
5060 htlc_maximum_msat: 50_000,
5062 fee_proportional_millionths: 0,
5063 excess_data: Vec::new()
5067 let route_params = RouteParameters::from_payment_params_and_value(
5068 payment_params, 50_000);
5069 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5070 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5071 assert_eq!(route.paths.len(), 1);
5072 let mut total_amount_paid_msat = 0;
5073 for path in &route.paths {
5074 assert_eq!(path.hops.len(), 2);
5075 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5076 total_amount_paid_msat += path.final_value_msat();
5078 assert_eq!(total_amount_paid_msat, 50_000);
5083 fn simple_mpp_route_test() {
5084 let (secp_ctx, _, _, _, _) = build_graph();
5085 let (_, _, _, nodes) = get_nodes(&secp_ctx);
5086 let config = UserConfig::default();
5087 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5088 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5090 do_simple_mpp_route_test(clear_payment_params);
5092 // MPP to a 1-hop blinded path for nodes[2]
5093 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
5094 let blinded_path = BlindedPath {
5095 introduction_node_id: nodes[2],
5096 blinding_point: ln_test_utils::pubkey(42),
5097 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
5099 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
5101 fee_proportional_millionths: 0,
5102 htlc_minimum_msat: 0,
5103 htlc_maximum_msat: 0,
5104 cltv_expiry_delta: 0,
5105 features: BlindedHopFeatures::empty(),
5107 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
5108 .with_bolt12_features(bolt12_features.clone()).unwrap();
5109 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
5111 // MPP to 3 2-hop blinded paths
5112 let mut blinded_path_node_0 = blinded_path.clone();
5113 blinded_path_node_0.introduction_node_id = nodes[0];
5114 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
5115 let mut node_0_payinfo = blinded_payinfo.clone();
5116 node_0_payinfo.htlc_maximum_msat = 50_000;
5118 let mut blinded_path_node_7 = blinded_path_node_0.clone();
5119 blinded_path_node_7.introduction_node_id = nodes[7];
5120 let mut node_7_payinfo = blinded_payinfo.clone();
5121 node_7_payinfo.htlc_maximum_msat = 60_000;
5123 let mut blinded_path_node_1 = blinded_path_node_0.clone();
5124 blinded_path_node_1.introduction_node_id = nodes[1];
5125 let mut node_1_payinfo = blinded_payinfo.clone();
5126 node_1_payinfo.htlc_maximum_msat = 180_000;
5128 let two_hop_blinded_payment_params = PaymentParameters::blinded(
5130 (node_0_payinfo, blinded_path_node_0),
5131 (node_7_payinfo, blinded_path_node_7),
5132 (node_1_payinfo, blinded_path_node_1)
5134 .with_bolt12_features(bolt12_features).unwrap();
5135 do_simple_mpp_route_test(two_hop_blinded_payment_params);
5139 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
5140 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5141 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5142 let scorer = ln_test_utils::TestScorer::new();
5143 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5144 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5146 // We need a route consisting of 3 paths:
5147 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5148 // To achieve this, the amount being transferred should be around
5149 // the total capacity of these 3 paths.
5151 // First, we set limits on these (previously unlimited) channels.
5152 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
5154 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5155 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5156 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5157 short_channel_id: 1,
5160 cltv_expiry_delta: 0,
5161 htlc_minimum_msat: 0,
5162 htlc_maximum_msat: 100_000,
5164 fee_proportional_millionths: 0,
5165 excess_data: Vec::new()
5167 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5168 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5169 short_channel_id: 3,
5172 cltv_expiry_delta: 0,
5173 htlc_minimum_msat: 0,
5174 htlc_maximum_msat: 50_000,
5176 fee_proportional_millionths: 0,
5177 excess_data: Vec::new()
5180 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
5181 // (total limit 60).
5182 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5183 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5184 short_channel_id: 12,
5187 cltv_expiry_delta: 0,
5188 htlc_minimum_msat: 0,
5189 htlc_maximum_msat: 60_000,
5191 fee_proportional_millionths: 0,
5192 excess_data: Vec::new()
5194 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5195 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5196 short_channel_id: 13,
5199 cltv_expiry_delta: 0,
5200 htlc_minimum_msat: 0,
5201 htlc_maximum_msat: 60_000,
5203 fee_proportional_millionths: 0,
5204 excess_data: Vec::new()
5207 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5208 // (total capacity 180 sats).
5209 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5210 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5211 short_channel_id: 2,
5214 cltv_expiry_delta: 0,
5215 htlc_minimum_msat: 0,
5216 htlc_maximum_msat: 200_000,
5218 fee_proportional_millionths: 0,
5219 excess_data: Vec::new()
5221 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5222 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5223 short_channel_id: 4,
5226 cltv_expiry_delta: 0,
5227 htlc_minimum_msat: 0,
5228 htlc_maximum_msat: 180_000,
5230 fee_proportional_millionths: 0,
5231 excess_data: Vec::new()
5235 // Attempt to route more than available results in a failure.
5236 let route_params = RouteParameters::from_payment_params_and_value(
5237 payment_params.clone(), 300_000);
5238 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5239 &our_id, &route_params, &network_graph.read_only(), None,
5240 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5241 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5242 } else { panic!(); }
5246 // Attempt to route while setting max_path_count to 0 results in a failure.
5247 let zero_payment_params = payment_params.clone().with_max_path_count(0);
5248 let route_params = RouteParameters::from_payment_params_and_value(
5249 zero_payment_params, 100);
5250 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5251 &our_id, &route_params, &network_graph.read_only(), None,
5252 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5253 assert_eq!(err, "Can't find a route with no paths allowed.");
5254 } else { panic!(); }
5258 // Attempt to route while setting max_path_count to 3 results in a failure.
5259 // This is the case because the minimal_value_contribution_msat would require each path
5260 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5261 let fail_payment_params = payment_params.clone().with_max_path_count(3);
5262 let route_params = RouteParameters::from_payment_params_and_value(
5263 fail_payment_params, 250_000);
5264 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5265 &our_id, &route_params, &network_graph.read_only(), None,
5266 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5267 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5268 } else { panic!(); }
5272 // Now, attempt to route 250 sats (just a bit below the capacity).
5273 // Our algorithm should provide us with these 3 paths.
5274 let route_params = RouteParameters::from_payment_params_and_value(
5275 payment_params.clone(), 250_000);
5276 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5277 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5278 assert_eq!(route.paths.len(), 3);
5279 let mut total_amount_paid_msat = 0;
5280 for path in &route.paths {
5281 if let Some(bt) = &path.blinded_tail {
5282 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5284 assert_eq!(path.hops.len(), 2);
5285 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5287 total_amount_paid_msat += path.final_value_msat();
5289 assert_eq!(total_amount_paid_msat, 250_000);
5293 // Attempt to route an exact amount is also fine
5294 let route_params = RouteParameters::from_payment_params_and_value(
5295 payment_params.clone(), 290_000);
5296 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5297 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5298 assert_eq!(route.paths.len(), 3);
5299 let mut total_amount_paid_msat = 0;
5300 for path in &route.paths {
5301 if payment_params.payee.blinded_route_hints().len() != 0 {
5302 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5303 if let Some(bt) = &path.blinded_tail {
5304 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5305 if bt.hops.len() > 1 {
5306 assert_eq!(path.hops.last().unwrap().pubkey,
5307 payment_params.payee.blinded_route_hints().iter()
5308 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5309 .map(|(_, p)| p.introduction_node_id).unwrap());
5311 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5314 assert_eq!(path.hops.len(), 2);
5315 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5317 total_amount_paid_msat += path.final_value_msat();
5319 assert_eq!(total_amount_paid_msat, 290_000);
5324 fn long_mpp_route_test() {
5325 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5326 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5327 let scorer = ln_test_utils::TestScorer::new();
5328 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5329 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5330 let config = UserConfig::default();
5331 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5332 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5335 // We need a route consisting of 3 paths:
5336 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5337 // Note that these paths overlap (channels 5, 12, 13).
5338 // We will route 300 sats.
5339 // Each path will have 100 sats capacity, those channels which
5340 // are used twice will have 200 sats capacity.
5342 // Disable other potential paths.
5343 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5344 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5345 short_channel_id: 2,
5348 cltv_expiry_delta: 0,
5349 htlc_minimum_msat: 0,
5350 htlc_maximum_msat: 100_000,
5352 fee_proportional_millionths: 0,
5353 excess_data: Vec::new()
5355 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5356 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5357 short_channel_id: 7,
5360 cltv_expiry_delta: 0,
5361 htlc_minimum_msat: 0,
5362 htlc_maximum_msat: 100_000,
5364 fee_proportional_millionths: 0,
5365 excess_data: Vec::new()
5368 // Path via {node0, node2} is channels {1, 3, 5}.
5369 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5370 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5371 short_channel_id: 1,
5374 cltv_expiry_delta: 0,
5375 htlc_minimum_msat: 0,
5376 htlc_maximum_msat: 100_000,
5378 fee_proportional_millionths: 0,
5379 excess_data: Vec::new()
5381 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5382 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5383 short_channel_id: 3,
5386 cltv_expiry_delta: 0,
5387 htlc_minimum_msat: 0,
5388 htlc_maximum_msat: 100_000,
5390 fee_proportional_millionths: 0,
5391 excess_data: Vec::new()
5394 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5395 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5396 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5397 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5398 short_channel_id: 5,
5401 cltv_expiry_delta: 0,
5402 htlc_minimum_msat: 0,
5403 htlc_maximum_msat: 200_000,
5405 fee_proportional_millionths: 0,
5406 excess_data: Vec::new()
5409 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5410 // Add 100 sats to the capacities of {12, 13}, because these channels
5411 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5412 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5413 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5414 short_channel_id: 12,
5417 cltv_expiry_delta: 0,
5418 htlc_minimum_msat: 0,
5419 htlc_maximum_msat: 200_000,
5421 fee_proportional_millionths: 0,
5422 excess_data: Vec::new()
5424 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5425 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5426 short_channel_id: 13,
5429 cltv_expiry_delta: 0,
5430 htlc_minimum_msat: 0,
5431 htlc_maximum_msat: 200_000,
5433 fee_proportional_millionths: 0,
5434 excess_data: Vec::new()
5437 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5438 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5439 short_channel_id: 6,
5442 cltv_expiry_delta: 0,
5443 htlc_minimum_msat: 0,
5444 htlc_maximum_msat: 100_000,
5446 fee_proportional_millionths: 0,
5447 excess_data: Vec::new()
5449 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5450 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5451 short_channel_id: 11,
5454 cltv_expiry_delta: 0,
5455 htlc_minimum_msat: 0,
5456 htlc_maximum_msat: 100_000,
5458 fee_proportional_millionths: 0,
5459 excess_data: Vec::new()
5462 // Path via {node7, node2} is channels {12, 13, 5}.
5463 // We already limited them to 200 sats (they are used twice for 100 sats).
5464 // Nothing to do here.
5467 // Attempt to route more than available results in a failure.
5468 let route_params = RouteParameters::from_payment_params_and_value(
5469 payment_params.clone(), 350_000);
5470 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5471 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5472 &scorer, &Default::default(), &random_seed_bytes) {
5473 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5474 } else { panic!(); }
5478 // Now, attempt to route 300 sats (exact amount we can route).
5479 // Our algorithm should provide us with these 3 paths, 100 sats each.
5480 let route_params = RouteParameters::from_payment_params_and_value(
5481 payment_params, 300_000);
5482 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5483 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5484 assert_eq!(route.paths.len(), 3);
5486 let mut total_amount_paid_msat = 0;
5487 for path in &route.paths {
5488 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5489 total_amount_paid_msat += path.final_value_msat();
5491 assert_eq!(total_amount_paid_msat, 300_000);
5497 fn mpp_cheaper_route_test() {
5498 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5499 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5500 let scorer = ln_test_utils::TestScorer::new();
5501 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5502 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5503 let config = UserConfig::default();
5504 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5505 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5508 // This test checks that if we have two cheaper paths and one more expensive path,
5509 // so that liquidity-wise any 2 of 3 combination is sufficient,
5510 // two cheaper paths will be taken.
5511 // These paths have equal available liquidity.
5513 // We need a combination of 3 paths:
5514 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5515 // Note that these paths overlap (channels 5, 12, 13).
5516 // Each path will have 100 sats capacity, those channels which
5517 // are used twice will have 200 sats capacity.
5519 // Disable other potential paths.
5520 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5521 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5522 short_channel_id: 2,
5525 cltv_expiry_delta: 0,
5526 htlc_minimum_msat: 0,
5527 htlc_maximum_msat: 100_000,
5529 fee_proportional_millionths: 0,
5530 excess_data: Vec::new()
5532 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5533 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5534 short_channel_id: 7,
5537 cltv_expiry_delta: 0,
5538 htlc_minimum_msat: 0,
5539 htlc_maximum_msat: 100_000,
5541 fee_proportional_millionths: 0,
5542 excess_data: Vec::new()
5545 // Path via {node0, node2} is channels {1, 3, 5}.
5546 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5547 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5548 short_channel_id: 1,
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()
5558 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5559 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5560 short_channel_id: 3,
5563 cltv_expiry_delta: 0,
5564 htlc_minimum_msat: 0,
5565 htlc_maximum_msat: 100_000,
5567 fee_proportional_millionths: 0,
5568 excess_data: Vec::new()
5571 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5572 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5573 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5574 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5575 short_channel_id: 5,
5578 cltv_expiry_delta: 0,
5579 htlc_minimum_msat: 0,
5580 htlc_maximum_msat: 200_000,
5582 fee_proportional_millionths: 0,
5583 excess_data: Vec::new()
5586 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5587 // Add 100 sats to the capacities of {12, 13}, because these channels
5588 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5589 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5590 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5591 short_channel_id: 12,
5594 cltv_expiry_delta: 0,
5595 htlc_minimum_msat: 0,
5596 htlc_maximum_msat: 200_000,
5598 fee_proportional_millionths: 0,
5599 excess_data: Vec::new()
5601 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5602 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5603 short_channel_id: 13,
5606 cltv_expiry_delta: 0,
5607 htlc_minimum_msat: 0,
5608 htlc_maximum_msat: 200_000,
5610 fee_proportional_millionths: 0,
5611 excess_data: Vec::new()
5614 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5615 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5616 short_channel_id: 6,
5619 cltv_expiry_delta: 0,
5620 htlc_minimum_msat: 0,
5621 htlc_maximum_msat: 100_000,
5622 fee_base_msat: 1_000,
5623 fee_proportional_millionths: 0,
5624 excess_data: Vec::new()
5626 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5627 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5628 short_channel_id: 11,
5631 cltv_expiry_delta: 0,
5632 htlc_minimum_msat: 0,
5633 htlc_maximum_msat: 100_000,
5635 fee_proportional_millionths: 0,
5636 excess_data: Vec::new()
5639 // Path via {node7, node2} is channels {12, 13, 5}.
5640 // We already limited them to 200 sats (they are used twice for 100 sats).
5641 // Nothing to do here.
5644 // Now, attempt to route 180 sats.
5645 // Our algorithm should provide us with these 2 paths.
5646 let route_params = RouteParameters::from_payment_params_and_value(
5647 payment_params, 180_000);
5648 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5649 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5650 assert_eq!(route.paths.len(), 2);
5652 let mut total_value_transferred_msat = 0;
5653 let mut total_paid_msat = 0;
5654 for path in &route.paths {
5655 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5656 total_value_transferred_msat += path.final_value_msat();
5657 for hop in &path.hops {
5658 total_paid_msat += hop.fee_msat;
5661 // If we paid fee, this would be higher.
5662 assert_eq!(total_value_transferred_msat, 180_000);
5663 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5664 assert_eq!(total_fees_paid, 0);
5669 fn fees_on_mpp_route_test() {
5670 // This test makes sure that MPP algorithm properly takes into account
5671 // fees charged on the channels, by making the fees impactful:
5672 // if the fee is not properly accounted for, the behavior is different.
5673 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5674 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5675 let scorer = ln_test_utils::TestScorer::new();
5676 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5677 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5678 let config = UserConfig::default();
5679 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5680 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5683 // We need a route consisting of 2 paths:
5684 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5685 // We will route 200 sats, Each path will have 100 sats capacity.
5687 // This test is not particularly stable: e.g.,
5688 // there's a way to route via {node0, node2, node4}.
5689 // It works while pathfinding is deterministic, but can be broken otherwise.
5690 // It's fine to ignore this concern for now.
5692 // Disable other potential paths.
5693 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5694 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5695 short_channel_id: 2,
5698 cltv_expiry_delta: 0,
5699 htlc_minimum_msat: 0,
5700 htlc_maximum_msat: 100_000,
5702 fee_proportional_millionths: 0,
5703 excess_data: Vec::new()
5706 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5707 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5708 short_channel_id: 7,
5711 cltv_expiry_delta: 0,
5712 htlc_minimum_msat: 0,
5713 htlc_maximum_msat: 100_000,
5715 fee_proportional_millionths: 0,
5716 excess_data: Vec::new()
5719 // Path via {node0, node2} is channels {1, 3, 5}.
5720 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5721 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5722 short_channel_id: 1,
5725 cltv_expiry_delta: 0,
5726 htlc_minimum_msat: 0,
5727 htlc_maximum_msat: 100_000,
5729 fee_proportional_millionths: 0,
5730 excess_data: Vec::new()
5732 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5733 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5734 short_channel_id: 3,
5737 cltv_expiry_delta: 0,
5738 htlc_minimum_msat: 0,
5739 htlc_maximum_msat: 100_000,
5741 fee_proportional_millionths: 0,
5742 excess_data: Vec::new()
5745 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5746 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5747 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5748 short_channel_id: 5,
5751 cltv_expiry_delta: 0,
5752 htlc_minimum_msat: 0,
5753 htlc_maximum_msat: 100_000,
5755 fee_proportional_millionths: 0,
5756 excess_data: Vec::new()
5759 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5760 // All channels should be 100 sats capacity. But for the fee experiment,
5761 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5762 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5763 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5764 // so no matter how large are other channels,
5765 // the whole path will be limited by 100 sats with just these 2 conditions:
5766 // - channel 12 capacity is 250 sats
5767 // - fee for channel 6 is 150 sats
5768 // Let's test this by enforcing these 2 conditions and removing other limits.
5769 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5770 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5771 short_channel_id: 12,
5774 cltv_expiry_delta: 0,
5775 htlc_minimum_msat: 0,
5776 htlc_maximum_msat: 250_000,
5778 fee_proportional_millionths: 0,
5779 excess_data: Vec::new()
5781 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5782 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5783 short_channel_id: 13,
5786 cltv_expiry_delta: 0,
5787 htlc_minimum_msat: 0,
5788 htlc_maximum_msat: MAX_VALUE_MSAT,
5790 fee_proportional_millionths: 0,
5791 excess_data: Vec::new()
5794 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5795 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5796 short_channel_id: 6,
5799 cltv_expiry_delta: 0,
5800 htlc_minimum_msat: 0,
5801 htlc_maximum_msat: MAX_VALUE_MSAT,
5802 fee_base_msat: 150_000,
5803 fee_proportional_millionths: 0,
5804 excess_data: Vec::new()
5806 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5807 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5808 short_channel_id: 11,
5811 cltv_expiry_delta: 0,
5812 htlc_minimum_msat: 0,
5813 htlc_maximum_msat: MAX_VALUE_MSAT,
5815 fee_proportional_millionths: 0,
5816 excess_data: Vec::new()
5820 // Attempt to route more than available results in a failure.
5821 let route_params = RouteParameters::from_payment_params_and_value(
5822 payment_params.clone(), 210_000);
5823 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5824 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5825 &scorer, &Default::default(), &random_seed_bytes) {
5826 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5827 } else { panic!(); }
5831 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5832 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5833 max_total_routing_fee_msat: Some(149_999) };
5834 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5835 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5836 &scorer, &Default::default(), &random_seed_bytes) {
5837 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5838 } else { panic!(); }
5842 // Now, attempt to route 200 sats (exact amount we can route).
5843 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5844 max_total_routing_fee_msat: Some(150_000) };
5845 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5846 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5847 assert_eq!(route.paths.len(), 2);
5849 let mut total_amount_paid_msat = 0;
5850 for path in &route.paths {
5851 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5852 total_amount_paid_msat += path.final_value_msat();
5854 assert_eq!(total_amount_paid_msat, 200_000);
5855 assert_eq!(route.get_total_fees(), 150_000);
5860 fn mpp_with_last_hops() {
5861 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5862 // via a single last-hop route hint, we'd fail to route if we first collected routes
5863 // totaling close but not quite enough to fund the full payment.
5865 // This was because we considered last-hop hints to have exactly the sought payment amount
5866 // instead of the amount we were trying to collect, needlessly limiting our path searching
5867 // at the very first hop.
5869 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5870 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5871 // to only have the remaining to-collect amount in available liquidity.
5873 // This bug appeared in production in some specific channel configurations.
5874 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5875 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5876 let scorer = ln_test_utils::TestScorer::new();
5877 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5878 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5879 let config = UserConfig::default();
5880 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
5881 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
5882 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5883 src_node_id: nodes[2],
5884 short_channel_id: 42,
5885 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5886 cltv_expiry_delta: 42,
5887 htlc_minimum_msat: None,
5888 htlc_maximum_msat: None,
5889 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5891 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5892 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5893 // would first use the no-fee route and then fail to find a path along the second route as
5894 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5895 // under 5% of our payment amount.
5896 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5897 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5898 short_channel_id: 1,
5901 cltv_expiry_delta: (5 << 4) | 5,
5902 htlc_minimum_msat: 0,
5903 htlc_maximum_msat: 99_000,
5904 fee_base_msat: u32::max_value(),
5905 fee_proportional_millionths: u32::max_value(),
5906 excess_data: Vec::new()
5908 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5909 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5910 short_channel_id: 2,
5913 cltv_expiry_delta: (5 << 4) | 3,
5914 htlc_minimum_msat: 0,
5915 htlc_maximum_msat: 99_000,
5916 fee_base_msat: u32::max_value(),
5917 fee_proportional_millionths: u32::max_value(),
5918 excess_data: Vec::new()
5920 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5921 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5922 short_channel_id: 4,
5925 cltv_expiry_delta: (4 << 4) | 1,
5926 htlc_minimum_msat: 0,
5927 htlc_maximum_msat: MAX_VALUE_MSAT,
5929 fee_proportional_millionths: 0,
5930 excess_data: Vec::new()
5932 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5933 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5934 short_channel_id: 13,
5936 flags: 0|2, // Channel disabled
5937 cltv_expiry_delta: (13 << 4) | 1,
5938 htlc_minimum_msat: 0,
5939 htlc_maximum_msat: MAX_VALUE_MSAT,
5941 fee_proportional_millionths: 2000000,
5942 excess_data: Vec::new()
5945 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5947 let route_params = RouteParameters::from_payment_params_and_value(
5948 payment_params, 100_000);
5949 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5950 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5951 assert_eq!(route.paths.len(), 2);
5952 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5953 // Paths are manually ordered ordered by SCID, so:
5954 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5955 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5956 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5957 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5958 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5959 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5960 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5961 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5962 assert_eq!(route.get_total_fees(), 1);
5963 assert_eq!(route.get_total_amount(), 100_000);
5967 fn drop_lowest_channel_mpp_route_test() {
5968 // This test checks that low-capacity channel is dropped when after
5969 // path finding we realize that we found more capacity than we need.
5970 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5971 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5972 let scorer = ln_test_utils::TestScorer::new();
5973 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5974 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5975 let config = UserConfig::default();
5976 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5977 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5979 .with_max_channel_saturation_power_of_half(0);
5981 // We need a route consisting of 3 paths:
5982 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5984 // The first and the second paths should be sufficient, but the third should be
5985 // cheaper, so that we select it but drop later.
5987 // First, we set limits on these (previously unlimited) channels.
5988 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5990 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5991 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5992 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5993 short_channel_id: 1,
5996 cltv_expiry_delta: 0,
5997 htlc_minimum_msat: 0,
5998 htlc_maximum_msat: 100_000,
6000 fee_proportional_millionths: 0,
6001 excess_data: Vec::new()
6003 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6004 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6005 short_channel_id: 3,
6008 cltv_expiry_delta: 0,
6009 htlc_minimum_msat: 0,
6010 htlc_maximum_msat: 50_000,
6012 fee_proportional_millionths: 0,
6013 excess_data: Vec::new()
6016 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
6017 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6018 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6019 short_channel_id: 12,
6022 cltv_expiry_delta: 0,
6023 htlc_minimum_msat: 0,
6024 htlc_maximum_msat: 60_000,
6026 fee_proportional_millionths: 0,
6027 excess_data: Vec::new()
6029 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6030 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6031 short_channel_id: 13,
6034 cltv_expiry_delta: 0,
6035 htlc_minimum_msat: 0,
6036 htlc_maximum_msat: 60_000,
6038 fee_proportional_millionths: 0,
6039 excess_data: Vec::new()
6042 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
6043 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6044 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6045 short_channel_id: 2,
6048 cltv_expiry_delta: 0,
6049 htlc_minimum_msat: 0,
6050 htlc_maximum_msat: 20_000,
6052 fee_proportional_millionths: 0,
6053 excess_data: Vec::new()
6055 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6056 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6057 short_channel_id: 4,
6060 cltv_expiry_delta: 0,
6061 htlc_minimum_msat: 0,
6062 htlc_maximum_msat: 20_000,
6064 fee_proportional_millionths: 0,
6065 excess_data: Vec::new()
6069 // Attempt to route more than available results in a failure.
6070 let route_params = RouteParameters::from_payment_params_and_value(
6071 payment_params.clone(), 150_000);
6072 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6073 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6074 &scorer, &Default::default(), &random_seed_bytes) {
6075 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6076 } else { panic!(); }
6080 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
6081 // Our algorithm should provide us with these 3 paths.
6082 let route_params = RouteParameters::from_payment_params_and_value(
6083 payment_params.clone(), 125_000);
6084 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6085 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6086 assert_eq!(route.paths.len(), 3);
6087 let mut total_amount_paid_msat = 0;
6088 for path in &route.paths {
6089 assert_eq!(path.hops.len(), 2);
6090 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6091 total_amount_paid_msat += path.final_value_msat();
6093 assert_eq!(total_amount_paid_msat, 125_000);
6097 // Attempt to route without the last small cheap channel
6098 let route_params = RouteParameters::from_payment_params_and_value(
6099 payment_params, 90_000);
6100 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6101 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6102 assert_eq!(route.paths.len(), 2);
6103 let mut total_amount_paid_msat = 0;
6104 for path in &route.paths {
6105 assert_eq!(path.hops.len(), 2);
6106 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6107 total_amount_paid_msat += path.final_value_msat();
6109 assert_eq!(total_amount_paid_msat, 90_000);
6114 fn min_criteria_consistency() {
6115 // Test that we don't use an inconsistent metric between updating and walking nodes during
6116 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
6117 // was updated with a different criterion from the heap sorting, resulting in loops in
6118 // calculated paths. We test for that specific case here.
6120 // We construct a network that looks like this:
6122 // node2 -1(3)2- node3
6126 // node1 -1(5)2- node4 -1(1)2- node6
6132 // We create a loop on the side of our real path - our destination is node 6, with a
6133 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
6134 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
6135 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
6136 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
6137 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
6138 // "previous hop" being set to node 3, creating a loop in the path.
6139 let secp_ctx = Secp256k1::new();
6140 let logger = Arc::new(ln_test_utils::TestLogger::new());
6141 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6142 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
6143 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6144 let scorer = ln_test_utils::TestScorer::new();
6145 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6146 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6147 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
6149 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
6150 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6151 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6152 short_channel_id: 6,
6155 cltv_expiry_delta: (6 << 4) | 0,
6156 htlc_minimum_msat: 0,
6157 htlc_maximum_msat: MAX_VALUE_MSAT,
6159 fee_proportional_millionths: 0,
6160 excess_data: Vec::new()
6162 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
6164 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6165 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6166 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6167 short_channel_id: 5,
6170 cltv_expiry_delta: (5 << 4) | 0,
6171 htlc_minimum_msat: 0,
6172 htlc_maximum_msat: MAX_VALUE_MSAT,
6174 fee_proportional_millionths: 0,
6175 excess_data: Vec::new()
6177 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
6179 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
6180 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6181 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6182 short_channel_id: 4,
6185 cltv_expiry_delta: (4 << 4) | 0,
6186 htlc_minimum_msat: 0,
6187 htlc_maximum_msat: MAX_VALUE_MSAT,
6189 fee_proportional_millionths: 0,
6190 excess_data: Vec::new()
6192 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6194 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6195 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
6196 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6197 short_channel_id: 3,
6200 cltv_expiry_delta: (3 << 4) | 0,
6201 htlc_minimum_msat: 0,
6202 htlc_maximum_msat: MAX_VALUE_MSAT,
6204 fee_proportional_millionths: 0,
6205 excess_data: Vec::new()
6207 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6209 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6210 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
6211 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6212 short_channel_id: 2,
6215 cltv_expiry_delta: (2 << 4) | 0,
6216 htlc_minimum_msat: 0,
6217 htlc_maximum_msat: MAX_VALUE_MSAT,
6219 fee_proportional_millionths: 0,
6220 excess_data: Vec::new()
6223 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6224 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6225 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6226 short_channel_id: 1,
6229 cltv_expiry_delta: (1 << 4) | 0,
6230 htlc_minimum_msat: 100,
6231 htlc_maximum_msat: MAX_VALUE_MSAT,
6233 fee_proportional_millionths: 0,
6234 excess_data: Vec::new()
6236 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6239 // Now ensure the route flows simply over nodes 1 and 4 to 6.
6240 let route_params = RouteParameters::from_payment_params_and_value(
6241 payment_params, 10_000);
6242 let route = get_route(&our_id, &route_params, &network.read_only(), None,
6243 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6244 assert_eq!(route.paths.len(), 1);
6245 assert_eq!(route.paths[0].hops.len(), 3);
6247 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6248 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6249 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6250 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6251 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6252 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6254 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6255 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6256 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6257 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6258 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6259 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6261 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6262 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6263 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6264 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6265 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6266 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6272 fn exact_fee_liquidity_limit() {
6273 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6274 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6275 // we calculated fees on a higher value, resulting in us ignoring such paths.
6276 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6277 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6278 let scorer = ln_test_utils::TestScorer::new();
6279 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6280 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6281 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6283 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6285 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6286 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6287 short_channel_id: 2,
6290 cltv_expiry_delta: 0,
6291 htlc_minimum_msat: 0,
6292 htlc_maximum_msat: 85_000,
6294 fee_proportional_millionths: 0,
6295 excess_data: Vec::new()
6298 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6299 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6300 short_channel_id: 12,
6303 cltv_expiry_delta: (4 << 4) | 1,
6304 htlc_minimum_msat: 0,
6305 htlc_maximum_msat: 270_000,
6307 fee_proportional_millionths: 1000000,
6308 excess_data: Vec::new()
6312 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6313 // 200% fee charged channel 13 in the 1-to-2 direction.
6314 let mut route_params = RouteParameters::from_payment_params_and_value(
6315 payment_params, 90_000);
6316 route_params.max_total_routing_fee_msat = Some(90_000*2);
6317 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6318 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6319 assert_eq!(route.paths.len(), 1);
6320 assert_eq!(route.paths[0].hops.len(), 2);
6322 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6323 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6324 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6325 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6326 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6327 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6329 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6330 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6331 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6332 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6333 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6334 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6339 fn htlc_max_reduction_below_min() {
6340 // Test that if, while walking the graph, we reduce the value being sent to meet an
6341 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6342 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6343 // resulting in us thinking there is no possible path, even if other paths exist.
6344 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6345 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6346 let scorer = ln_test_utils::TestScorer::new();
6347 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6348 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6349 let config = UserConfig::default();
6350 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6351 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6354 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6355 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6356 // then try to send 90_000.
6357 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6358 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6359 short_channel_id: 2,
6362 cltv_expiry_delta: 0,
6363 htlc_minimum_msat: 0,
6364 htlc_maximum_msat: 80_000,
6366 fee_proportional_millionths: 0,
6367 excess_data: Vec::new()
6369 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6370 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6371 short_channel_id: 4,
6374 cltv_expiry_delta: (4 << 4) | 1,
6375 htlc_minimum_msat: 90_000,
6376 htlc_maximum_msat: MAX_VALUE_MSAT,
6378 fee_proportional_millionths: 0,
6379 excess_data: Vec::new()
6383 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6384 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6385 // expensive) channels 12-13 path.
6386 let mut route_params = RouteParameters::from_payment_params_and_value(
6387 payment_params, 90_000);
6388 route_params.max_total_routing_fee_msat = Some(90_000*2);
6389 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6390 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6391 assert_eq!(route.paths.len(), 1);
6392 assert_eq!(route.paths[0].hops.len(), 2);
6394 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6395 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6396 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6397 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6398 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6399 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6401 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6402 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6403 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6404 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6405 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6406 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6411 fn multiple_direct_first_hops() {
6412 // Previously we'd only ever considered one first hop path per counterparty.
6413 // However, as we don't restrict users to one channel per peer, we really need to support
6414 // looking at all first hop paths.
6415 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6416 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6417 // route over multiple channels with the same first hop.
6418 let secp_ctx = Secp256k1::new();
6419 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6420 let logger = Arc::new(ln_test_utils::TestLogger::new());
6421 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6422 let scorer = ln_test_utils::TestScorer::new();
6423 let config = UserConfig::default();
6424 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6425 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6427 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6428 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6431 let route_params = RouteParameters::from_payment_params_and_value(
6432 payment_params.clone(), 100_000);
6433 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6434 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6435 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6436 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6437 assert_eq!(route.paths.len(), 1);
6438 assert_eq!(route.paths[0].hops.len(), 1);
6440 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6441 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6442 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6445 let route_params = RouteParameters::from_payment_params_and_value(
6446 payment_params.clone(), 100_000);
6447 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6448 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6449 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6450 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6451 assert_eq!(route.paths.len(), 2);
6452 assert_eq!(route.paths[0].hops.len(), 1);
6453 assert_eq!(route.paths[1].hops.len(), 1);
6455 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6456 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6458 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6459 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6461 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6462 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6466 // If we have a bunch of outbound channels to the same node, where most are not
6467 // sufficient to pay the full payment, but one is, we should default to just using the
6468 // one single channel that has sufficient balance, avoiding MPP.
6470 // If we have several options above the 3xpayment value threshold, we should pick the
6471 // smallest of them, avoiding further fragmenting our available outbound balance to
6473 let route_params = RouteParameters::from_payment_params_and_value(
6474 payment_params, 100_000);
6475 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6476 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6477 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6478 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6479 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6480 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6481 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6482 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6483 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6484 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6485 assert_eq!(route.paths.len(), 1);
6486 assert_eq!(route.paths[0].hops.len(), 1);
6488 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6489 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6490 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6495 fn prefers_shorter_route_with_higher_fees() {
6496 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6497 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6498 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6500 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6501 let scorer = ln_test_utils::TestScorer::new();
6502 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6503 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6504 let route_params = RouteParameters::from_payment_params_and_value(
6505 payment_params.clone(), 100);
6506 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6507 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6508 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6510 assert_eq!(route.get_total_fees(), 100);
6511 assert_eq!(route.get_total_amount(), 100);
6512 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6514 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6515 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6516 let scorer = FixedPenaltyScorer::with_penalty(100);
6517 let route_params = RouteParameters::from_payment_params_and_value(
6518 payment_params, 100);
6519 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6520 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6521 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6523 assert_eq!(route.get_total_fees(), 300);
6524 assert_eq!(route.get_total_amount(), 100);
6525 assert_eq!(path, vec![2, 4, 7, 10]);
6528 struct BadChannelScorer {
6529 short_channel_id: u64,
6533 impl Writeable for BadChannelScorer {
6534 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6536 impl ScoreLookUp for BadChannelScorer {
6537 type ScoreParams = ();
6538 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6539 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6543 struct BadNodeScorer {
6548 impl Writeable for BadNodeScorer {
6549 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6552 impl ScoreLookUp for BadNodeScorer {
6553 type ScoreParams = ();
6554 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6555 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6560 fn avoids_routing_through_bad_channels_and_nodes() {
6561 let (secp_ctx, network, _, _, logger) = build_graph();
6562 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6563 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6564 let network_graph = network.read_only();
6566 // A path to nodes[6] exists when no penalties are applied to any channel.
6567 let scorer = ln_test_utils::TestScorer::new();
6568 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6569 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6570 let route_params = RouteParameters::from_payment_params_and_value(
6571 payment_params, 100);
6572 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6573 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6574 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6576 assert_eq!(route.get_total_fees(), 100);
6577 assert_eq!(route.get_total_amount(), 100);
6578 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6580 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6581 let scorer = BadChannelScorer { short_channel_id: 6 };
6582 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6583 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6584 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6586 assert_eq!(route.get_total_fees(), 300);
6587 assert_eq!(route.get_total_amount(), 100);
6588 assert_eq!(path, vec![2, 4, 7, 10]);
6590 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6591 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6592 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6593 &scorer, &Default::default(), &random_seed_bytes) {
6594 Err(LightningError { err, .. } ) => {
6595 assert_eq!(err, "Failed to find a path to the given destination");
6597 Ok(_) => panic!("Expected error"),
6602 fn total_fees_single_path() {
6604 paths: vec![Path { hops: vec![
6606 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6607 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6608 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6611 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6612 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6613 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6616 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6617 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6618 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6620 ], blinded_tail: None }],
6624 assert_eq!(route.get_total_fees(), 250);
6625 assert_eq!(route.get_total_amount(), 225);
6629 fn total_fees_multi_path() {
6631 paths: vec![Path { hops: vec![
6633 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6634 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6635 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6638 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6639 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6640 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6642 ], blinded_tail: None }, Path { hops: vec![
6644 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6645 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6646 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6649 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6650 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6651 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6653 ], blinded_tail: None }],
6657 assert_eq!(route.get_total_fees(), 200);
6658 assert_eq!(route.get_total_amount(), 300);
6662 fn total_empty_route_no_panic() {
6663 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6664 // would both panic if the route was completely empty. We test to ensure they return 0
6665 // here, even though its somewhat nonsensical as a route.
6666 let route = Route { paths: Vec::new(), route_params: None };
6668 assert_eq!(route.get_total_fees(), 0);
6669 assert_eq!(route.get_total_amount(), 0);
6673 fn limits_total_cltv_delta() {
6674 let (secp_ctx, network, _, _, logger) = build_graph();
6675 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6676 let network_graph = network.read_only();
6678 let scorer = ln_test_utils::TestScorer::new();
6680 // Make sure that generally there is at least one route available
6681 let feasible_max_total_cltv_delta = 1008;
6682 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6683 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6684 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6685 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6686 let route_params = RouteParameters::from_payment_params_and_value(
6687 feasible_payment_params, 100);
6688 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6689 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6690 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6691 assert_ne!(path.len(), 0);
6693 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6694 let fail_max_total_cltv_delta = 23;
6695 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6696 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6697 let route_params = RouteParameters::from_payment_params_and_value(
6698 fail_payment_params, 100);
6699 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6700 &Default::default(), &random_seed_bytes)
6702 Err(LightningError { err, .. } ) => {
6703 assert_eq!(err, "Failed to find a path to the given destination");
6705 Ok(_) => panic!("Expected error"),
6710 fn avoids_recently_failed_paths() {
6711 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6712 // randomly inserting channels into it until we can't find a route anymore.
6713 let (secp_ctx, network, _, _, logger) = build_graph();
6714 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6715 let network_graph = network.read_only();
6717 let scorer = ln_test_utils::TestScorer::new();
6718 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6719 .with_max_path_count(1);
6720 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6721 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6723 // We should be able to find a route initially, and then after we fail a few random
6724 // channels eventually we won't be able to any longer.
6725 let route_params = RouteParameters::from_payment_params_and_value(
6726 payment_params.clone(), 100);
6727 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6728 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6730 let route_params = RouteParameters::from_payment_params_and_value(
6731 payment_params.clone(), 100);
6732 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6733 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6735 for chan in route.paths[0].hops.iter() {
6736 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6738 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6739 % route.paths[0].hops.len();
6740 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6746 fn limits_path_length() {
6747 let (secp_ctx, network, _, _, logger) = build_line_graph();
6748 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6749 let network_graph = network.read_only();
6751 let scorer = ln_test_utils::TestScorer::new();
6752 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6753 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6755 // First check we can actually create a long route on this graph.
6756 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6757 let route_params = RouteParameters::from_payment_params_and_value(
6758 feasible_payment_params, 100);
6759 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6760 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6761 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6762 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6764 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6765 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6766 let route_params = RouteParameters::from_payment_params_and_value(
6767 fail_payment_params, 100);
6768 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6769 &Default::default(), &random_seed_bytes)
6771 Err(LightningError { err, .. } ) => {
6772 assert_eq!(err, "Failed to find a path to the given destination");
6774 Ok(_) => panic!("Expected error"),
6779 fn adds_and_limits_cltv_offset() {
6780 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6781 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6783 let scorer = ln_test_utils::TestScorer::new();
6785 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6786 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6787 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6788 let route_params = RouteParameters::from_payment_params_and_value(
6789 payment_params.clone(), 100);
6790 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6791 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6792 assert_eq!(route.paths.len(), 1);
6794 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6796 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6797 let mut route_default = route.clone();
6798 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6799 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6800 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6801 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6802 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6804 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6805 let mut route_limited = route.clone();
6806 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6807 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6808 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6809 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6810 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6814 fn adds_plausible_cltv_offset() {
6815 let (secp_ctx, network, _, _, logger) = build_graph();
6816 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6817 let network_graph = network.read_only();
6818 let network_nodes = network_graph.nodes();
6819 let network_channels = network_graph.channels();
6820 let scorer = ln_test_utils::TestScorer::new();
6821 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6822 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6823 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6825 let route_params = RouteParameters::from_payment_params_and_value(
6826 payment_params.clone(), 100);
6827 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6828 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6829 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6831 let mut path_plausibility = vec![];
6833 for p in route.paths {
6834 // 1. Select random observation point
6835 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6836 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6838 prng.process_in_place(&mut random_bytes);
6839 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6840 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6842 // 2. Calculate what CLTV expiry delta we would observe there
6843 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6845 // 3. Starting from the observation point, find candidate paths
6846 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6847 candidates.push_back((observation_point, vec![]));
6849 let mut found_plausible_candidate = false;
6851 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6852 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6853 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6854 found_plausible_candidate = true;
6855 break 'candidate_loop;
6859 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6860 for channel_id in &cur_node.channels {
6861 if let Some(channel_info) = network_channels.get(&channel_id) {
6862 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6863 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6864 if cur_path_cltv_deltas.iter().sum::<u32>()
6865 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6866 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6867 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6868 candidates.push_back((*next_id, new_path_cltv_deltas));
6876 path_plausibility.push(found_plausible_candidate);
6878 assert!(path_plausibility.iter().all(|x| *x));
6882 fn builds_correct_path_from_hops() {
6883 let (secp_ctx, network, _, _, logger) = build_graph();
6884 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6885 let network_graph = network.read_only();
6887 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6888 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6890 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6891 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6892 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6893 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6894 Arc::clone(&logger), &random_seed_bytes).unwrap();
6895 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6896 assert_eq!(hops.len(), route.paths[0].hops.len());
6897 for (idx, hop_pubkey) in hops.iter().enumerate() {
6898 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6903 fn avoids_saturating_channels() {
6904 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6905 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6906 let decay_params = ProbabilisticScoringDecayParameters::default();
6907 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6909 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6910 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6911 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6912 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6913 short_channel_id: 4,
6916 cltv_expiry_delta: (4 << 4) | 1,
6917 htlc_minimum_msat: 0,
6918 htlc_maximum_msat: 250_000_000,
6920 fee_proportional_millionths: 0,
6921 excess_data: Vec::new()
6923 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6924 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6925 short_channel_id: 13,
6928 cltv_expiry_delta: (13 << 4) | 1,
6929 htlc_minimum_msat: 0,
6930 htlc_maximum_msat: 250_000_000,
6932 fee_proportional_millionths: 0,
6933 excess_data: Vec::new()
6936 let config = UserConfig::default();
6937 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6938 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6940 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6941 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6942 // 100,000 sats is less than the available liquidity on each channel, set above.
6943 let route_params = RouteParameters::from_payment_params_and_value(
6944 payment_params, 100_000_000);
6945 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6946 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6947 assert_eq!(route.paths.len(), 2);
6948 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6949 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6952 #[cfg(feature = "std")]
6953 pub(super) fn random_init_seed() -> u64 {
6954 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6955 use core::hash::{BuildHasher, Hasher};
6956 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6957 println!("Using seed of {}", seed);
6962 #[cfg(feature = "std")]
6963 fn generate_routes() {
6964 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6966 let logger = ln_test_utils::TestLogger::new();
6967 let graph = match super::bench_utils::read_network_graph(&logger) {
6975 let params = ProbabilisticScoringFeeParameters::default();
6976 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6977 let features = super::Bolt11InvoiceFeatures::empty();
6979 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6983 #[cfg(feature = "std")]
6984 fn generate_routes_mpp() {
6985 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6987 let logger = ln_test_utils::TestLogger::new();
6988 let graph = match super::bench_utils::read_network_graph(&logger) {
6996 let params = ProbabilisticScoringFeeParameters::default();
6997 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6998 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7000 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
7004 #[cfg(feature = "std")]
7005 fn generate_large_mpp_routes() {
7006 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
7008 let logger = ln_test_utils::TestLogger::new();
7009 let graph = match super::bench_utils::read_network_graph(&logger) {
7017 let params = ProbabilisticScoringFeeParameters::default();
7018 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
7019 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7021 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
7025 fn honors_manual_penalties() {
7026 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
7027 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7029 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7030 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7032 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
7033 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
7035 // First check set manual penalties are returned by the scorer.
7036 let usage = ChannelUsage {
7038 inflight_htlc_msat: 0,
7039 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
7041 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
7042 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
7043 let network_graph = network_graph.read_only();
7044 let channels = network_graph.channels();
7045 let channel = channels.get(&5).unwrap();
7046 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
7047 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop(PublicHopCandidate {
7049 short_channel_id: 5,
7051 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
7053 // Then check we can get a normal route
7054 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
7055 let route_params = RouteParameters::from_payment_params_and_value(
7056 payment_params, 100);
7057 let route = get_route(&our_id, &route_params, &network_graph, None,
7058 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
7059 assert!(route.is_ok());
7061 // Then check that we can't get a route if we ban an intermediate node.
7062 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
7063 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7064 assert!(route.is_err());
7066 // Finally make sure we can route again, when we remove the ban.
7067 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
7068 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7069 assert!(route.is_ok());
7073 fn abide_by_route_hint_max_htlc() {
7074 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
7075 // params in the final route.
7076 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7077 let netgraph = network_graph.read_only();
7078 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7079 let scorer = ln_test_utils::TestScorer::new();
7080 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7081 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7082 let config = UserConfig::default();
7084 let max_htlc_msat = 50_000;
7085 let route_hint_1 = RouteHint(vec![RouteHintHop {
7086 src_node_id: nodes[2],
7087 short_channel_id: 42,
7090 proportional_millionths: 0,
7092 cltv_expiry_delta: 10,
7093 htlc_minimum_msat: None,
7094 htlc_maximum_msat: Some(max_htlc_msat),
7096 let dest_node_id = ln_test_utils::pubkey(42);
7097 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7098 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
7099 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7102 // Make sure we'll error if our route hints don't have enough liquidity according to their
7103 // htlc_maximum_msat.
7104 let mut route_params = RouteParameters::from_payment_params_and_value(
7105 payment_params, max_htlc_msat + 1);
7106 route_params.max_total_routing_fee_msat = None;
7107 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
7108 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
7111 assert_eq!(err, "Failed to find a sufficient route to the given destination");
7112 } else { panic!(); }
7114 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
7115 let mut route_hint_2 = route_hint_1.clone();
7116 route_hint_2.0[0].short_channel_id = 43;
7117 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7118 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7119 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7121 let mut route_params = RouteParameters::from_payment_params_and_value(
7122 payment_params, max_htlc_msat + 1);
7123 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
7124 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
7125 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7126 assert_eq!(route.paths.len(), 2);
7127 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7128 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7132 fn direct_channel_to_hints_with_max_htlc() {
7133 // Check that if we have a first hop channel peer that's connected to multiple provided route
7134 // hints, that we properly split the payment between the route hints if needed.
7135 let logger = Arc::new(ln_test_utils::TestLogger::new());
7136 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7137 let scorer = ln_test_utils::TestScorer::new();
7138 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7139 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7140 let config = UserConfig::default();
7142 let our_node_id = ln_test_utils::pubkey(42);
7143 let intermed_node_id = ln_test_utils::pubkey(43);
7144 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7146 let amt_msat = 900_000;
7147 let max_htlc_msat = 500_000;
7148 let route_hint_1 = RouteHint(vec![RouteHintHop {
7149 src_node_id: intermed_node_id,
7150 short_channel_id: 44,
7153 proportional_millionths: 0,
7155 cltv_expiry_delta: 10,
7156 htlc_minimum_msat: None,
7157 htlc_maximum_msat: Some(max_htlc_msat),
7159 src_node_id: intermed_node_id,
7160 short_channel_id: 45,
7163 proportional_millionths: 0,
7165 cltv_expiry_delta: 10,
7166 htlc_minimum_msat: None,
7167 // Check that later route hint max htlcs don't override earlier ones
7168 htlc_maximum_msat: Some(max_htlc_msat - 50),
7170 let mut route_hint_2 = route_hint_1.clone();
7171 route_hint_2.0[0].short_channel_id = 46;
7172 route_hint_2.0[1].short_channel_id = 47;
7173 let dest_node_id = ln_test_utils::pubkey(44);
7174 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7175 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7176 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7179 let route_params = RouteParameters::from_payment_params_and_value(
7180 payment_params, amt_msat);
7181 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7182 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7183 &Default::default(), &random_seed_bytes).unwrap();
7184 assert_eq!(route.paths.len(), 2);
7185 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7186 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7187 assert_eq!(route.get_total_amount(), amt_msat);
7189 // Re-run but with two first hop channels connected to the same route hint peers that must be
7191 let first_hops = vec![
7192 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7193 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7195 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7196 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7197 &Default::default(), &random_seed_bytes).unwrap();
7198 assert_eq!(route.paths.len(), 2);
7199 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7200 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7201 assert_eq!(route.get_total_amount(), amt_msat);
7203 // Make sure this works for blinded route hints.
7204 let blinded_path = BlindedPath {
7205 introduction_node_id: intermed_node_id,
7206 blinding_point: ln_test_utils::pubkey(42),
7208 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
7209 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
7212 let blinded_payinfo = BlindedPayInfo {
7214 fee_proportional_millionths: 0,
7215 htlc_minimum_msat: 1,
7216 htlc_maximum_msat: max_htlc_msat,
7217 cltv_expiry_delta: 10,
7218 features: BlindedHopFeatures::empty(),
7220 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7221 let payment_params = PaymentParameters::blinded(vec![
7222 (blinded_payinfo.clone(), blinded_path.clone()),
7223 (blinded_payinfo.clone(), blinded_path.clone())])
7224 .with_bolt12_features(bolt12_features).unwrap();
7225 let route_params = RouteParameters::from_payment_params_and_value(
7226 payment_params, amt_msat);
7227 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7228 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7229 &Default::default(), &random_seed_bytes).unwrap();
7230 assert_eq!(route.paths.len(), 2);
7231 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7232 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7233 assert_eq!(route.get_total_amount(), amt_msat);
7237 fn blinded_route_ser() {
7238 let blinded_path_1 = BlindedPath {
7239 introduction_node_id: ln_test_utils::pubkey(42),
7240 blinding_point: ln_test_utils::pubkey(43),
7242 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7243 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7246 let blinded_path_2 = BlindedPath {
7247 introduction_node_id: ln_test_utils::pubkey(46),
7248 blinding_point: ln_test_utils::pubkey(47),
7250 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7251 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7254 // (De)serialize a Route with 1 blinded path out of two total paths.
7255 let mut route = Route { paths: vec![Path {
7256 hops: vec![RouteHop {
7257 pubkey: ln_test_utils::pubkey(50),
7258 node_features: NodeFeatures::empty(),
7259 short_channel_id: 42,
7260 channel_features: ChannelFeatures::empty(),
7262 cltv_expiry_delta: 0,
7263 maybe_announced_channel: true,
7265 blinded_tail: Some(BlindedTail {
7266 hops: blinded_path_1.blinded_hops,
7267 blinding_point: blinded_path_1.blinding_point,
7268 excess_final_cltv_expiry_delta: 40,
7269 final_value_msat: 100,
7271 hops: vec![RouteHop {
7272 pubkey: ln_test_utils::pubkey(51),
7273 node_features: NodeFeatures::empty(),
7274 short_channel_id: 43,
7275 channel_features: ChannelFeatures::empty(),
7277 cltv_expiry_delta: 0,
7278 maybe_announced_channel: true,
7279 }], blinded_tail: None }],
7282 let encoded_route = route.encode();
7283 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7284 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7285 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7287 // (De)serialize a Route with two paths, each containing a blinded tail.
7288 route.paths[1].blinded_tail = Some(BlindedTail {
7289 hops: blinded_path_2.blinded_hops,
7290 blinding_point: blinded_path_2.blinding_point,
7291 excess_final_cltv_expiry_delta: 41,
7292 final_value_msat: 101,
7294 let encoded_route = route.encode();
7295 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7296 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7297 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7301 fn blinded_path_inflight_processing() {
7302 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7303 // account for the blinded tail's final amount_msat.
7304 let mut inflight_htlcs = InFlightHtlcs::new();
7305 let blinded_path = BlindedPath {
7306 introduction_node_id: ln_test_utils::pubkey(43),
7307 blinding_point: ln_test_utils::pubkey(48),
7308 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7311 hops: vec![RouteHop {
7312 pubkey: ln_test_utils::pubkey(42),
7313 node_features: NodeFeatures::empty(),
7314 short_channel_id: 42,
7315 channel_features: ChannelFeatures::empty(),
7317 cltv_expiry_delta: 0,
7318 maybe_announced_channel: false,
7321 pubkey: blinded_path.introduction_node_id,
7322 node_features: NodeFeatures::empty(),
7323 short_channel_id: 43,
7324 channel_features: ChannelFeatures::empty(),
7326 cltv_expiry_delta: 0,
7327 maybe_announced_channel: false,
7329 blinded_tail: Some(BlindedTail {
7330 hops: blinded_path.blinded_hops,
7331 blinding_point: blinded_path.blinding_point,
7332 excess_final_cltv_expiry_delta: 0,
7333 final_value_msat: 200,
7336 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7337 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7338 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7342 fn blinded_path_cltv_shadow_offset() {
7343 // Make sure we add a shadow offset when sending to blinded paths.
7344 let blinded_path = BlindedPath {
7345 introduction_node_id: ln_test_utils::pubkey(43),
7346 blinding_point: ln_test_utils::pubkey(44),
7348 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7349 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7352 let mut route = Route { paths: vec![Path {
7353 hops: vec![RouteHop {
7354 pubkey: ln_test_utils::pubkey(42),
7355 node_features: NodeFeatures::empty(),
7356 short_channel_id: 42,
7357 channel_features: ChannelFeatures::empty(),
7359 cltv_expiry_delta: 0,
7360 maybe_announced_channel: false,
7363 pubkey: blinded_path.introduction_node_id,
7364 node_features: NodeFeatures::empty(),
7365 short_channel_id: 43,
7366 channel_features: ChannelFeatures::empty(),
7368 cltv_expiry_delta: 0,
7369 maybe_announced_channel: false,
7372 blinded_tail: Some(BlindedTail {
7373 hops: blinded_path.blinded_hops,
7374 blinding_point: blinded_path.blinding_point,
7375 excess_final_cltv_expiry_delta: 0,
7376 final_value_msat: 200,
7378 }], route_params: None};
7380 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7381 let (_, network_graph, _, _, _) = build_line_graph();
7382 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7383 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7384 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7388 fn simple_blinded_route_hints() {
7389 do_simple_blinded_route_hints(1);
7390 do_simple_blinded_route_hints(2);
7391 do_simple_blinded_route_hints(3);
7394 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7395 // Check that we can generate a route to a blinded path with the expected hops.
7396 let (secp_ctx, network, _, _, logger) = build_graph();
7397 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7398 let network_graph = network.read_only();
7400 let scorer = ln_test_utils::TestScorer::new();
7401 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7402 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7404 let mut blinded_path = BlindedPath {
7405 introduction_node_id: nodes[2],
7406 blinding_point: ln_test_utils::pubkey(42),
7407 blinded_hops: Vec::with_capacity(num_blinded_hops),
7409 for i in 0..num_blinded_hops {
7410 blinded_path.blinded_hops.push(
7411 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7414 let blinded_payinfo = BlindedPayInfo {
7416 fee_proportional_millionths: 500,
7417 htlc_minimum_msat: 1000,
7418 htlc_maximum_msat: 100_000_000,
7419 cltv_expiry_delta: 15,
7420 features: BlindedHopFeatures::empty(),
7423 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7424 let route_params = RouteParameters::from_payment_params_and_value(
7425 payment_params, 1001);
7426 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7427 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7428 assert_eq!(route.paths.len(), 1);
7429 assert_eq!(route.paths[0].hops.len(), 2);
7431 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7432 assert_eq!(tail.hops, blinded_path.blinded_hops);
7433 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7434 assert_eq!(tail.final_value_msat, 1001);
7436 let final_hop = route.paths[0].hops.last().unwrap();
7437 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
7438 if tail.hops.len() > 1 {
7439 assert_eq!(final_hop.fee_msat,
7440 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7441 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7443 assert_eq!(final_hop.fee_msat, 0);
7444 assert_eq!(final_hop.cltv_expiry_delta, 0);
7449 fn blinded_path_routing_errors() {
7450 // Check that we can generate a route to a blinded path with the expected hops.
7451 let (secp_ctx, network, _, _, logger) = build_graph();
7452 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7453 let network_graph = network.read_only();
7455 let scorer = ln_test_utils::TestScorer::new();
7456 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7457 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7459 let mut invalid_blinded_path = BlindedPath {
7460 introduction_node_id: nodes[2],
7461 blinding_point: ln_test_utils::pubkey(42),
7463 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7466 let blinded_payinfo = BlindedPayInfo {
7468 fee_proportional_millionths: 500,
7469 htlc_minimum_msat: 1000,
7470 htlc_maximum_msat: 100_000_000,
7471 cltv_expiry_delta: 15,
7472 features: BlindedHopFeatures::empty(),
7475 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7476 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
7477 let payment_params = PaymentParameters::blinded(vec![
7478 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7479 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7480 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7481 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7482 &scorer, &Default::default(), &random_seed_bytes)
7484 Err(LightningError { err, .. }) => {
7485 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7487 _ => panic!("Expected error")
7490 invalid_blinded_path.introduction_node_id = our_id;
7491 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7492 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7493 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7494 &Default::default(), &random_seed_bytes)
7496 Err(LightningError { err, .. }) => {
7497 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7499 _ => panic!("Expected error")
7502 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
7503 invalid_blinded_path.blinded_hops.clear();
7504 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7505 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7506 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7507 &Default::default(), &random_seed_bytes)
7509 Err(LightningError { err, .. }) => {
7510 assert_eq!(err, "0-hop blinded path provided");
7512 _ => panic!("Expected error")
7517 fn matching_intro_node_paths_provided() {
7518 // Check that if multiple blinded paths with the same intro node are provided in payment
7519 // parameters, we'll return the correct paths in the resulting MPP route.
7520 let (secp_ctx, network, _, _, logger) = build_graph();
7521 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7522 let network_graph = network.read_only();
7524 let scorer = ln_test_utils::TestScorer::new();
7525 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7526 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7527 let config = UserConfig::default();
7529 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7530 let blinded_path_1 = BlindedPath {
7531 introduction_node_id: nodes[2],
7532 blinding_point: ln_test_utils::pubkey(42),
7534 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7535 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7538 let blinded_payinfo_1 = BlindedPayInfo {
7540 fee_proportional_millionths: 0,
7541 htlc_minimum_msat: 0,
7542 htlc_maximum_msat: 30_000,
7543 cltv_expiry_delta: 0,
7544 features: BlindedHopFeatures::empty(),
7547 let mut blinded_path_2 = blinded_path_1.clone();
7548 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7549 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7550 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7552 let blinded_hints = vec![
7553 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7554 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7556 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7557 .with_bolt12_features(bolt12_features).unwrap();
7559 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7560 route_params.max_total_routing_fee_msat = Some(100_000);
7561 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7562 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7563 assert_eq!(route.paths.len(), 2);
7564 let mut total_amount_paid_msat = 0;
7565 for path in route.paths.into_iter() {
7566 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7567 if let Some(bt) = &path.blinded_tail {
7568 assert_eq!(bt.blinding_point,
7569 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7570 .map(|(_, bp)| bp.blinding_point).unwrap());
7571 } else { panic!(); }
7572 total_amount_paid_msat += path.final_value_msat();
7574 assert_eq!(total_amount_paid_msat, 100_000);
7578 fn direct_to_intro_node() {
7579 // This previously caused a debug panic in the router when asserting
7580 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7581 // direct channels we failed to account for the fee charged for use of the blinded path.
7584 // node0 -1(1)2 - node1
7585 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7586 // doesn't account for the blinded path fee.
7588 let secp_ctx = Secp256k1::new();
7589 let logger = Arc::new(ln_test_utils::TestLogger::new());
7590 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7591 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7592 let scorer = ln_test_utils::TestScorer::new();
7593 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7594 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7596 let amt_msat = 10_000_000;
7597 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7598 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7599 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7600 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7601 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7602 short_channel_id: 1,
7605 cltv_expiry_delta: 42,
7606 htlc_minimum_msat: 1_000,
7607 htlc_maximum_msat: 10_000_000,
7609 fee_proportional_millionths: 0,
7610 excess_data: Vec::new()
7612 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7613 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7614 short_channel_id: 1,
7617 cltv_expiry_delta: 42,
7618 htlc_minimum_msat: 1_000,
7619 htlc_maximum_msat: 10_000_000,
7621 fee_proportional_millionths: 0,
7622 excess_data: Vec::new()
7624 let first_hops = vec![
7625 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7627 let blinded_path = BlindedPath {
7628 introduction_node_id: nodes[1],
7629 blinding_point: ln_test_utils::pubkey(42),
7631 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7632 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7635 let blinded_payinfo = BlindedPayInfo {
7636 fee_base_msat: 1000,
7637 fee_proportional_millionths: 0,
7638 htlc_minimum_msat: 1000,
7639 htlc_maximum_msat: MAX_VALUE_MSAT,
7640 cltv_expiry_delta: 0,
7641 features: BlindedHopFeatures::empty(),
7643 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7645 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7647 let netgraph = network_graph.read_only();
7648 let route_params = RouteParameters::from_payment_params_and_value(
7649 payment_params.clone(), amt_msat);
7650 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7651 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7652 &Default::default(), &random_seed_bytes) {
7653 assert_eq!(err, "Failed to find a path to the given destination");
7654 } else { panic!("Expected error") }
7656 // Sending an exact amount accounting for the blinded path fee works.
7657 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7658 let route_params = RouteParameters::from_payment_params_and_value(
7659 payment_params, amt_minus_blinded_path_fee);
7660 let route = get_route(&nodes[0], &route_params, &netgraph,
7661 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7662 &Default::default(), &random_seed_bytes).unwrap();
7663 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7664 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7668 fn direct_to_matching_intro_nodes() {
7669 // This previously caused us to enter `unreachable` code in the following situation:
7670 // 1. We add a route candidate for intro_node contributing a high amount
7671 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7672 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7673 // amount, and update our route candidate for intro_node for the lower amount
7674 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7675 // lower contribution amount, but fail (this was previously caused by failure to account for
7676 // blinded path fees when adding first_hop<>intro_node candidates)
7677 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7678 // candidate still thinks its path is contributing the original higher amount. This caused us
7679 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7681 let secp_ctx = Secp256k1::new();
7682 let logger = Arc::new(ln_test_utils::TestLogger::new());
7683 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7684 let scorer = ln_test_utils::TestScorer::new();
7685 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7686 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7687 let config = UserConfig::default();
7689 // Values are taken from the fuzz input that uncovered this panic.
7690 let amt_msat = 21_7020_5185_1403_2640;
7691 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7692 let first_hops = vec![
7693 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7694 18446744073709551615)];
7696 let blinded_path = BlindedPath {
7697 introduction_node_id: nodes[1],
7698 blinding_point: ln_test_utils::pubkey(42),
7700 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7701 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7704 let blinded_payinfo = BlindedPayInfo {
7705 fee_base_msat: 5046_2720,
7706 fee_proportional_millionths: 0,
7707 htlc_minimum_msat: 4503_5996_2737_0496,
7708 htlc_maximum_msat: 45_0359_9627_3704_9600,
7709 cltv_expiry_delta: 0,
7710 features: BlindedHopFeatures::empty(),
7712 let mut blinded_hints = vec![
7713 (blinded_payinfo.clone(), blinded_path.clone()),
7714 (blinded_payinfo.clone(), blinded_path.clone()),
7716 blinded_hints[1].0.fee_base_msat = 419_4304;
7717 blinded_hints[1].0.fee_proportional_millionths = 257;
7718 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7719 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7720 blinded_hints[1].0.cltv_expiry_delta = 0;
7722 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7723 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7724 .with_bolt12_features(bolt12_features).unwrap();
7726 let netgraph = network_graph.read_only();
7727 let route_params = RouteParameters::from_payment_params_and_value(
7728 payment_params, amt_msat);
7729 let route = get_route(&nodes[0], &route_params, &netgraph,
7730 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7731 &Default::default(), &random_seed_bytes).unwrap();
7732 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7733 assert_eq!(route.get_total_amount(), amt_msat);
7737 fn we_are_intro_node_candidate_hops() {
7738 // This previously led to a panic in the router because we'd generate a Path with only a
7739 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7740 // where the origin node is the intro node. We now fully disallow considering candidate hops
7741 // where the origin node is the intro node.
7742 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7743 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7744 let scorer = ln_test_utils::TestScorer::new();
7745 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7746 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7747 let config = UserConfig::default();
7749 // Values are taken from the fuzz input that uncovered this panic.
7750 let amt_msat = 21_7020_5185_1423_0019;
7752 let blinded_path = BlindedPath {
7753 introduction_node_id: our_id,
7754 blinding_point: ln_test_utils::pubkey(42),
7756 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7757 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7760 let blinded_payinfo = BlindedPayInfo {
7761 fee_base_msat: 5052_9027,
7762 fee_proportional_millionths: 0,
7763 htlc_minimum_msat: 21_7020_5185_1423_0019,
7764 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7765 cltv_expiry_delta: 0,
7766 features: BlindedHopFeatures::empty(),
7768 let mut blinded_hints = vec![
7769 (blinded_payinfo.clone(), blinded_path.clone()),
7770 (blinded_payinfo.clone(), blinded_path.clone()),
7772 blinded_hints[1].1.introduction_node_id = nodes[6];
7774 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7775 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7776 .with_bolt12_features(bolt12_features.clone()).unwrap();
7778 let netgraph = network_graph.read_only();
7779 let route_params = RouteParameters::from_payment_params_and_value(
7780 payment_params, amt_msat);
7781 if let Err(LightningError { err, .. }) = get_route(
7782 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7784 assert_eq!(err, "Failed to find a path to the given destination");
7789 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7790 // This previously led to a debug panic in the router because we'd find an invalid Path with
7791 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7792 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7793 // the payment, when it was intended to only include the final value of the payment.
7794 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7795 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7796 let scorer = ln_test_utils::TestScorer::new();
7797 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7798 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7799 let config = UserConfig::default();
7801 // Values are taken from the fuzz input that uncovered this panic.
7802 let amt_msat = 21_7020_5185_1423_0019;
7804 let blinded_path = BlindedPath {
7805 introduction_node_id: our_id,
7806 blinding_point: ln_test_utils::pubkey(42),
7808 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7809 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7812 let blinded_payinfo = BlindedPayInfo {
7813 fee_base_msat: 10_4425_1395,
7814 fee_proportional_millionths: 0,
7815 htlc_minimum_msat: 21_7301_9934_9094_0931,
7816 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7817 cltv_expiry_delta: 0,
7818 features: BlindedHopFeatures::empty(),
7820 let mut blinded_hints = vec![
7821 (blinded_payinfo.clone(), blinded_path.clone()),
7822 (blinded_payinfo.clone(), blinded_path.clone()),
7823 (blinded_payinfo.clone(), blinded_path.clone()),
7825 blinded_hints[1].0.fee_base_msat = 5052_9027;
7826 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7827 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7829 blinded_hints[2].1.introduction_node_id = nodes[6];
7831 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7832 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7833 .with_bolt12_features(bolt12_features.clone()).unwrap();
7835 let netgraph = network_graph.read_only();
7836 let route_params = RouteParameters::from_payment_params_and_value(
7837 payment_params, amt_msat);
7838 if let Err(LightningError { err, .. }) = get_route(
7839 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7841 assert_eq!(err, "Failed to find a path to the given destination");
7846 fn min_htlc_overpay_violates_max_htlc() {
7847 do_min_htlc_overpay_violates_max_htlc(true);
7848 do_min_htlc_overpay_violates_max_htlc(false);
7850 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7851 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7852 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7853 // to `targets` and build an invalid path with it, and subsequently hit a debug panic asserting
7854 // that the used liquidity for a hop was less than its available liquidity limit.
7855 let secp_ctx = Secp256k1::new();
7856 let logger = Arc::new(ln_test_utils::TestLogger::new());
7857 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7858 let scorer = ln_test_utils::TestScorer::new();
7859 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7860 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7861 let config = UserConfig::default();
7863 // Values are taken from the fuzz input that uncovered this panic.
7864 let amt_msat = 7_4009_8048;
7865 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7866 let first_hop_outbound_capacity = 2_7345_2000;
7867 let first_hops = vec![get_channel_details(
7868 Some(200), nodes[0], channelmanager::provided_init_features(&config),
7869 first_hop_outbound_capacity
7872 let base_fee = 1_6778_3453;
7873 let htlc_min = 2_5165_8240;
7874 let payment_params = if blinded_payee {
7875 let blinded_path = BlindedPath {
7876 introduction_node_id: nodes[0],
7877 blinding_point: ln_test_utils::pubkey(42),
7879 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7880 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7883 let blinded_payinfo = BlindedPayInfo {
7884 fee_base_msat: base_fee,
7885 fee_proportional_millionths: 0,
7886 htlc_minimum_msat: htlc_min,
7887 htlc_maximum_msat: htlc_min * 1000,
7888 cltv_expiry_delta: 0,
7889 features: BlindedHopFeatures::empty(),
7891 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7892 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
7893 .with_bolt12_features(bolt12_features.clone()).unwrap()
7895 let route_hint = RouteHint(vec![RouteHintHop {
7896 src_node_id: nodes[0],
7897 short_channel_id: 42,
7899 base_msat: base_fee,
7900 proportional_millionths: 0,
7902 cltv_expiry_delta: 10,
7903 htlc_minimum_msat: Some(htlc_min),
7904 htlc_maximum_msat: None,
7907 PaymentParameters::from_node_id(nodes[1], 42)
7908 .with_route_hints(vec![route_hint]).unwrap()
7909 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7912 let netgraph = network_graph.read_only();
7913 let route_params = RouteParameters::from_payment_params_and_value(
7914 payment_params, amt_msat);
7915 if let Err(LightningError { err, .. }) = get_route(
7916 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7917 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7919 assert_eq!(err, "Failed to find a path to the given destination");
7924 fn previously_used_liquidity_violates_max_htlc() {
7925 do_previously_used_liquidity_violates_max_htlc(true);
7926 do_previously_used_liquidity_violates_max_htlc(false);
7929 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
7930 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
7931 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
7932 // candidate. In this case, the candidate does not have enough due to a previous path taking up
7933 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
7934 // asserting that the used liquidity for a hop was less than its available liquidity limit.
7935 let secp_ctx = Secp256k1::new();
7936 let logger = Arc::new(ln_test_utils::TestLogger::new());
7937 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7938 let scorer = ln_test_utils::TestScorer::new();
7939 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7940 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7941 let config = UserConfig::default();
7943 // Values are taken from the fuzz input that uncovered this panic.
7944 let amt_msat = 52_4288;
7945 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7946 let first_hops = vec![get_channel_details(
7947 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
7948 ), get_channel_details(
7949 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
7952 let base_fees = [0, 425_9840, 0, 0];
7953 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
7954 let payment_params = if blinded_payee {
7955 let blinded_path = BlindedPath {
7956 introduction_node_id: nodes[0],
7957 blinding_point: ln_test_utils::pubkey(42),
7959 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7960 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7963 let mut blinded_hints = Vec::new();
7964 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
7965 blinded_hints.push((BlindedPayInfo {
7966 fee_base_msat: *base_fee,
7967 fee_proportional_millionths: 0,
7968 htlc_minimum_msat: *htlc_min,
7969 htlc_maximum_msat: htlc_min * 100,
7970 cltv_expiry_delta: 10,
7971 features: BlindedHopFeatures::empty(),
7972 }, blinded_path.clone()));
7974 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7975 PaymentParameters::blinded(blinded_hints.clone())
7976 .with_bolt12_features(bolt12_features.clone()).unwrap()
7978 let mut route_hints = Vec::new();
7979 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
7980 route_hints.push(RouteHint(vec![RouteHintHop {
7981 src_node_id: nodes[0],
7982 short_channel_id: 42 + idx as u64,
7984 base_msat: *base_fee,
7985 proportional_millionths: 0,
7987 cltv_expiry_delta: 10,
7988 htlc_minimum_msat: Some(*htlc_min),
7989 htlc_maximum_msat: Some(htlc_min * 100),
7992 PaymentParameters::from_node_id(nodes[1], 42)
7993 .with_route_hints(route_hints).unwrap()
7994 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7997 let netgraph = network_graph.read_only();
7998 let route_params = RouteParameters::from_payment_params_and_value(
7999 payment_params, amt_msat);
8001 let route = get_route(
8002 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8003 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8005 assert_eq!(route.paths.len(), 1);
8006 assert_eq!(route.get_total_amount(), amt_msat);
8010 fn candidate_path_min() {
8011 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
8012 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
8013 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
8014 // would add a connecting first_hop node that did not have enough contribution amount, leading
8015 // to a debug panic upon invalid path construction.
8016 let secp_ctx = Secp256k1::new();
8017 let logger = Arc::new(ln_test_utils::TestLogger::new());
8018 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8019 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
8020 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8021 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8022 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8023 let config = UserConfig::default();
8025 // Values are taken from the fuzz input that uncovered this panic.
8026 let amt_msat = 7_4009_8048;
8027 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
8028 let first_hops = vec![get_channel_details(
8029 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
8032 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
8033 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8034 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8035 short_channel_id: 6,
8038 cltv_expiry_delta: (6 << 4) | 0,
8039 htlc_minimum_msat: 0,
8040 htlc_maximum_msat: MAX_VALUE_MSAT,
8042 fee_proportional_millionths: 0,
8043 excess_data: Vec::new()
8045 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
8047 let htlc_min = 2_5165_8240;
8048 let blinded_hints = vec![
8050 fee_base_msat: 1_6778_3453,
8051 fee_proportional_millionths: 0,
8052 htlc_minimum_msat: htlc_min,
8053 htlc_maximum_msat: htlc_min * 100,
8054 cltv_expiry_delta: 10,
8055 features: BlindedHopFeatures::empty(),
8057 introduction_node_id: nodes[0],
8058 blinding_point: ln_test_utils::pubkey(42),
8060 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8061 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8065 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8066 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8067 .with_bolt12_features(bolt12_features.clone()).unwrap();
8068 let route_params = RouteParameters::from_payment_params_and_value(
8069 payment_params, amt_msat);
8070 let netgraph = network_graph.read_only();
8072 if let Err(LightningError { err, .. }) = get_route(
8073 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8074 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8077 assert_eq!(err, "Failed to find a path to the given destination");
8082 fn path_contribution_includes_min_htlc_overpay() {
8083 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
8084 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
8085 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
8086 // selection, both tested here.
8087 let secp_ctx = Secp256k1::new();
8088 let logger = Arc::new(ln_test_utils::TestLogger::new());
8089 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8090 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8091 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8092 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8093 let config = UserConfig::default();
8095 // Values are taken from the fuzz input that uncovered this panic.
8096 let amt_msat = 562_0000;
8097 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8098 let first_hops = vec![
8099 get_channel_details(
8100 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
8104 let htlc_mins = [49_0000, 1125_0000];
8105 let payment_params = {
8106 let blinded_path = BlindedPath {
8107 introduction_node_id: nodes[0],
8108 blinding_point: ln_test_utils::pubkey(42),
8110 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8111 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8114 let mut blinded_hints = Vec::new();
8115 for htlc_min in htlc_mins.iter() {
8116 blinded_hints.push((BlindedPayInfo {
8118 fee_proportional_millionths: 0,
8119 htlc_minimum_msat: *htlc_min,
8120 htlc_maximum_msat: *htlc_min * 100,
8121 cltv_expiry_delta: 10,
8122 features: BlindedHopFeatures::empty(),
8123 }, blinded_path.clone()));
8125 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8126 PaymentParameters::blinded(blinded_hints.clone())
8127 .with_bolt12_features(bolt12_features.clone()).unwrap()
8130 let netgraph = network_graph.read_only();
8131 let route_params = RouteParameters::from_payment_params_and_value(
8132 payment_params, amt_msat);
8133 let route = get_route(
8134 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8135 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8138 assert_eq!(route.paths.len(), 1);
8139 assert_eq!(route.get_total_amount(), amt_msat);
8143 fn first_hop_preferred_over_hint() {
8144 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
8145 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
8146 let secp_ctx = Secp256k1::new();
8147 let logger = Arc::new(ln_test_utils::TestLogger::new());
8148 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8149 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
8150 let scorer = ln_test_utils::TestScorer::new();
8151 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8152 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8153 let config = UserConfig::default();
8155 let amt_msat = 1_000_000;
8156 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
8158 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
8159 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
8160 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8161 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8162 short_channel_id: 1,
8165 cltv_expiry_delta: 42,
8166 htlc_minimum_msat: 1_000,
8167 htlc_maximum_msat: 10_000_000,
8169 fee_proportional_millionths: 0,
8170 excess_data: Vec::new()
8172 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8173 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8174 short_channel_id: 1,
8177 cltv_expiry_delta: 42,
8178 htlc_minimum_msat: 1_000,
8179 htlc_maximum_msat: 10_000_000,
8181 fee_proportional_millionths: 0,
8182 excess_data: Vec::new()
8185 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
8186 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
8187 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8188 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8189 short_channel_id: 2,
8192 cltv_expiry_delta: 42,
8193 htlc_minimum_msat: 1_000,
8194 htlc_maximum_msat: 10_000_000,
8196 fee_proportional_millionths: 0,
8197 excess_data: Vec::new()
8199 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8200 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8201 short_channel_id: 2,
8204 cltv_expiry_delta: 42,
8205 htlc_minimum_msat: 1_000,
8206 htlc_maximum_msat: 10_000_000,
8208 fee_proportional_millionths: 0,
8209 excess_data: Vec::new()
8212 let dest_node_id = nodes[2];
8214 let route_hint = RouteHint(vec![RouteHintHop {
8215 src_node_id: our_node_id,
8216 short_channel_id: 44,
8219 proportional_millionths: 0,
8221 cltv_expiry_delta: 10,
8222 htlc_minimum_msat: None,
8223 htlc_maximum_msat: Some(5_000_000),
8226 src_node_id: nodes[0],
8227 short_channel_id: 45,
8230 proportional_millionths: 0,
8232 cltv_expiry_delta: 10,
8233 htlc_minimum_msat: None,
8234 htlc_maximum_msat: None,
8237 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8238 .with_route_hints(vec![route_hint]).unwrap()
8239 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8240 let route_params = RouteParameters::from_payment_params_and_value(
8241 payment_params, amt_msat);
8243 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8245 let first_hop = get_channel_details(Some(1), nodes[0],
8246 channelmanager::provided_init_features(&config), 999_999);
8247 let first_hops = vec![first_hop];
8249 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8250 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8251 &Default::default(), &random_seed_bytes).unwrap();
8252 assert_eq!(route.paths.len(), 1);
8253 assert_eq!(route.get_total_amount(), amt_msat);
8254 assert_eq!(route.paths[0].hops.len(), 2);
8255 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8256 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8257 assert_eq!(route.get_total_fees(), 123);
8259 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8260 // for a first hop channel.
8261 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8262 first_hop.outbound_scid_alias = Some(44);
8263 let first_hops = vec![first_hop];
8265 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8266 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8267 &Default::default(), &random_seed_bytes);
8268 assert!(route_res.is_err());
8270 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8271 // use the cheaper second hop of the route hint.
8272 let mut first_hop = get_channel_details(Some(1), nodes[0],
8273 channelmanager::provided_init_features(&config), 10_000_000);
8274 first_hop.outbound_scid_alias = Some(44);
8275 let first_hops = vec![first_hop];
8277 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8278 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8279 &Default::default(), &random_seed_bytes).unwrap();
8280 assert_eq!(route.paths.len(), 1);
8281 assert_eq!(route.get_total_amount(), amt_msat);
8282 assert_eq!(route.paths[0].hops.len(), 2);
8283 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8284 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8285 assert_eq!(route.get_total_fees(), 123);
8289 fn allow_us_being_first_hint() {
8290 // Check that we consider a route hint even if we are the src of the first hop.
8291 let secp_ctx = Secp256k1::new();
8292 let logger = Arc::new(ln_test_utils::TestLogger::new());
8293 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8294 let scorer = ln_test_utils::TestScorer::new();
8295 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8296 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8297 let config = UserConfig::default();
8299 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8301 let amt_msat = 1_000_000;
8302 let dest_node_id = nodes[1];
8304 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8305 let first_hops = vec![first_hop];
8307 let route_hint = RouteHint(vec![RouteHintHop {
8308 src_node_id: our_node_id,
8309 short_channel_id: 44,
8312 proportional_millionths: 0,
8314 cltv_expiry_delta: 10,
8315 htlc_minimum_msat: None,
8316 htlc_maximum_msat: None,
8319 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8320 .with_route_hints(vec![route_hint]).unwrap()
8321 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8323 let route_params = RouteParameters::from_payment_params_and_value(
8324 payment_params, amt_msat);
8327 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8328 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8329 &Default::default(), &random_seed_bytes).unwrap();
8331 assert_eq!(route.paths.len(), 1);
8332 assert_eq!(route.get_total_amount(), amt_msat);
8333 assert_eq!(route.get_total_fees(), 0);
8334 assert_eq!(route.paths[0].hops.len(), 1);
8336 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8340 #[cfg(all(any(test, ldk_bench), feature = "std"))]
8341 pub(crate) mod bench_utils {
8344 use std::time::Duration;
8346 use bitcoin::hashes::Hash;
8347 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
8349 use crate::chain::transaction::OutPoint;
8350 use crate::routing::scoring::ScoreUpdate;
8351 use crate::sign::{EntropySource, KeysManager};
8352 use crate::ln::ChannelId;
8353 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
8354 use crate::ln::features::Bolt11InvoiceFeatures;
8355 use crate::routing::gossip::NetworkGraph;
8356 use crate::util::config::UserConfig;
8357 use crate::util::ser::ReadableArgs;
8358 use crate::util::test_utils::TestLogger;
8360 /// Tries to open a network graph file, or panics with a URL to fetch it.
8361 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
8362 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
8363 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
8364 .or_else(|_| { // Fall back to guessing based on the binary location
8365 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8366 let mut path = std::env::current_exe().unwrap();
8367 path.pop(); // lightning-...
8369 path.pop(); // debug
8370 path.pop(); // target
8371 path.push("lightning");
8372 path.push("net_graph-2023-01-18.bin");
8375 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8376 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8377 let mut path = std::env::current_exe().unwrap();
8378 path.pop(); // bench...
8380 path.pop(); // debug
8381 path.pop(); // target
8382 path.pop(); // bench
8383 path.push("lightning");
8384 path.push("net_graph-2023-01-18.bin");
8387 .map_err(|_| "Please fetch https://bitcoin.ninja/ldk-net_graph-v0.0.113-2023-01-18.bin and place it at lightning/net_graph-2023-01-18.bin");
8388 #[cfg(require_route_graph_test)]
8389 return Ok(res.unwrap());
8390 #[cfg(not(require_route_graph_test))]
8394 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
8395 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
8398 pub(crate) fn payer_pubkey() -> PublicKey {
8399 let secp_ctx = Secp256k1::new();
8400 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8404 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8406 channel_id: ChannelId::new_zero(),
8407 counterparty: ChannelCounterparty {
8408 features: channelmanager::provided_init_features(&UserConfig::default()),
8410 unspendable_punishment_reserve: 0,
8411 forwarding_info: None,
8412 outbound_htlc_minimum_msat: None,
8413 outbound_htlc_maximum_msat: None,
8415 funding_txo: Some(OutPoint {
8416 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8419 short_channel_id: Some(1),
8420 inbound_scid_alias: None,
8421 outbound_scid_alias: None,
8422 channel_value_satoshis: 10_000_000_000,
8424 balance_msat: 10_000_000_000,
8425 outbound_capacity_msat: 10_000_000_000,
8426 next_outbound_htlc_minimum_msat: 0,
8427 next_outbound_htlc_limit_msat: 10_000_000_000,
8428 inbound_capacity_msat: 0,
8429 unspendable_punishment_reserve: None,
8430 confirmations_required: None,
8431 confirmations: None,
8432 force_close_spend_delay: None,
8434 is_channel_ready: true,
8437 inbound_htlc_minimum_msat: None,
8438 inbound_htlc_maximum_msat: None,
8440 feerate_sat_per_1000_weight: None,
8441 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
8442 pending_inbound_htlcs: Vec::new(),
8443 pending_outbound_htlcs: Vec::new(),
8447 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8448 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8449 starting_amount: u64, route_count: usize,
8450 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8451 let payer = payer_pubkey();
8452 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8453 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8455 let nodes = graph.read_only().nodes().clone();
8456 let mut route_endpoints = Vec::new();
8457 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
8458 // with some routes we picked being un-routable.
8459 for _ in 0..route_count * 3 / 2 {
8461 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8462 let src = PublicKey::from_slice(nodes.unordered_keys()
8463 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8464 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8465 let dst = PublicKey::from_slice(nodes.unordered_keys()
8466 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8467 let params = PaymentParameters::from_node_id(dst, 42)
8468 .with_bolt11_features(features.clone()).unwrap();
8469 let first_hop = first_hop(src);
8470 let amt_msat = starting_amount + seed % 1_000_000;
8471 let route_params = RouteParameters::from_payment_params_and_value(
8472 params.clone(), amt_msat);
8474 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8475 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8477 // ...and seed the scorer with success and failure data...
8478 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8479 let mut score_amt = seed % 1_000_000_000;
8481 // Generate fail/success paths for a wider range of potential amounts with
8482 // MPP enabled to give us a chance to apply penalties for more potential
8484 let mpp_features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
8485 let params = PaymentParameters::from_node_id(dst, 42)
8486 .with_bolt11_features(mpp_features).unwrap();
8487 let route_params = RouteParameters::from_payment_params_and_value(
8488 params.clone(), score_amt);
8489 let route_res = get_route(&payer, &route_params, &graph.read_only(),
8490 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
8491 &random_seed_bytes);
8492 if let Ok(route) = route_res {
8493 for path in route.paths {
8494 if seed & 0x80 == 0 {
8495 scorer.payment_path_successful(&path, Duration::ZERO);
8497 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
8498 scorer.payment_path_failed(&path, short_channel_id, Duration::ZERO);
8500 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8504 // If we couldn't find a path with a higher amount, reduce and try again.
8508 route_endpoints.push((first_hop, params, amt_msat));
8514 // Because we've changed channel scores, it's possible we'll take different routes to the
8515 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
8516 // requires a too-high CLTV delta.
8517 route_endpoints.retain(|(first_hop, params, amt_msat)| {
8518 let route_params = RouteParameters::from_payment_params_and_value(
8519 params.clone(), *amt_msat);
8520 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8521 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
8523 route_endpoints.truncate(route_count);
8524 assert_eq!(route_endpoints.len(), route_count);
8532 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8533 use crate::sign::{EntropySource, KeysManager};
8534 use crate::ln::channelmanager;
8535 use crate::ln::features::Bolt11InvoiceFeatures;
8536 use crate::routing::gossip::NetworkGraph;
8537 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
8538 use crate::util::config::UserConfig;
8539 use crate::util::logger::{Logger, Record};
8540 use crate::util::test_utils::TestLogger;
8542 use criterion::Criterion;
8544 struct DummyLogger {}
8545 impl Logger for DummyLogger {
8546 fn log(&self, _record: Record) {}
8549 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8550 let logger = TestLogger::new();
8551 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8552 let scorer = FixedPenaltyScorer::with_penalty(0);
8553 generate_routes(bench, &network_graph, scorer, &Default::default(),
8554 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8557 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8558 let logger = TestLogger::new();
8559 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8560 let scorer = FixedPenaltyScorer::with_penalty(0);
8561 generate_routes(bench, &network_graph, scorer, &Default::default(),
8562 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8563 "generate_mpp_routes_with_zero_penalty_scorer");
8566 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8567 let logger = TestLogger::new();
8568 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8569 let params = ProbabilisticScoringFeeParameters::default();
8570 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8571 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8572 "generate_routes_with_probabilistic_scorer");
8575 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8576 let logger = TestLogger::new();
8577 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8578 let params = ProbabilisticScoringFeeParameters::default();
8579 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8580 generate_routes(bench, &network_graph, scorer, ¶ms,
8581 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8582 "generate_mpp_routes_with_probabilistic_scorer");
8585 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8586 let logger = TestLogger::new();
8587 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8588 let params = ProbabilisticScoringFeeParameters::default();
8589 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8590 generate_routes(bench, &network_graph, scorer, ¶ms,
8591 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8592 "generate_large_mpp_routes_with_probabilistic_scorer");
8595 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8596 let logger = TestLogger::new();
8597 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8598 let mut params = ProbabilisticScoringFeeParameters::default();
8599 params.linear_success_probability = false;
8600 let scorer = ProbabilisticScorer::new(
8601 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8602 generate_routes(bench, &network_graph, scorer, ¶ms,
8603 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8604 "generate_routes_with_nonlinear_probabilistic_scorer");
8607 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8608 let logger = TestLogger::new();
8609 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8610 let mut params = ProbabilisticScoringFeeParameters::default();
8611 params.linear_success_probability = false;
8612 let scorer = ProbabilisticScorer::new(
8613 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8614 generate_routes(bench, &network_graph, scorer, ¶ms,
8615 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8616 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8619 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8620 let logger = TestLogger::new();
8621 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8622 let mut params = ProbabilisticScoringFeeParameters::default();
8623 params.linear_success_probability = false;
8624 let scorer = ProbabilisticScorer::new(
8625 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8626 generate_routes(bench, &network_graph, scorer, ¶ms,
8627 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8628 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8631 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8632 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8633 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8634 bench_name: &'static str,
8636 let payer = bench_utils::payer_pubkey();
8637 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8638 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8640 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8641 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8643 // ...then benchmark finding paths between the nodes we learned.
8645 bench.bench_function(bench_name, |b| b.iter(|| {
8646 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8647 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8648 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8649 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());