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;
13 use bitcoin::hashes::Hash;
14 use bitcoin::hashes::sha256::Hash as Sha256;
16 use crate::blinded_path::{BlindedHop, BlindedPath};
17 use crate::ln::PaymentHash;
18 use crate::ln::channelmanager::{ChannelDetails, PaymentId};
19 use crate::ln::features::{Bolt12InvoiceFeatures, ChannelFeatures, InvoiceFeatures, NodeFeatures};
20 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
21 use crate::offers::invoice::{BlindedPayInfo, Invoice as Bolt12Invoice};
22 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
23 use crate::routing::scoring::{ChannelUsage, LockableScore, Score};
24 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
25 use crate::util::logger::{Level, Logger};
26 use crate::util::chacha20::ChaCha20;
29 use crate::prelude::*;
30 use crate::sync::{Mutex};
31 use alloc::collections::BinaryHeap;
33 use core::ops::{Deref, DerefMut};
35 /// A [`Router`] implemented using [`find_route`].
36 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: Score<ScoreParams = SP>> where
38 S::Target: for <'a> LockableScore<'a, Score = Sc>,
42 random_seed_bytes: Mutex<[u8; 32]>,
47 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: Score<ScoreParams = SP>> DefaultRouter<G, L, S, SP, Sc> where
49 S::Target: for <'a> LockableScore<'a, Score = Sc>,
51 /// Creates a new router.
52 pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32], scorer: S, score_params: SP) -> Self {
53 let random_seed_bytes = Mutex::new(random_seed_bytes);
54 Self { network_graph, logger, random_seed_bytes, scorer, score_params }
58 impl< G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: Score<ScoreParams = SP>> Router for DefaultRouter<G, L, S, SP, Sc> where
60 S::Target: for <'a> LockableScore<'a, Score = Sc>,
65 params: &RouteParameters,
66 first_hops: Option<&[&ChannelDetails]>,
67 inflight_htlcs: &InFlightHtlcs
68 ) -> Result<Route, LightningError> {
69 let random_seed_bytes = {
70 let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
71 *locked_random_seed_bytes = Sha256::hash(&*locked_random_seed_bytes).into_inner();
72 *locked_random_seed_bytes
75 payer, params, &self.network_graph, first_hops, &*self.logger,
76 &ScorerAccountingForInFlightHtlcs::new(self.scorer.lock().deref_mut(), inflight_htlcs),
83 /// A trait defining behavior for routing a payment.
85 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
87 &self, payer: &PublicKey, route_params: &RouteParameters,
88 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs
89 ) -> Result<Route, LightningError>;
90 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes
91 /// `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment.
92 fn find_route_with_id(
93 &self, payer: &PublicKey, route_params: &RouteParameters,
94 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs,
95 _payment_hash: PaymentHash, _payment_id: PaymentId
96 ) -> Result<Route, LightningError> {
97 self.find_route(payer, route_params, first_hops, inflight_htlcs)
101 /// [`Score`] implementation that factors in in-flight HTLC liquidity.
103 /// Useful for custom [`Router`] implementations to wrap their [`Score`] on-the-fly when calling
106 /// [`Score`]: crate::routing::scoring::Score
107 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Score<ScoreParams = SP>, SP: Sized> {
109 // Maps a channel's short channel id and its direction to the liquidity used up.
110 inflight_htlcs: &'a InFlightHtlcs,
113 impl<'a, S: Score<ScoreParams = SP>, SP: Sized> ScorerAccountingForInFlightHtlcs<'a, S, SP> {
114 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
115 pub fn new(scorer: &'a mut S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
116 ScorerAccountingForInFlightHtlcs {
124 impl<'a, S: Score<ScoreParams = SP>, SP: Sized> Writeable for ScorerAccountingForInFlightHtlcs<'a, S, SP> {
125 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.scorer.write(writer) }
128 impl<'a, S: Score<ScoreParams = SP>, SP: Sized> Score for ScorerAccountingForInFlightHtlcs<'a, S, SP> {
129 type ScoreParams = S::ScoreParams;
130 fn channel_penalty_msat(&self, short_channel_id: u64, source: &NodeId, target: &NodeId, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
131 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
132 source, target, short_channel_id
134 let usage = ChannelUsage {
135 inflight_htlc_msat: usage.inflight_htlc_msat + used_liquidity,
139 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
141 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
145 fn payment_path_failed(&mut self, path: &Path, short_channel_id: u64) {
146 self.scorer.payment_path_failed(path, short_channel_id)
149 fn payment_path_successful(&mut self, path: &Path) {
150 self.scorer.payment_path_successful(path)
153 fn probe_failed(&mut self, path: &Path, short_channel_id: u64) {
154 self.scorer.probe_failed(path, short_channel_id)
157 fn probe_successful(&mut self, path: &Path) {
158 self.scorer.probe_successful(path)
162 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
163 /// in-use channel liquidity.
165 pub struct InFlightHtlcs(
166 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
167 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
168 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
170 HashMap<(u64, bool), u64>
174 /// Constructs an empty `InFlightHtlcs`.
175 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
177 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
178 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
179 if path.hops.is_empty() { return };
181 let mut cumulative_msat = 0;
182 if let Some(tail) = &path.blinded_tail {
183 cumulative_msat += tail.final_value_msat;
186 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
187 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
188 // the router excludes the payer node. In the following lines, the payer's information is
189 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
190 // in our sliding window of two.
191 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
192 .map(|hop| hop.pubkey)
193 .chain(core::iter::once(payer_node_id));
195 // Taking the reversed vector from above, we zip it with just the reversed hops list to
196 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
197 // the total amount sent.
198 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
199 cumulative_msat += next_hop.fee_msat;
201 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
202 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
203 .or_insert(cumulative_msat);
207 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
209 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
210 self.0.get(&(channel_scid, source < target)).map(|v| *v)
214 impl Writeable for InFlightHtlcs {
215 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
218 impl Readable for InFlightHtlcs {
219 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
220 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
221 Ok(Self(infight_map))
225 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
226 /// that leads to it.
227 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
228 pub struct RouteHop {
229 /// The node_id of the node at this hop.
230 pub pubkey: PublicKey,
231 /// The node_announcement features of the node at this hop. For the last hop, these may be
232 /// amended to match the features present in the invoice this node generated.
233 pub node_features: NodeFeatures,
234 /// The channel that should be used from the previous hop to reach this node.
235 pub short_channel_id: u64,
236 /// The channel_announcement features of the channel that should be used from the previous hop
237 /// to reach this node.
238 pub channel_features: ChannelFeatures,
239 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
240 /// If this is the last hop in [`Path::hops`]:
241 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
242 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
244 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
246 /// The CLTV delta added for this hop.
247 /// If this is the last hop in [`Path::hops`]:
248 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
249 /// * otherwise, this is the CLTV delta expected at the destination
251 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
252 pub cltv_expiry_delta: u32,
255 impl_writeable_tlv_based!(RouteHop, {
256 (0, pubkey, required),
257 (2, node_features, required),
258 (4, short_channel_id, required),
259 (6, channel_features, required),
260 (8, fee_msat, required),
261 (10, cltv_expiry_delta, required),
264 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
265 /// their BOLT12 [`Invoice`].
267 /// [`Invoice`]: crate::offers::invoice::Invoice
268 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
269 pub struct BlindedTail {
270 /// The hops of the [`BlindedPath`] provided by the recipient.
272 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
273 pub hops: Vec<BlindedHop>,
274 /// The blinding point of the [`BlindedPath`] provided by the recipient.
276 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
277 pub blinding_point: PublicKey,
278 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
279 /// inferring the destination. May be 0.
280 pub excess_final_cltv_expiry_delta: u32,
281 /// The total amount paid on this [`Path`], excluding the fees.
282 pub final_value_msat: u64,
285 impl_writeable_tlv_based!(BlindedTail, {
286 (0, hops, required_vec),
287 (2, blinding_point, required),
288 (4, excess_final_cltv_expiry_delta, required),
289 (6, final_value_msat, required),
292 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
293 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
294 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
296 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
297 pub hops: Vec<RouteHop>,
298 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
299 pub blinded_tail: Option<BlindedTail>,
303 /// Gets the fees for a given path, excluding any excess paid to the recipient.
304 pub fn fee_msat(&self) -> u64 {
305 match &self.blinded_tail {
306 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
308 // Do not count last hop of each path since that's the full value of the payment
309 self.hops.split_last().map_or(0,
310 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
315 /// Gets the total amount paid on this [`Path`], excluding the fees.
316 pub fn final_value_msat(&self) -> u64 {
317 match &self.blinded_tail {
318 Some(blinded_tail) => blinded_tail.final_value_msat,
319 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
323 /// Gets the final hop's CLTV expiry delta.
324 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
325 match &self.blinded_tail {
327 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
332 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
333 /// it can take multiple paths. Each path is composed of one or more hops through the network.
334 #[derive(Clone, Hash, PartialEq, Eq)]
336 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
337 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
339 pub paths: Vec<Path>,
340 /// The `payment_params` parameter passed to [`find_route`].
341 /// This is used by `ChannelManager` to track information which may be required for retries,
342 /// provided back to you via [`Event::PaymentPathFailed`].
344 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
345 pub payment_params: Option<PaymentParameters>,
349 /// Returns the total amount of fees paid on this [`Route`].
351 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
352 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
353 pub fn get_total_fees(&self) -> u64 {
354 self.paths.iter().map(|path| path.fee_msat()).sum()
357 /// Returns the total amount paid on this [`Route`], excluding the fees. Might be more than
358 /// requested if we had to reach htlc_minimum_msat.
359 pub fn get_total_amount(&self) -> u64 {
360 self.paths.iter().map(|path| path.final_value_msat()).sum()
364 const SERIALIZATION_VERSION: u8 = 1;
365 const MIN_SERIALIZATION_VERSION: u8 = 1;
367 impl Writeable for Route {
368 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
369 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
370 (self.paths.len() as u64).write(writer)?;
371 let mut blinded_tails = Vec::new();
372 for path in self.paths.iter() {
373 (path.hops.len() as u8).write(writer)?;
374 for (idx, hop) in path.hops.iter().enumerate() {
376 if let Some(blinded_tail) = &path.blinded_tail {
377 if blinded_tails.is_empty() {
378 blinded_tails = Vec::with_capacity(path.hops.len());
380 blinded_tails.push(None);
383 blinded_tails.push(Some(blinded_tail));
384 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
387 write_tlv_fields!(writer, {
388 (1, self.payment_params, option),
389 (2, blinded_tails, optional_vec),
395 impl Readable for Route {
396 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
397 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
398 let path_count: u64 = Readable::read(reader)?;
399 if path_count == 0 { return Err(DecodeError::InvalidValue); }
400 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
401 let mut min_final_cltv_expiry_delta = u32::max_value();
402 for _ in 0..path_count {
403 let hop_count: u8 = Readable::read(reader)?;
404 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
405 for _ in 0..hop_count {
406 hops.push(Readable::read(reader)?);
408 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
409 min_final_cltv_expiry_delta =
410 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
411 paths.push(Path { hops, blinded_tail: None });
413 _init_and_read_tlv_fields!(reader, {
414 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
415 (2, blinded_tails, optional_vec),
417 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
418 if blinded_tails.len() != 0 {
419 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
420 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
421 path.blinded_tail = blinded_tail_opt;
424 Ok(Route { paths, payment_params })
428 /// Parameters needed to find a [`Route`].
430 /// Passed to [`find_route`] and [`build_route_from_hops`], but also provided in
431 /// [`Event::PaymentPathFailed`].
433 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
434 #[derive(Clone, Debug, PartialEq, Eq)]
435 pub struct RouteParameters {
436 /// The parameters of the failed payment path.
437 pub payment_params: PaymentParameters,
439 /// The amount in msats sent on the failed payment path.
440 pub final_value_msat: u64,
443 impl Writeable for RouteParameters {
444 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
445 write_tlv_fields!(writer, {
446 (0, self.payment_params, required),
447 (2, self.final_value_msat, required),
448 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
449 // `RouteParameters` directly. For compatibility, we write it here.
450 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
456 impl Readable for RouteParameters {
457 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
458 _init_and_read_tlv_fields!(reader, {
459 (0, payment_params, (required: ReadableArgs, 0)),
460 (2, final_value_msat, required),
461 (4, final_cltv_delta, option),
463 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
464 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
465 if final_cltv_expiry_delta == &0 {
466 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
471 final_value_msat: final_value_msat.0.unwrap(),
476 /// Maximum total CTLV difference we allow for a full payment path.
477 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
479 /// Maximum number of paths we allow an (MPP) payment to have.
480 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
481 // limits, but for now more than 10 paths likely carries too much one-path failure.
482 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
484 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
486 // The median hop CLTV expiry delta currently seen in the network.
487 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
489 // During routing, we only consider paths shorter than our maximum length estimate.
490 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
491 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
492 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
494 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
495 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
496 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
497 // (payment_secret and total_msat) = 93 bytes for the final hop.
498 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
499 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
500 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
502 /// Information used to route a payment.
503 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
504 pub struct PaymentParameters {
505 /// Information about the payee, such as their features and route hints for their channels.
508 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
509 pub expiry_time: Option<u64>,
511 /// The maximum total CLTV delta we accept for the route.
512 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
513 pub max_total_cltv_expiry_delta: u32,
515 /// The maximum number of paths that may be used by (MPP) payments.
516 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
517 pub max_path_count: u8,
519 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
520 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
521 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
522 /// increasing failure probability for those paths.
524 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
525 /// restriction have been found. While paths which meet this criteria will be searched for, it
526 /// is ultimately up to the scorer to select them over other paths.
528 /// A value of 0 will allow payments up to and including a channel's total announced usable
529 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
532 pub max_channel_saturation_power_of_half: u8,
534 /// A list of SCIDs which this payment was previously attempted over and which caused the
535 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
537 pub previously_failed_channels: Vec<u64>,
540 impl Writeable for PaymentParameters {
541 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
542 let mut clear_hints = &vec![];
543 let mut blinded_hints = &vec![];
545 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
546 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
548 write_tlv_fields!(writer, {
549 (0, self.payee.node_id(), option),
550 (1, self.max_total_cltv_expiry_delta, required),
551 (2, self.payee.features(), option),
552 (3, self.max_path_count, required),
553 (4, *clear_hints, required_vec),
554 (5, self.max_channel_saturation_power_of_half, required),
555 (6, self.expiry_time, option),
556 (7, self.previously_failed_channels, required_vec),
557 (8, *blinded_hints, optional_vec),
558 (9, self.payee.final_cltv_expiry_delta(), option),
564 impl ReadableArgs<u32> for PaymentParameters {
565 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
566 _init_and_read_tlv_fields!(reader, {
567 (0, payee_pubkey, option),
568 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
569 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
570 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
571 (4, clear_route_hints, required_vec),
572 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
573 (6, expiry_time, option),
574 (7, previously_failed_channels, optional_vec),
575 (8, blinded_route_hints, optional_vec),
576 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
578 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
579 let payee = if blinded_route_hints.len() != 0 {
580 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
582 route_hints: blinded_route_hints,
583 features: features.and_then(|f: Features| f.bolt12()),
587 route_hints: clear_route_hints,
588 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
589 features: features.and_then(|f| f.bolt11()),
590 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
594 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
595 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
597 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
599 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
605 impl PaymentParameters {
606 /// Creates a payee with the node id of the given `pubkey`.
608 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
610 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
612 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
614 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
615 max_path_count: DEFAULT_MAX_PATH_COUNT,
616 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
617 previously_failed_channels: Vec::new(),
621 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
623 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
626 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
627 /// whether your router will be allowed to find a multi-part route for this payment. If you
628 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
629 /// [`RecipientOnionFields::secret_only`].
631 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
632 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
633 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
634 .with_bolt11_features(InvoiceFeatures::for_keysend(allow_mpp))
635 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
638 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
639 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
640 /// [`PaymentParameters::expiry_time`].
641 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
642 Self::blinded(invoice.payment_paths().to_vec())
643 .with_bolt12_features(invoice.features().clone()).unwrap()
644 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
647 fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
649 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
651 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
652 max_path_count: DEFAULT_MAX_PATH_COUNT,
653 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
654 previously_failed_channels: Vec::new(),
658 /// Includes the payee's features. Errors if the parameters were not initialized with
659 /// [`PaymentParameters::from_bolt12_invoice`].
661 /// This is not exported to bindings users since bindings don't support move semantics
662 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
664 Payee::Clear { .. } => Err(()),
665 Payee::Blinded { route_hints, .. } =>
666 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
670 /// Includes the payee's features. Errors if the parameters were initialized with
671 /// [`PaymentParameters::from_bolt12_invoice`].
673 /// This is not exported to bindings users since bindings don't support move semantics
674 pub fn with_bolt11_features(self, features: InvoiceFeatures) -> Result<Self, ()> {
676 Payee::Blinded { .. } => Err(()),
677 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
679 payee: Payee::Clear {
680 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
686 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
687 /// [`PaymentParameters::from_bolt12_invoice`].
689 /// This is not exported to bindings users since bindings don't support move semantics
690 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
692 Payee::Blinded { .. } => Err(()),
693 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
695 payee: Payee::Clear {
696 route_hints, node_id, features, final_cltv_expiry_delta,
702 /// Includes a payment expiration in seconds relative to the UNIX epoch.
704 /// This is not exported to bindings users since bindings don't support move semantics
705 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
706 Self { expiry_time: Some(expiry_time), ..self }
709 /// Includes a limit for the total CLTV expiry delta which is considered during routing
711 /// This is not exported to bindings users since bindings don't support move semantics
712 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
713 Self { max_total_cltv_expiry_delta, ..self }
716 /// Includes a limit for the maximum number of payment paths that may be used.
718 /// This is not exported to bindings users since bindings don't support move semantics
719 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
720 Self { max_path_count, ..self }
723 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
724 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
726 /// This is not exported to bindings users since bindings don't support move semantics
727 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
728 Self { max_channel_saturation_power_of_half, ..self }
732 /// The recipient of a payment, differing based on whether they've hidden their identity with route
734 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
736 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
737 /// will be included in the final [`Route`].
739 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
741 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
742 /// Features supported by the payee.
744 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
746 features: Option<Bolt12InvoiceFeatures>,
748 /// The recipient included these route hints in their BOLT11 invoice.
750 /// The node id of the payee.
752 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
753 route_hints: Vec<RouteHint>,
754 /// Features supported by the payee.
756 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
757 /// does not contain any features.
759 /// [`for_keysend`]: PaymentParameters::for_keysend
760 features: Option<InvoiceFeatures>,
761 /// The minimum CLTV delta at the end of the route. This value must not be zero.
762 final_cltv_expiry_delta: u32,
767 fn node_id(&self) -> Option<PublicKey> {
769 Self::Clear { node_id, .. } => Some(*node_id),
773 fn node_features(&self) -> Option<NodeFeatures> {
775 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
776 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
779 fn supports_basic_mpp(&self) -> bool {
781 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
782 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
785 fn features(&self) -> Option<FeaturesRef> {
787 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
788 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
791 fn final_cltv_expiry_delta(&self) -> Option<u32> {
793 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
797 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
799 Self::Blinded { route_hints, .. } => &route_hints[..],
800 Self::Clear { .. } => &[]
804 fn unblinded_route_hints(&self) -> &[RouteHint] {
806 Self::Blinded { .. } => &[],
807 Self::Clear { route_hints, .. } => &route_hints[..]
812 enum FeaturesRef<'a> {
813 Bolt11(&'a InvoiceFeatures),
814 Bolt12(&'a Bolt12InvoiceFeatures),
817 Bolt11(InvoiceFeatures),
818 Bolt12(Bolt12InvoiceFeatures),
822 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
824 Self::Bolt12(f) => Some(f),
828 fn bolt11(self) -> Option<InvoiceFeatures> {
830 Self::Bolt11(f) => Some(f),
836 impl<'a> Writeable for FeaturesRef<'a> {
837 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
839 Self::Bolt11(f) => Ok(f.write(w)?),
840 Self::Bolt12(f) => Ok(f.write(w)?),
845 impl ReadableArgs<bool> for Features {
846 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
847 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
848 Ok(Self::Bolt12(Readable::read(reader)?))
852 /// A list of hops along a payment path terminating with a channel to the recipient.
853 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
854 pub struct RouteHint(pub Vec<RouteHintHop>);
856 impl Writeable for RouteHint {
857 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
858 (self.0.len() as u64).write(writer)?;
859 for hop in self.0.iter() {
866 impl Readable for RouteHint {
867 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
868 let hop_count: u64 = Readable::read(reader)?;
869 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
870 for _ in 0..hop_count {
871 hops.push(Readable::read(reader)?);
877 /// A channel descriptor for a hop along a payment path.
878 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
879 pub struct RouteHintHop {
880 /// The node_id of the non-target end of the route
881 pub src_node_id: PublicKey,
882 /// The short_channel_id of this channel
883 pub short_channel_id: u64,
884 /// The fees which must be paid to use this channel
885 pub fees: RoutingFees,
886 /// The difference in CLTV values between this node and the next node.
887 pub cltv_expiry_delta: u16,
888 /// The minimum value, in msat, which must be relayed to the next hop.
889 pub htlc_minimum_msat: Option<u64>,
890 /// The maximum value in msat available for routing with a single HTLC.
891 pub htlc_maximum_msat: Option<u64>,
894 impl_writeable_tlv_based!(RouteHintHop, {
895 (0, src_node_id, required),
896 (1, htlc_minimum_msat, option),
897 (2, short_channel_id, required),
898 (3, htlc_maximum_msat, option),
900 (6, cltv_expiry_delta, required),
903 #[derive(Eq, PartialEq)]
904 struct RouteGraphNode {
906 lowest_fee_to_node: u64,
907 total_cltv_delta: u32,
908 // The maximum value a yet-to-be-constructed payment path might flow through this node.
909 // This value is upper-bounded by us by:
910 // - how much is needed for a path being constructed
911 // - how much value can channels following this node (up to the destination) can contribute,
912 // considering their capacity and fees
913 value_contribution_msat: u64,
914 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
915 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
916 path_htlc_minimum_msat: u64,
917 /// All penalties incurred from this hop on the way to the destination, as calculated using
919 path_penalty_msat: u64,
920 /// The number of hops walked up to this node.
921 path_length_to_node: u8,
924 impl cmp::Ord for RouteGraphNode {
925 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
926 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
927 .saturating_add(other.path_penalty_msat);
928 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
929 .saturating_add(self.path_penalty_msat);
930 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
934 impl cmp::PartialOrd for RouteGraphNode {
935 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
936 Some(self.cmp(other))
940 /// A wrapper around the various hop representations.
942 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
943 #[derive(Clone, Debug)]
944 enum CandidateRouteHop<'a> {
945 /// A hop from the payer, where the outbound liquidity is known.
947 details: &'a ChannelDetails,
949 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
951 info: DirectedChannelInfo<'a>,
952 short_channel_id: u64,
954 /// A hop to the payee found in the BOLT 11 payment invoice, though not necessarily a direct
957 hint: &'a RouteHintHop,
959 /// The payee's identity is concealed behind blinded paths provided in a BOLT 12 invoice.
961 hint: &'a (BlindedPayInfo, BlindedPath),
964 /// Similar to [`Self::Blinded`], but the path here has 1 blinded hop. `BlindedPayInfo` provided
965 /// for 1-hop blinded paths is ignored because it is meant to apply to the hops *between* the
966 /// introduction node and the destination. Useful for tracking that we need to include a blinded
967 /// path at the end of our [`Route`].
969 hint: &'a (BlindedPayInfo, BlindedPath),
974 impl<'a> CandidateRouteHop<'a> {
975 fn short_channel_id(&self) -> Option<u64> {
977 CandidateRouteHop::FirstHop { details } => Some(details.get_outbound_payment_scid().unwrap()),
978 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
979 CandidateRouteHop::PrivateHop { hint } => Some(hint.short_channel_id),
980 CandidateRouteHop::Blinded { .. } => None,
981 CandidateRouteHop::OneHopBlinded { .. } => None,
985 // NOTE: This may alloc memory so avoid calling it in a hot code path.
986 fn features(&self) -> ChannelFeatures {
988 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
989 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
990 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
991 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
992 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
996 fn cltv_expiry_delta(&self) -> u32 {
998 CandidateRouteHop::FirstHop { .. } => 0,
999 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1000 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
1001 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1002 CandidateRouteHop::OneHopBlinded { .. } => 0,
1006 fn htlc_minimum_msat(&self) -> u64 {
1008 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_minimum_msat,
1009 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1010 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
1011 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1012 CandidateRouteHop::OneHopBlinded { .. } => 0,
1016 fn fees(&self) -> RoutingFees {
1018 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1019 base_msat: 0, proportional_millionths: 0,
1021 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1022 CandidateRouteHop::PrivateHop { hint } => hint.fees,
1023 CandidateRouteHop::Blinded { hint, .. } => {
1025 base_msat: hint.0.fee_base_msat,
1026 proportional_millionths: hint.0.fee_proportional_millionths
1029 CandidateRouteHop::OneHopBlinded { .. } =>
1030 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1034 fn effective_capacity(&self) -> EffectiveCapacity {
1036 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
1037 liquidity_msat: details.next_outbound_htlc_limit_msat,
1039 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1040 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }} =>
1041 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1042 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }} =>
1043 EffectiveCapacity::Infinite,
1044 CandidateRouteHop::Blinded { hint, .. } =>
1045 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1046 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1050 fn id(&self, channel_direction: bool /* src_node_id < target_node_id */) -> CandidateHopId {
1052 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1053 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1054 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), channel_direction)),
1057 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1059 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1067 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1068 enum CandidateHopId {
1069 /// Contains (scid, src_node_id < target_node_id)
1071 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1076 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1077 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1079 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1080 EffectiveCapacity::Infinite => u64::max_value(),
1081 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1082 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1083 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1084 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1085 // expected to have been generated from up-to-date capacity information.
1086 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1087 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1088 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1092 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1093 -> bool where I1::Item: PartialEq<I2::Item> {
1095 let a = iter_a.next();
1096 let b = iter_b.next();
1097 if a.is_none() && b.is_none() { return true; }
1098 if a.is_none() || b.is_none() { return false; }
1099 if a.unwrap().ne(&b.unwrap()) { return false; }
1103 /// It's useful to keep track of the hops associated with the fees required to use them,
1104 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1105 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1106 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1108 struct PathBuildingHop<'a> {
1109 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
1110 // is a larger refactor and will require careful performance analysis.
1112 candidate: CandidateRouteHop<'a>,
1115 /// All the fees paid *after* this channel on the way to the destination
1116 next_hops_fee_msat: u64,
1117 /// Fee paid for the use of the current channel (see candidate.fees()).
1118 /// The value will be actually deducted from the counterparty balance on the previous link.
1119 hop_use_fee_msat: u64,
1120 /// Used to compare channels when choosing the for routing.
1121 /// Includes paying for the use of a hop and the following hops, as well as
1122 /// an estimated cost of reaching this hop.
1123 /// Might get stale when fees are recomputed. Primarily for internal use.
1124 total_fee_msat: u64,
1125 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1126 /// walk and may be invalid thereafter.
1127 path_htlc_minimum_msat: u64,
1128 /// All penalties incurred from this channel on the way to the destination, as calculated using
1129 /// channel scoring.
1130 path_penalty_msat: u64,
1131 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1132 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1133 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1134 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1135 /// avoid processing them again.
1136 was_processed: bool,
1137 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1138 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1139 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1140 // value_contribution_msat, which requires tracking it here. See comments below where it is
1141 // used for more info.
1142 value_contribution_msat: u64,
1145 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1146 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1147 let mut debug_struct = f.debug_struct("PathBuildingHop");
1149 .field("node_id", &self.node_id)
1150 .field("short_channel_id", &self.candidate.short_channel_id())
1151 .field("total_fee_msat", &self.total_fee_msat)
1152 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1153 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1154 .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)))
1155 .field("path_penalty_msat", &self.path_penalty_msat)
1156 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1157 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1158 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1159 let debug_struct = debug_struct
1160 .field("value_contribution_msat", &self.value_contribution_msat);
1161 debug_struct.finish()
1165 // Instantiated with a list of hops with correct data in them collected during path finding,
1166 // an instance of this struct should be further modified only via given methods.
1168 struct PaymentPath<'a> {
1169 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1172 impl<'a> PaymentPath<'a> {
1173 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1174 fn get_value_msat(&self) -> u64 {
1175 self.hops.last().unwrap().0.fee_msat
1178 fn get_path_penalty_msat(&self) -> u64 {
1179 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1182 fn get_total_fee_paid_msat(&self) -> u64 {
1183 if self.hops.len() < 1 {
1187 // Can't use next_hops_fee_msat because it gets outdated.
1188 for (i, (hop, _)) in self.hops.iter().enumerate() {
1189 if i != self.hops.len() - 1 {
1190 result += hop.fee_msat;
1196 fn get_cost_msat(&self) -> u64 {
1197 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1200 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1201 // to change fees may result in an inconsistency.
1203 // Sometimes we call this function right after constructing a path which is inconsistent in
1204 // that it the value being transferred has decreased while we were doing path finding, leading
1205 // to the fees being paid not lining up with the actual limits.
1207 // Note that this function is not aware of the available_liquidity limit, and thus does not
1208 // support increasing the value being transferred beyond what was selected during the initial
1210 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
1211 let mut total_fee_paid_msat = 0 as u64;
1212 for i in (0..self.hops.len()).rev() {
1213 let last_hop = i == self.hops.len() - 1;
1215 // For non-last-hop, this value will represent the fees paid on the current hop. It
1216 // will consist of the fees for the use of the next hop, and extra fees to match
1217 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1218 let mut cur_hop_fees_msat = 0;
1220 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1223 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1224 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1225 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1226 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1227 // set it too high just to maliciously take more fees by exploiting this
1228 // match htlc_minimum_msat logic.
1229 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1230 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1231 // Note that there is a risk that *previous hops* (those closer to us, as we go
1232 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1234 // This might make us end up with a broken route, although this should be super-rare
1235 // in practice, both because of how healthy channels look like, and how we pick
1236 // channels in add_entry.
1237 // Also, this can't be exploited more heavily than *announce a free path and fail
1239 cur_hop_transferred_amount_msat += extra_fees_msat;
1240 total_fee_paid_msat += extra_fees_msat;
1241 cur_hop_fees_msat += extra_fees_msat;
1245 // Final hop is a special case: it usually has just value_msat (by design), but also
1246 // it still could overpay for the htlc_minimum_msat.
1247 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1249 // Propagate updated fees for the use of the channels to one hop back, where they
1250 // will be actually paid (fee_msat). The last hop is handled above separately.
1251 cur_hop.fee_msat = cur_hop_fees_msat;
1254 // Fee for the use of the current hop which will be deducted on the previous hop.
1255 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1256 // this channel is free for us.
1258 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1259 cur_hop.hop_use_fee_msat = new_fee;
1260 total_fee_paid_msat += new_fee;
1262 // It should not be possible because this function is called only to reduce the
1263 // value. In that case, compute_fee was already called with the same fees for
1264 // larger amount and there was no overflow.
1273 /// Calculate the fees required to route the given amount over a channel with the given fees.
1274 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1275 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1276 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1280 /// Calculate the fees required to route the given amount over a channel with the given fees,
1281 /// saturating to [`u64::max_value`].
1282 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1283 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1284 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1285 .saturating_add(channel_fees.base_msat as u64)
1288 /// The default `features` we assume for a node in a route, when no `features` are known about that
1291 /// Default features are:
1292 /// * variable_length_onion_optional
1293 fn default_node_features() -> NodeFeatures {
1294 let mut features = NodeFeatures::empty();
1295 features.set_variable_length_onion_optional();
1299 struct LoggedPayeePubkey(Option<PublicKey>);
1300 impl fmt::Display for LoggedPayeePubkey {
1301 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1304 "payee node id ".fmt(f)?;
1308 "blinded payee".fmt(f)
1314 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1315 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1316 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1318 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1319 "blinded route hint with introduction node id ".fmt(f)?;
1320 hint.1.introduction_node_id.fmt(f)?;
1321 " and blinding point ".fmt(f)?;
1322 hint.1.blinding_point.fmt(f)
1326 self.0.short_channel_id().unwrap().fmt(f)
1333 fn sort_first_hop_channels(
1334 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1335 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1337 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1338 // most like to use.
1340 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1341 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1344 // Second, because simply always sorting in descending order would always use our largest
1345 // available outbound capacity, needlessly fragmenting our available channel capacities,
1346 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1347 // which have enough, but not too much, capacity for the payment.
1349 // Available outbound balances factor in liquidity already reserved for previously found paths.
1350 channels.sort_unstable_by(|chan_a, chan_b| {
1351 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1352 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1353 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1354 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1355 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1356 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1357 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1358 // Sort in descending order
1359 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1361 // Sort in ascending order
1362 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1367 /// Finds a route from us (payer) to the given target node (payee).
1369 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
1370 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1372 /// Private routing paths between a public node and the target may be included in `params.payee`.
1374 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1375 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1376 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1378 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1379 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1380 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1384 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
1385 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
1390 /// Panics if first_hops contains channels without short_channel_ids;
1391 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1393 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1394 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1395 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1396 pub fn find_route<L: Deref, GL: Deref, S: Score>(
1397 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1398 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1399 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1400 ) -> Result<Route, LightningError>
1401 where L::Target: Logger, GL::Target: Logger {
1402 let graph_lock = network_graph.read_only();
1403 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
1404 route_params.final_value_msat, logger, scorer, score_params,
1405 random_seed_bytes)?;
1406 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1410 pub(crate) fn get_route<L: Deref, S: Score>(
1411 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
1412 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, logger: L, scorer: &S, score_params: &S::ScoreParams,
1413 _random_seed_bytes: &[u8; 32]
1414 ) -> Result<Route, LightningError>
1415 where L::Target: Logger {
1416 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1417 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1418 // so use a dummy id for this in the blinded case.
1419 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1420 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1421 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1422 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1423 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1425 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1426 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1429 if final_value_msat > MAX_VALUE_MSAT {
1430 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1433 if final_value_msat == 0 {
1434 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1437 match &payment_params.payee {
1438 Payee::Clear { route_hints, node_id, .. } => {
1439 for route in route_hints.iter() {
1440 for hop in &route.0 {
1441 if hop.src_node_id == *node_id {
1442 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1447 Payee::Blinded { route_hints, .. } => {
1448 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1449 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});
1451 for (_, blinded_path) in route_hints.iter() {
1452 if blinded_path.blinded_hops.len() == 0 {
1453 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1454 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1455 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1456 } else if blinded_path.blinded_hops.len() == 1 &&
1457 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1458 && p.introduction_node_id != blinded_path.introduction_node_id)
1460 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1465 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1466 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1467 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});
1470 // The general routing idea is the following:
1471 // 1. Fill first/last hops communicated by the caller.
1472 // 2. Attempt to construct a path from payer to payee for transferring
1473 // any ~sufficient (described later) value.
1474 // If succeed, remember which channels were used and how much liquidity they have available,
1475 // so that future paths don't rely on the same liquidity.
1476 // 3. Proceed to the next step if:
1477 // - we hit the recommended target value;
1478 // - OR if we could not construct a new path. Any next attempt will fail too.
1479 // Otherwise, repeat step 2.
1480 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1481 // (not recommended value).
1482 // 5. If yes, proceed. If not, fail routing.
1483 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1484 // transferred up to the transfer target value.
1485 // 7. Reduce the value of the last path until we are sending only the target value.
1486 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1487 // them so that we're not sending two HTLCs along the same path.
1489 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1490 // distance from the payee
1492 // We are not a faithful Dijkstra's implementation because we can change values which impact
1493 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1494 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1495 // the value we are currently attempting to send over a path, we simply reduce the value being
1496 // sent along the path for any hops after that channel. This may imply that later fees (which
1497 // we've already tabulated) are lower because a smaller value is passing through the channels
1498 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1499 // channels which were selected earlier (and which may still be used for other paths without a
1500 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1503 // One potentially problematic case for this algorithm would be if there are many
1504 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1505 // graph walking), we may never find a path which is not liquidity-limited and has lower
1506 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1507 // Because we only consider paths with at least 5% of the total value being sent, the damage
1508 // from such a case should be limited, however this could be further reduced in the future by
1509 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1510 // limits for the purposes of fee calculation.
1512 // Alternatively, we could store more detailed path information in the heap (targets, below)
1513 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1514 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1515 // and practically (as we would need to store dynamically-allocated path information in heap
1516 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1517 // results of such an algorithm would likely be biased towards lower-value paths.
1519 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1520 // outside of our current search value, running a path search more times to gather candidate
1521 // paths at different values. While this may be acceptable, further path searches may increase
1522 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1523 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1524 // the same time, remaining generic across different payment values.
1526 let network_channels = network_graph.channels();
1527 let network_nodes = network_graph.nodes();
1529 if payment_params.max_path_count == 0 {
1530 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1533 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1534 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1536 let allow_mpp = if payment_params.max_path_count == 1 {
1538 } else if payment_params.payee.supports_basic_mpp() {
1540 } else if let Some(payee) = payee_node_id_opt {
1541 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1542 |info| info.features.supports_basic_mpp()))
1545 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1546 LoggedPayeePubkey(payment_params.payee.node_id()), if allow_mpp { "with" } else { "without" },
1547 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1550 // Prepare the data we'll use for payee-to-payer search by
1551 // inserting first hops suggested by the caller as targets.
1552 // Our search will then attempt to reach them while traversing from the payee node.
1553 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1554 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1555 if let Some(hops) = first_hops {
1557 if chan.get_outbound_payment_scid().is_none() {
1558 panic!("first_hops should be filled in with usable channels, not pending ones");
1560 if chan.counterparty.node_id == *our_node_pubkey {
1561 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1564 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1565 .or_insert(Vec::new())
1568 if first_hop_targets.is_empty() {
1569 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1573 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1574 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1575 // adding duplicate entries when we find a better path to a given node.
1576 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1578 // Map from node_id to information about the best current path to that node, including feerate
1580 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1582 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1583 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1584 // htlc_minimum with extra fees while still finding a cheaper path.
1585 let mut hit_minimum_limit;
1587 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1588 // We start with a path_value of the exact amount we want, and if that generates a route we may
1589 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1590 // amount we want in total across paths, selecting the best subset at the end.
1591 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1592 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1593 let mut path_value_msat = final_value_msat;
1595 // Routing Fragmentation Mitigation heuristic:
1597 // Routing fragmentation across many payment paths increases the overall routing
1598 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1599 // Taking too many smaller paths also increases the chance of payment failure.
1600 // Thus to avoid this effect, we require from our collected links to provide
1601 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1602 // This requirement is currently set to be 1/max_path_count of the payment
1603 // value to ensure we only ever return routes that do not violate this limit.
1604 let minimal_value_contribution_msat: u64 = if allow_mpp {
1605 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1610 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1611 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1612 // drop the requirement by setting this to 0.
1613 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1615 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1616 // determine if the channel can be used by additional MPP paths or to inform path finding
1617 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1618 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1620 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1621 HashMap::with_capacity(network_nodes.len());
1623 // Keeping track of how much value we already collected across other paths. Helps to decide
1624 // when we want to stop looking for new paths.
1625 let mut already_collected_value_msat = 0;
1627 for (_, channels) in first_hop_targets.iter_mut() {
1628 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1632 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1633 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1635 macro_rules! add_entry {
1636 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1637 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1638 // since that value has to be transferred over this channel.
1639 // Returns whether this channel caused an update to `targets`.
1640 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1641 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1642 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1643 // We "return" whether we updated the path at the end, and how much we can route via
1644 // this channel, via this:
1645 let mut did_add_update_path_to_src_node = None;
1646 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1647 // practice these cases should be caught earlier:
1648 // - for regular channels at channel announcement (TODO)
1649 // - for first and last hops early in get_route
1650 if $src_node_id != $dest_node_id {
1651 let scid_opt = $candidate.short_channel_id();
1652 let effective_capacity = $candidate.effective_capacity();
1653 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1655 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1656 // It may be misleading because we might later choose to reduce the value transferred
1657 // over these channels, and the channel which was insufficient might become sufficient.
1658 // Worst case: we drop a good channel here because it can't cover the high following
1659 // fees caused by one expensive channel, but then this channel could have been used
1660 // if the amount being transferred over this path is lower.
1661 // We do this for now, but this is a subject for removal.
1662 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1663 let used_liquidity_msat = used_liquidities
1664 .get(&$candidate.id($src_node_id < $dest_node_id))
1665 .map_or(0, |used_liquidity_msat| {
1666 available_value_contribution_msat = available_value_contribution_msat
1667 .saturating_sub(*used_liquidity_msat);
1668 *used_liquidity_msat
1671 // Verify the liquidity offered by this channel complies to the minimal contribution.
1672 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1673 // Do not consider candidate hops that would exceed the maximum path length.
1674 let path_length_to_node = $next_hops_path_length + 1;
1675 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1677 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1678 // In order to already account for some of the privacy enhancing random CLTV
1679 // expiry delta offset we add on top later, we subtract a rough estimate
1680 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1681 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1682 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1683 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1684 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1685 .saturating_add($candidate.cltv_expiry_delta());
1686 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1688 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1689 // Includes paying fees for the use of the following channels.
1690 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1691 Some(result) => result,
1692 // Can't overflow due to how the values were computed right above.
1693 None => unreachable!(),
1695 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1696 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1697 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1699 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1700 let may_overpay_to_meet_path_minimum_msat =
1701 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1702 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1703 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1704 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1706 let payment_failed_on_this_channel = scid_opt.map_or(false,
1707 |scid| payment_params.previously_failed_channels.contains(&scid));
1709 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1710 // bother considering this channel. If retrying with recommended_value_msat may
1711 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1712 // around again with a higher amount.
1713 if !contributes_sufficient_value || exceeds_max_path_length ||
1714 exceeds_cltv_delta_limit || payment_failed_on_this_channel {
1715 // Path isn't useful, ignore it and move on.
1716 } else if may_overpay_to_meet_path_minimum_msat {
1717 hit_minimum_limit = true;
1718 } else if over_path_minimum_msat {
1719 // Note that low contribution here (limited by available_liquidity_msat)
1720 // might violate htlc_minimum_msat on the hops which are next along the
1721 // payment path (upstream to the payee). To avoid that, we recompute
1722 // path fees knowing the final path contribution after constructing it.
1723 let path_htlc_minimum_msat = cmp::max(
1724 compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1725 .saturating_add($next_hops_path_htlc_minimum_msat),
1726 $candidate.htlc_minimum_msat());
1727 let hm_entry = dist.entry($src_node_id);
1728 let old_entry = hm_entry.or_insert_with(|| {
1729 // If there was previously no known way to access the source node
1730 // (recall it goes payee-to-payer) of short_channel_id, first add a
1731 // semi-dummy record just to compute the fees to reach the source node.
1732 // This will affect our decision on selecting short_channel_id
1733 // as a way to reach the $dest_node_id.
1735 node_id: $dest_node_id.clone(),
1736 candidate: $candidate.clone(),
1738 next_hops_fee_msat: u64::max_value(),
1739 hop_use_fee_msat: u64::max_value(),
1740 total_fee_msat: u64::max_value(),
1741 path_htlc_minimum_msat,
1742 path_penalty_msat: u64::max_value(),
1743 was_processed: false,
1744 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1745 value_contribution_msat,
1749 #[allow(unused_mut)] // We only use the mut in cfg(test)
1750 let mut should_process = !old_entry.was_processed;
1751 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1753 // In test/fuzzing builds, we do extra checks to make sure the skipping
1754 // of already-seen nodes only happens in cases we expect (see below).
1755 if !should_process { should_process = true; }
1759 let mut hop_use_fee_msat = 0;
1760 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1762 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1763 // will have the same effective-fee
1764 if $src_node_id != our_node_id {
1765 // Note that `u64::max_value` means we'll always fail the
1766 // `old_entry.total_fee_msat > total_fee_msat` check below
1767 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1768 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1771 let channel_usage = ChannelUsage {
1772 amount_msat: amount_to_transfer_over_msat,
1773 inflight_htlc_msat: used_liquidity_msat,
1776 let channel_penalty_msat = scid_opt.map_or(0,
1777 |scid| scorer.channel_penalty_msat(scid, &$src_node_id, &$dest_node_id,
1778 channel_usage, score_params));
1779 let path_penalty_msat = $next_hops_path_penalty_msat
1780 .saturating_add(channel_penalty_msat);
1781 let new_graph_node = RouteGraphNode {
1782 node_id: $src_node_id,
1783 lowest_fee_to_node: total_fee_msat,
1784 total_cltv_delta: hop_total_cltv_delta,
1785 value_contribution_msat,
1786 path_htlc_minimum_msat,
1788 path_length_to_node,
1791 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1792 // if this way is cheaper than the already known
1793 // (considering the cost to "reach" this channel from the route destination,
1794 // the cost of using this channel,
1795 // and the cost of routing to the source node of this channel).
1796 // Also, consider that htlc_minimum_msat_difference, because we might end up
1797 // paying it. Consider the following exploit:
1798 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1799 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1800 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1801 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1803 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1804 // but it may require additional tracking - we don't want to double-count
1805 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1806 // can't use something that may decrease on future hops.
1807 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1808 .saturating_add(old_entry.path_penalty_msat);
1809 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1810 .saturating_add(path_penalty_msat);
1812 if !old_entry.was_processed && new_cost < old_cost {
1813 targets.push(new_graph_node);
1814 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1815 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1816 old_entry.total_fee_msat = total_fee_msat;
1817 old_entry.node_id = $dest_node_id.clone();
1818 old_entry.candidate = $candidate.clone();
1819 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1820 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1821 old_entry.path_penalty_msat = path_penalty_msat;
1822 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1824 old_entry.value_contribution_msat = value_contribution_msat;
1826 did_add_update_path_to_src_node = Some(value_contribution_msat);
1827 } else if old_entry.was_processed && new_cost < old_cost {
1828 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1830 // If we're skipping processing a node which was previously
1831 // processed even though we found another path to it with a
1832 // cheaper fee, check that it was because the second path we
1833 // found (which we are processing now) has a lower value
1834 // contribution due to an HTLC minimum limit.
1836 // e.g. take a graph with two paths from node 1 to node 2, one
1837 // through channel A, and one through channel B. Channel A and
1838 // B are both in the to-process heap, with their scores set by
1839 // a higher htlc_minimum than fee.
1840 // Channel A is processed first, and the channels onwards from
1841 // node 1 are added to the to-process heap. Thereafter, we pop
1842 // Channel B off of the heap, note that it has a much more
1843 // restrictive htlc_maximum_msat, and recalculate the fees for
1844 // all of node 1's channels using the new, reduced, amount.
1846 // This would be bogus - we'd be selecting a higher-fee path
1847 // with a lower htlc_maximum_msat instead of the one we'd
1848 // already decided to use.
1849 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1851 value_contribution_msat + path_penalty_msat <
1852 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1860 did_add_update_path_to_src_node
1864 let default_node_features = default_node_features();
1866 // Find ways (channels with destination) to reach a given node and store them
1867 // in the corresponding data structures (routing graph etc).
1868 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1869 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1870 // This data can later be helpful to optimize routing (pay lower fees).
1871 macro_rules! add_entries_to_cheapest_to_target_node {
1872 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1873 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1874 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1875 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1876 let was_processed = elem.was_processed;
1877 elem.was_processed = true;
1880 // Entries are added to dist in add_entry!() when there is a channel from a node.
1881 // Because there are no channels from payee, it will not have a dist entry at this point.
1882 // If we're processing any other node, it is always be the result of a channel from it.
1883 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
1888 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1889 for details in first_channels {
1890 let candidate = CandidateRouteHop::FirstHop { details };
1891 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1892 $next_hops_value_contribution,
1893 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1894 $next_hops_cltv_delta, $next_hops_path_length);
1898 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1901 &default_node_features
1904 if !features.requires_unknown_bits() {
1905 for chan_id in $node.channels.iter() {
1906 let chan = network_channels.get(chan_id).unwrap();
1907 if !chan.features.requires_unknown_bits() {
1908 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1909 if first_hops.is_none() || *source != our_node_id {
1910 if directed_channel.direction().enabled {
1911 let candidate = CandidateRouteHop::PublicHop {
1912 info: directed_channel,
1913 short_channel_id: *chan_id,
1915 add_entry!(candidate, *source, $node_id,
1916 $fee_to_target_msat,
1917 $next_hops_value_contribution,
1918 $next_hops_path_htlc_minimum_msat,
1919 $next_hops_path_penalty_msat,
1920 $next_hops_cltv_delta, $next_hops_path_length);
1931 let mut payment_paths = Vec::<PaymentPath>::new();
1933 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1934 'paths_collection: loop {
1935 // For every new path, start from scratch, except for used_liquidities, which
1936 // helps to avoid reusing previously selected paths in future iterations.
1939 hit_minimum_limit = false;
1941 // If first hop is a private channel and the only way to reach the payee, this is the only
1942 // place where it could be added.
1943 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
1944 for details in first_channels {
1945 let candidate = CandidateRouteHop::FirstHop { details };
1946 let added = add_entry!(candidate, our_node_id, payee, 0, path_value_msat,
1947 0, 0u64, 0, 0).is_some();
1948 log_trace!(logger, "{} direct route to payee via {}",
1949 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
1953 // Add the payee as a target, so that the payee-to-payer
1954 // search algorithm knows what to start with.
1955 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
1956 // The payee is not in our network graph, so nothing to add here.
1957 // There is still a chance of reaching them via last_hops though,
1958 // so don't yet fail the payment here.
1959 // If not, targets.pop() will not even let us enter the loop in step 2.
1962 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
1967 // If a caller provided us with last hops, add them to routing targets. Since this happens
1968 // earlier than general path finding, they will be somewhat prioritized, although currently
1969 // it matters only if the fees are exactly the same.
1970 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
1971 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
1972 let have_intro_node_in_graph =
1973 // Only add the hops in this route to our candidate set if either
1974 // we have a direct channel to the first hop or the first hop is
1975 // in the regular network graph.
1976 first_hop_targets.get(&intro_node_id).is_some() ||
1977 network_nodes.get(&intro_node_id).is_some();
1978 if !have_intro_node_in_graph { continue }
1979 let candidate = if hint.1.blinded_hops.len() == 1 {
1980 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
1981 } else { CandidateRouteHop::Blinded { hint, hint_idx } };
1982 let mut path_contribution_msat = path_value_msat;
1983 if let Some(hop_used_msat) = add_entry!(candidate, intro_node_id, maybe_dummy_payee_node_id,
1984 0, path_contribution_msat, 0, 0_u64, 0, 0)
1986 path_contribution_msat = hop_used_msat;
1988 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
1989 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
1991 for details in first_channels {
1992 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
1993 add_entry!(first_hop_candidate, our_node_id, intro_node_id, 0, path_contribution_msat, 0,
1998 for route in payment_params.payee.unblinded_route_hints().iter()
1999 .filter(|route| !route.0.is_empty())
2001 let first_hop_in_route = &(route.0)[0];
2002 let have_hop_src_in_graph =
2003 // Only add the hops in this route to our candidate set if either
2004 // we have a direct channel to the first hop or the first hop is
2005 // in the regular network graph.
2006 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
2007 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
2008 if have_hop_src_in_graph {
2009 // We start building the path from reverse, i.e., from payee
2010 // to the first RouteHintHop in the path.
2011 let hop_iter = route.0.iter().rev();
2012 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2013 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2014 let mut hop_used = true;
2015 let mut aggregate_next_hops_fee_msat: u64 = 0;
2016 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2017 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2018 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2019 let mut aggregate_next_hops_path_length: u8 = 0;
2020 let mut aggregate_path_contribution_msat = path_value_msat;
2022 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2023 let source = NodeId::from_pubkey(&hop.src_node_id);
2024 let target = NodeId::from_pubkey(&prev_hop_id);
2025 let candidate = network_channels
2026 .get(&hop.short_channel_id)
2027 .and_then(|channel| channel.as_directed_to(&target))
2028 .map(|(info, _)| CandidateRouteHop::PublicHop {
2030 short_channel_id: hop.short_channel_id,
2032 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
2034 if let Some(hop_used_msat) = add_entry!(candidate, source, target,
2035 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2036 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2037 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2039 aggregate_path_contribution_msat = hop_used_msat;
2041 // If this hop was not used then there is no use checking the preceding
2042 // hops in the RouteHint. We can break by just searching for a direct
2043 // channel between last checked hop and first_hop_targets.
2047 let used_liquidity_msat = used_liquidities
2048 .get(&candidate.id(source < target)).copied()
2050 let channel_usage = ChannelUsage {
2051 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2052 inflight_htlc_msat: used_liquidity_msat,
2053 effective_capacity: candidate.effective_capacity(),
2055 let channel_penalty_msat = scorer.channel_penalty_msat(
2056 hop.short_channel_id, &source, &target, channel_usage, score_params
2058 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2059 .saturating_add(channel_penalty_msat);
2061 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2062 .saturating_add(hop.cltv_expiry_delta as u32);
2064 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2067 // Searching for a direct channel between last checked hop and first_hop_targets
2068 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&prev_hop_id)) {
2069 sort_first_hop_channels(first_channels, &used_liquidities,
2070 recommended_value_msat, our_node_pubkey);
2071 for details in first_channels {
2072 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2073 add_entry!(first_hop_candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
2074 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2075 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2076 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2084 // In the next values of the iterator, the aggregate fees already reflects
2085 // the sum of value sent from payer (final_value_msat) and routing fees
2086 // for the last node in the RouteHint. We need to just add the fees to
2087 // route through the current node so that the preceding node (next iteration)
2089 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2090 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2091 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2093 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
2094 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
2095 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
2096 .checked_add(hop_htlc_minimum_msat_inc);
2097 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
2099 if idx == route.0.len() - 1 {
2100 // The last hop in this iterator is the first hop in
2101 // overall RouteHint.
2102 // If this hop connects to a node with which we have a direct channel,
2103 // ignore the network graph and, if the last hop was added, add our
2104 // direct channel to the candidate set.
2106 // Note that we *must* check if the last hop was added as `add_entry`
2107 // always assumes that the third argument is a node to which we have a
2109 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2110 sort_first_hop_channels(first_channels, &used_liquidities,
2111 recommended_value_msat, our_node_pubkey);
2112 for details in first_channels {
2113 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2114 add_entry!(first_hop_candidate, our_node_id,
2115 NodeId::from_pubkey(&hop.src_node_id),
2116 aggregate_next_hops_fee_msat,
2117 aggregate_path_contribution_msat,
2118 aggregate_next_hops_path_htlc_minimum_msat,
2119 aggregate_next_hops_path_penalty_msat,
2120 aggregate_next_hops_cltv_delta,
2121 aggregate_next_hops_path_length);
2129 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2131 // At this point, targets are filled with the data from first and
2132 // last hops communicated by the caller, and the payment receiver.
2133 let mut found_new_path = false;
2136 // If this loop terminates due the exhaustion of targets, two situations are possible:
2137 // - not enough outgoing liquidity:
2138 // 0 < already_collected_value_msat < final_value_msat
2139 // - enough outgoing liquidity:
2140 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2141 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2142 // paths_collection will be stopped because found_new_path==false.
2143 // This is not necessarily a routing failure.
2144 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, total_cltv_delta, mut value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, path_length_to_node, .. }) = targets.pop() {
2146 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2147 // traversing the graph and arrange the path out of what we found.
2148 if node_id == our_node_id {
2149 let mut new_entry = dist.remove(&our_node_id).unwrap();
2150 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2153 let mut features_set = false;
2154 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
2155 for details in first_channels {
2156 if let Some(scid) = ordered_hops.last().unwrap().0.candidate.short_channel_id() {
2157 if details.get_outbound_payment_scid().unwrap() == scid {
2158 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2159 features_set = true;
2166 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
2167 if let Some(node_info) = node.announcement_info.as_ref() {
2168 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2170 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2173 // We can fill in features for everything except hops which were
2174 // provided via the invoice we're paying. We could guess based on the
2175 // recipient's features but for now we simply avoid guessing at all.
2179 // Means we succesfully traversed from the payer to the payee, now
2180 // save this path for the payment route. Also, update the liquidity
2181 // remaining on the used hops, so that we take them into account
2182 // while looking for more paths.
2183 if ordered_hops.last().unwrap().0.node_id == maybe_dummy_payee_node_id {
2187 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
2188 Some(payment_hop) => payment_hop,
2189 // We can't arrive at None because, if we ever add an entry to targets,
2190 // we also fill in the entry in dist (see add_entry!).
2191 None => unreachable!(),
2193 // We "propagate" the fees one hop backward (topologically) here,
2194 // so that fees paid for a HTLC forwarding on the current channel are
2195 // associated with the previous channel (where they will be subtracted).
2196 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2197 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2199 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2200 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2202 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2203 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2205 let mut payment_path = PaymentPath {hops: ordered_hops};
2207 // We could have possibly constructed a slightly inconsistent path: since we reduce
2208 // value being transferred along the way, we could have violated htlc_minimum_msat
2209 // on some channels we already passed (assuming dest->source direction). Here, we
2210 // recompute the fees again, so that if that's the case, we match the currently
2211 // underpaid htlc_minimum_msat with fees.
2212 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2213 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
2214 payment_path.update_value_and_recompute_fees(value_contribution_msat);
2216 // Since a path allows to transfer as much value as
2217 // the smallest channel it has ("bottleneck"), we should recompute
2218 // the fees so sender HTLC don't overpay fees when traversing
2219 // larger channels than the bottleneck. This may happen because
2220 // when we were selecting those channels we were not aware how much value
2221 // this path will transfer, and the relative fee for them
2222 // might have been computed considering a larger value.
2223 // Remember that we used these channels so that we don't rely
2224 // on the same liquidity in future paths.
2225 let mut prevented_redundant_path_selection = false;
2226 let prev_hop_iter = core::iter::once(&our_node_id)
2227 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
2228 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
2229 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2230 let used_liquidity_msat = used_liquidities
2231 .entry(hop.candidate.id(*prev_hop < hop.node_id))
2232 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2233 .or_insert(spent_on_hop_msat);
2234 let hop_capacity = hop.candidate.effective_capacity();
2235 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2236 if *used_liquidity_msat == hop_max_msat {
2237 // If this path used all of this channel's available liquidity, we know
2238 // this path will not be selected again in the next loop iteration.
2239 prevented_redundant_path_selection = true;
2241 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2243 if !prevented_redundant_path_selection {
2244 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2245 // we'll probably end up picking the same path again on the next iteration.
2246 // Decrease the available liquidity of a hop in the middle of the path.
2247 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2248 let exhausted = u64::max_value();
2249 log_trace!(logger, "Disabling route candidate {} for future path building iterations to
2250 avoid duplicates.", LoggedCandidateHop(victim_candidate));
2251 *used_liquidities.entry(victim_candidate.id(false)).or_default() = exhausted;
2252 *used_liquidities.entry(victim_candidate.id(true)).or_default() = exhausted;
2255 // Track the total amount all our collected paths allow to send so that we know
2256 // when to stop looking for more paths
2257 already_collected_value_msat += value_contribution_msat;
2259 payment_paths.push(payment_path);
2260 found_new_path = true;
2261 break 'path_construction;
2264 // If we found a path back to the payee, we shouldn't try to process it again. This is
2265 // the equivalent of the `elem.was_processed` check in
2266 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2267 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2269 // Otherwise, since the current target node is not us,
2270 // keep "unrolling" the payment graph from payee to payer by
2271 // finding a way to reach the current target from the payer side.
2272 match network_nodes.get(&node_id) {
2275 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2276 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2277 total_cltv_delta, path_length_to_node);
2283 if !found_new_path && channel_saturation_pow_half != 0 {
2284 channel_saturation_pow_half = 0;
2285 continue 'paths_collection;
2287 // If we don't support MPP, no use trying to gather more value ever.
2288 break 'paths_collection;
2292 // Stop either when the recommended value is reached or if no new path was found in this
2294 // In the latter case, making another path finding attempt won't help,
2295 // because we deterministically terminated the search due to low liquidity.
2296 if !found_new_path && channel_saturation_pow_half != 0 {
2297 channel_saturation_pow_half = 0;
2298 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2299 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2300 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2301 break 'paths_collection;
2302 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2303 // Further, if this was our first walk of the graph, and we weren't limited by an
2304 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2305 // limited by an htlc_minimum_msat value, find another path with a higher value,
2306 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2307 // still keeping a lower total fee than this path.
2308 if !hit_minimum_limit {
2309 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2310 break 'paths_collection;
2312 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
2313 path_value_msat = recommended_value_msat;
2318 if payment_paths.len() == 0 {
2319 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2322 if already_collected_value_msat < final_value_msat {
2323 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2327 let mut selected_route = payment_paths;
2329 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2330 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2332 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2333 // the value they contribute towards the payment amount.
2334 // We sort in descending order as we will remove from the front in `retain`, next.
2335 selected_route.sort_unstable_by(|a, b|
2336 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2337 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2340 // We should make sure that at least 1 path left.
2341 let mut paths_left = selected_route.len();
2342 selected_route.retain(|path| {
2343 if paths_left == 1 {
2346 let path_value_msat = path.get_value_msat();
2347 if path_value_msat <= overpaid_value_msat {
2348 overpaid_value_msat -= path_value_msat;
2354 debug_assert!(selected_route.len() > 0);
2356 if overpaid_value_msat != 0 {
2358 // Now, subtract the remaining overpaid value from the most-expensive path.
2359 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2360 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2361 selected_route.sort_unstable_by(|a, b| {
2362 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2363 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2364 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2366 let expensive_payment_path = selected_route.first_mut().unwrap();
2368 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2369 // can't go negative.
2370 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2371 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2375 // Sort by the path itself and combine redundant paths.
2376 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2377 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2379 selected_route.sort_unstable_by_key(|path| {
2380 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2381 debug_assert!(path.hops.len() <= key.len());
2382 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id(true)).zip(key.iter_mut()) {
2387 for idx in 0..(selected_route.len() - 1) {
2388 if idx + 1 >= selected_route.len() { break; }
2389 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id)),
2390 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id))) {
2391 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2392 selected_route[idx].update_value_and_recompute_fees(new_value);
2393 selected_route.remove(idx + 1);
2397 let mut paths = Vec::new();
2398 for payment_path in selected_route {
2399 let mut hops = Vec::with_capacity(payment_path.hops.len());
2400 for (hop, node_features) in payment_path.hops.iter()
2401 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2403 hops.push(RouteHop {
2404 pubkey: PublicKey::from_slice(hop.node_id.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &hop.node_id), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
2405 node_features: node_features.clone(),
2406 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2407 channel_features: hop.candidate.features(),
2408 fee_msat: hop.fee_msat,
2409 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2412 let mut final_cltv_delta = final_cltv_expiry_delta;
2413 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2414 if let Some(blinded_path) = h.candidate.blinded_path() {
2415 final_cltv_delta = h.candidate.cltv_expiry_delta();
2417 hops: blinded_path.blinded_hops.clone(),
2418 blinding_point: blinded_path.blinding_point,
2419 excess_final_cltv_expiry_delta: 0,
2420 final_value_msat: h.fee_msat,
2424 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2425 // applicable for the previous hop.
2426 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2427 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2430 paths.push(Path { hops, blinded_tail });
2432 // Make sure we would never create a route with more paths than we allow.
2433 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2435 if let Some(node_features) = payment_params.payee.node_features() {
2436 for path in paths.iter_mut() {
2437 path.hops.last_mut().unwrap().node_features = node_features.clone();
2441 let route = Route { paths, payment_params: Some(payment_params.clone()) };
2442 log_info!(logger, "Got route: {}", log_route!(route));
2446 // When an adversarial intermediary node observes a payment, it may be able to infer its
2447 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2448 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2449 // payment path by adding a randomized 'shadow route' offset to the final hop.
2450 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2451 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2453 let network_channels = network_graph.channels();
2454 let network_nodes = network_graph.nodes();
2456 for path in route.paths.iter_mut() {
2457 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2459 // Remember the last three nodes of the random walk and avoid looping back on them.
2460 // Init with the last three nodes from the actual path, if possible.
2461 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2462 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2463 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2465 // Choose the last publicly known node as the starting point for the random walk.
2466 let mut cur_hop: Option<NodeId> = None;
2467 let mut path_nonce = [0u8; 12];
2468 if let Some(starting_hop) = path.hops.iter().rev()
2469 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2470 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2471 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2474 // Init PRNG with the path-dependant nonce, which is static for private paths.
2475 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2476 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2478 // Pick a random path length in [1 .. 3]
2479 prng.process_in_place(&mut random_path_bytes);
2480 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2482 for random_hop in 0..random_walk_length {
2483 // If we don't find a suitable offset in the public network graph, we default to
2484 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2485 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2487 if let Some(cur_node_id) = cur_hop {
2488 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2489 // Randomly choose the next unvisited hop.
2490 prng.process_in_place(&mut random_path_bytes);
2491 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2492 .checked_rem(cur_node.channels.len())
2493 .and_then(|index| cur_node.channels.get(index))
2494 .and_then(|id| network_channels.get(id)) {
2495 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2496 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2497 nodes_to_avoid[random_hop] = *next_id;
2498 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2499 cur_hop = Some(*next_id);
2506 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2507 .checked_add(random_hop_offset)
2508 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2511 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2512 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2513 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2515 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2516 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2517 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2518 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2519 max_path_offset = cmp::max(
2520 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2521 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2522 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2524 // Add 'shadow' CLTV offset to the final hop
2525 if let Some(tail) = path.blinded_tail.as_mut() {
2526 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2527 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2529 if let Some(last_hop) = path.hops.last_mut() {
2530 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2531 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2536 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2537 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2539 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2540 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2541 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2542 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2543 ) -> Result<Route, LightningError>
2544 where L::Target: Logger, GL::Target: Logger {
2545 let graph_lock = network_graph.read_only();
2546 let mut route = build_route_from_hops_internal(
2547 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
2548 route_params.final_value_msat, logger, random_seed_bytes)?;
2549 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2553 fn build_route_from_hops_internal<L: Deref>(
2554 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
2555 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, logger: L,
2556 random_seed_bytes: &[u8; 32]
2557 ) -> Result<Route, LightningError> where L::Target: Logger {
2560 our_node_id: NodeId,
2561 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2564 impl Score for HopScorer {
2565 type ScoreParams = ();
2566 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2567 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2569 let mut cur_id = self.our_node_id;
2570 for i in 0..self.hop_ids.len() {
2571 if let Some(next_id) = self.hop_ids[i] {
2572 if cur_id == *source && next_id == *target {
2583 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
2585 fn payment_path_successful(&mut self, _path: &Path) {}
2587 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
2589 fn probe_successful(&mut self, _path: &Path) {}
2592 impl<'a> Writeable for HopScorer {
2594 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2599 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2600 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2603 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2604 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2605 for i in 0..hops.len() {
2606 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2609 let scorer = HopScorer { our_node_id, hop_ids };
2611 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
2612 logger, &scorer, &(), random_seed_bytes)
2617 use crate::blinded_path::{BlindedHop, BlindedPath};
2618 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2619 use crate::routing::utxo::UtxoResult;
2620 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2621 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2622 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
2623 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, Score, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2624 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2625 use crate::chain::transaction::OutPoint;
2626 use crate::sign::EntropySource;
2627 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2628 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2629 use crate::ln::channelmanager;
2630 use crate::offers::invoice::BlindedPayInfo;
2631 use crate::util::config::UserConfig;
2632 use crate::util::test_utils as ln_test_utils;
2633 use crate::util::chacha20::ChaCha20;
2634 use crate::util::ser::{Readable, Writeable};
2636 use crate::util::ser::Writer;
2638 use bitcoin::hashes::Hash;
2639 use bitcoin::network::constants::Network;
2640 use bitcoin::blockdata::constants::genesis_block;
2641 use bitcoin::blockdata::script::Builder;
2642 use bitcoin::blockdata::opcodes;
2643 use bitcoin::blockdata::transaction::TxOut;
2647 use bitcoin::secp256k1::{PublicKey,SecretKey};
2648 use bitcoin::secp256k1::Secp256k1;
2650 use crate::io::Cursor;
2651 use crate::prelude::*;
2652 use crate::sync::Arc;
2654 use core::convert::TryInto;
2656 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2657 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2658 channelmanager::ChannelDetails {
2659 channel_id: [0; 32],
2660 counterparty: channelmanager::ChannelCounterparty {
2663 unspendable_punishment_reserve: 0,
2664 forwarding_info: None,
2665 outbound_htlc_minimum_msat: None,
2666 outbound_htlc_maximum_msat: None,
2668 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2671 outbound_scid_alias: None,
2672 inbound_scid_alias: None,
2673 channel_value_satoshis: 0,
2676 outbound_capacity_msat,
2677 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2678 next_outbound_htlc_minimum_msat: 0,
2679 inbound_capacity_msat: 42,
2680 unspendable_punishment_reserve: None,
2681 confirmations_required: None,
2682 confirmations: None,
2683 force_close_spend_delay: None,
2684 is_outbound: true, is_channel_ready: true,
2685 is_usable: true, is_public: true,
2686 inbound_htlc_minimum_msat: None,
2687 inbound_htlc_maximum_msat: None,
2689 feerate_sat_per_1000_weight: None
2694 fn simple_route_test() {
2695 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2696 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2697 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2698 let scorer = ln_test_utils::TestScorer::new();
2699 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2700 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2702 // Simple route to 2 via 1
2704 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 0, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2705 assert_eq!(err, "Cannot send a payment of 0 msat");
2706 } else { panic!(); }
2708 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2709 assert_eq!(route.paths[0].hops.len(), 2);
2711 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2712 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2713 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2714 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2715 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2716 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2718 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2719 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2720 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2721 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2722 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2723 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2727 fn invalid_first_hop_test() {
2728 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2729 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2730 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2731 let scorer = ln_test_utils::TestScorer::new();
2732 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2733 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2735 // Simple route to 2 via 1
2737 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2739 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2740 get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2741 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2742 } else { panic!(); }
2744 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2745 assert_eq!(route.paths[0].hops.len(), 2);
2749 fn htlc_minimum_test() {
2750 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2751 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2752 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2753 let scorer = ln_test_utils::TestScorer::new();
2754 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2755 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2757 // Simple route to 2 via 1
2759 // Disable other paths
2760 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2761 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2762 short_channel_id: 12,
2764 flags: 2, // to disable
2765 cltv_expiry_delta: 0,
2766 htlc_minimum_msat: 0,
2767 htlc_maximum_msat: MAX_VALUE_MSAT,
2769 fee_proportional_millionths: 0,
2770 excess_data: Vec::new()
2772 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2773 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2774 short_channel_id: 3,
2776 flags: 2, // to disable
2777 cltv_expiry_delta: 0,
2778 htlc_minimum_msat: 0,
2779 htlc_maximum_msat: MAX_VALUE_MSAT,
2781 fee_proportional_millionths: 0,
2782 excess_data: Vec::new()
2784 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2785 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2786 short_channel_id: 13,
2788 flags: 2, // to disable
2789 cltv_expiry_delta: 0,
2790 htlc_minimum_msat: 0,
2791 htlc_maximum_msat: MAX_VALUE_MSAT,
2793 fee_proportional_millionths: 0,
2794 excess_data: Vec::new()
2796 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2797 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2798 short_channel_id: 6,
2800 flags: 2, // to disable
2801 cltv_expiry_delta: 0,
2802 htlc_minimum_msat: 0,
2803 htlc_maximum_msat: MAX_VALUE_MSAT,
2805 fee_proportional_millionths: 0,
2806 excess_data: Vec::new()
2808 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2809 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2810 short_channel_id: 7,
2812 flags: 2, // to disable
2813 cltv_expiry_delta: 0,
2814 htlc_minimum_msat: 0,
2815 htlc_maximum_msat: MAX_VALUE_MSAT,
2817 fee_proportional_millionths: 0,
2818 excess_data: Vec::new()
2821 // Check against amount_to_transfer_over_msat.
2822 // Set minimal HTLC of 200_000_000 msat.
2823 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2824 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2825 short_channel_id: 2,
2828 cltv_expiry_delta: 0,
2829 htlc_minimum_msat: 200_000_000,
2830 htlc_maximum_msat: MAX_VALUE_MSAT,
2832 fee_proportional_millionths: 0,
2833 excess_data: Vec::new()
2836 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2838 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2839 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2840 short_channel_id: 4,
2843 cltv_expiry_delta: 0,
2844 htlc_minimum_msat: 0,
2845 htlc_maximum_msat: 199_999_999,
2847 fee_proportional_millionths: 0,
2848 excess_data: Vec::new()
2851 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2852 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 199_999_999, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2853 assert_eq!(err, "Failed to find a path to the given destination");
2854 } else { panic!(); }
2856 // Lift the restriction on the first hop.
2857 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2858 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2859 short_channel_id: 2,
2862 cltv_expiry_delta: 0,
2863 htlc_minimum_msat: 0,
2864 htlc_maximum_msat: MAX_VALUE_MSAT,
2866 fee_proportional_millionths: 0,
2867 excess_data: Vec::new()
2870 // A payment above the minimum should pass
2871 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 199_999_999, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2872 assert_eq!(route.paths[0].hops.len(), 2);
2876 fn htlc_minimum_overpay_test() {
2877 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2878 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2879 let config = UserConfig::default();
2880 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
2881 let scorer = ln_test_utils::TestScorer::new();
2882 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2883 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2885 // A route to node#2 via two paths.
2886 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2887 // Thus, they can't send 60 without overpaying.
2888 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2889 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2890 short_channel_id: 2,
2893 cltv_expiry_delta: 0,
2894 htlc_minimum_msat: 35_000,
2895 htlc_maximum_msat: 40_000,
2897 fee_proportional_millionths: 0,
2898 excess_data: Vec::new()
2900 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2901 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2902 short_channel_id: 12,
2905 cltv_expiry_delta: 0,
2906 htlc_minimum_msat: 35_000,
2907 htlc_maximum_msat: 40_000,
2909 fee_proportional_millionths: 0,
2910 excess_data: Vec::new()
2914 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2915 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2916 short_channel_id: 13,
2919 cltv_expiry_delta: 0,
2920 htlc_minimum_msat: 0,
2921 htlc_maximum_msat: MAX_VALUE_MSAT,
2923 fee_proportional_millionths: 0,
2924 excess_data: Vec::new()
2926 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2927 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2928 short_channel_id: 4,
2931 cltv_expiry_delta: 0,
2932 htlc_minimum_msat: 0,
2933 htlc_maximum_msat: MAX_VALUE_MSAT,
2935 fee_proportional_millionths: 0,
2936 excess_data: Vec::new()
2939 // Disable other paths
2940 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2941 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2942 short_channel_id: 1,
2944 flags: 2, // to disable
2945 cltv_expiry_delta: 0,
2946 htlc_minimum_msat: 0,
2947 htlc_maximum_msat: MAX_VALUE_MSAT,
2949 fee_proportional_millionths: 0,
2950 excess_data: Vec::new()
2953 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2954 // Overpay fees to hit htlc_minimum_msat.
2955 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
2956 // TODO: this could be better balanced to overpay 10k and not 15k.
2957 assert_eq!(overpaid_fees, 15_000);
2959 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2960 // while taking even more fee to match htlc_minimum_msat.
2961 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2962 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2963 short_channel_id: 12,
2966 cltv_expiry_delta: 0,
2967 htlc_minimum_msat: 65_000,
2968 htlc_maximum_msat: 80_000,
2970 fee_proportional_millionths: 0,
2971 excess_data: Vec::new()
2973 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2974 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2975 short_channel_id: 2,
2978 cltv_expiry_delta: 0,
2979 htlc_minimum_msat: 0,
2980 htlc_maximum_msat: MAX_VALUE_MSAT,
2982 fee_proportional_millionths: 0,
2983 excess_data: Vec::new()
2985 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2986 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2987 short_channel_id: 4,
2990 cltv_expiry_delta: 0,
2991 htlc_minimum_msat: 0,
2992 htlc_maximum_msat: MAX_VALUE_MSAT,
2994 fee_proportional_millionths: 100_000,
2995 excess_data: Vec::new()
2998 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2999 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3000 assert_eq!(route.paths.len(), 1);
3001 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3002 let fees = route.paths[0].hops[0].fee_msat;
3003 assert_eq!(fees, 5_000);
3005 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3006 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3007 // the other channel.
3008 assert_eq!(route.paths.len(), 1);
3009 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3010 let fees = route.paths[0].hops[0].fee_msat;
3011 assert_eq!(fees, 5_000);
3015 fn disable_channels_test() {
3016 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3017 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3018 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3019 let scorer = ln_test_utils::TestScorer::new();
3020 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3021 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3023 // // Disable channels 4 and 12 by flags=2
3024 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3025 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3026 short_channel_id: 4,
3028 flags: 2, // to disable
3029 cltv_expiry_delta: 0,
3030 htlc_minimum_msat: 0,
3031 htlc_maximum_msat: MAX_VALUE_MSAT,
3033 fee_proportional_millionths: 0,
3034 excess_data: Vec::new()
3036 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3037 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3038 short_channel_id: 12,
3040 flags: 2, // to disable
3041 cltv_expiry_delta: 0,
3042 htlc_minimum_msat: 0,
3043 htlc_maximum_msat: MAX_VALUE_MSAT,
3045 fee_proportional_millionths: 0,
3046 excess_data: Vec::new()
3049 // If all the channels require some features we don't understand, route should fail
3050 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3051 assert_eq!(err, "Failed to find a path to the given destination");
3052 } else { panic!(); }
3054 // If we specify a channel to node7, that overrides our local channel view and that gets used
3055 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3056 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3057 assert_eq!(route.paths[0].hops.len(), 2);
3059 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3060 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3061 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3062 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3063 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3064 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3066 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3067 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3068 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3069 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3070 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3071 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3075 fn disable_node_test() {
3076 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3077 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3078 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3079 let scorer = ln_test_utils::TestScorer::new();
3080 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3081 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3083 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3084 let mut unknown_features = NodeFeatures::empty();
3085 unknown_features.set_unknown_feature_required();
3086 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3087 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3088 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3090 // If all nodes require some features we don't understand, route should fail
3091 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3092 assert_eq!(err, "Failed to find a path to the given destination");
3093 } else { panic!(); }
3095 // If we specify a channel to node7, that overrides our local channel view and that gets used
3096 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3097 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3098 assert_eq!(route.paths[0].hops.len(), 2);
3100 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3101 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3102 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3103 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3104 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3105 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3107 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3108 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3109 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3110 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3111 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3112 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3114 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3115 // naively) assume that the user checked the feature bits on the invoice, which override
3116 // the node_announcement.
3120 fn our_chans_test() {
3121 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3122 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3123 let scorer = ln_test_utils::TestScorer::new();
3124 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3125 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3127 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3128 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3129 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3130 assert_eq!(route.paths[0].hops.len(), 3);
3132 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3133 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3134 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3135 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3136 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3137 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3139 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3140 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3141 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3142 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3143 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3144 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3146 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3147 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3148 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3149 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3150 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3151 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3153 // If we specify a channel to node7, that overrides our local channel view and that gets used
3154 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3155 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3156 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3157 assert_eq!(route.paths[0].hops.len(), 2);
3159 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3160 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3161 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3162 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3163 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3164 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3166 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3167 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3168 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3169 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3170 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3171 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3174 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3175 let zero_fees = RoutingFees {
3177 proportional_millionths: 0,
3179 vec![RouteHint(vec![RouteHintHop {
3180 src_node_id: nodes[3],
3181 short_channel_id: 8,
3183 cltv_expiry_delta: (8 << 4) | 1,
3184 htlc_minimum_msat: None,
3185 htlc_maximum_msat: None,
3187 ]), RouteHint(vec![RouteHintHop {
3188 src_node_id: nodes[4],
3189 short_channel_id: 9,
3192 proportional_millionths: 0,
3194 cltv_expiry_delta: (9 << 4) | 1,
3195 htlc_minimum_msat: None,
3196 htlc_maximum_msat: None,
3197 }]), RouteHint(vec![RouteHintHop {
3198 src_node_id: nodes[5],
3199 short_channel_id: 10,
3201 cltv_expiry_delta: (10 << 4) | 1,
3202 htlc_minimum_msat: None,
3203 htlc_maximum_msat: None,
3207 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3208 let zero_fees = RoutingFees {
3210 proportional_millionths: 0,
3212 vec![RouteHint(vec![RouteHintHop {
3213 src_node_id: nodes[2],
3214 short_channel_id: 5,
3217 proportional_millionths: 0,
3219 cltv_expiry_delta: (5 << 4) | 1,
3220 htlc_minimum_msat: None,
3221 htlc_maximum_msat: None,
3223 src_node_id: nodes[3],
3224 short_channel_id: 8,
3226 cltv_expiry_delta: (8 << 4) | 1,
3227 htlc_minimum_msat: None,
3228 htlc_maximum_msat: None,
3230 ]), RouteHint(vec![RouteHintHop {
3231 src_node_id: nodes[4],
3232 short_channel_id: 9,
3235 proportional_millionths: 0,
3237 cltv_expiry_delta: (9 << 4) | 1,
3238 htlc_minimum_msat: None,
3239 htlc_maximum_msat: None,
3240 }]), RouteHint(vec![RouteHintHop {
3241 src_node_id: nodes[5],
3242 short_channel_id: 10,
3244 cltv_expiry_delta: (10 << 4) | 1,
3245 htlc_minimum_msat: None,
3246 htlc_maximum_msat: None,
3251 fn partial_route_hint_test() {
3252 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3253 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3254 let scorer = ln_test_utils::TestScorer::new();
3255 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3256 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3258 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3259 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3260 // RouteHint may be partially used by the algo to build the best path.
3262 // First check that last hop can't have its source as the payee.
3263 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3264 src_node_id: nodes[6],
3265 short_channel_id: 8,
3268 proportional_millionths: 0,
3270 cltv_expiry_delta: (8 << 4) | 1,
3271 htlc_minimum_msat: None,
3272 htlc_maximum_msat: None,
3275 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3276 invalid_last_hops.push(invalid_last_hop);
3278 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(invalid_last_hops).unwrap();
3279 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3280 assert_eq!(err, "Route hint cannot have the payee as the source.");
3281 } else { panic!(); }
3284 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3285 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3286 assert_eq!(route.paths[0].hops.len(), 5);
3288 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3289 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3290 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3291 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3292 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3293 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3295 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3296 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3297 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3298 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3299 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3300 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3302 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3303 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3304 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3305 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3306 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3307 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3309 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3310 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3311 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3312 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3313 // If we have a peer in the node map, we'll use their features here since we don't have
3314 // a way of figuring out their features from the invoice:
3315 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3316 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3318 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3319 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3320 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3321 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3322 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3323 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3326 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3327 let zero_fees = RoutingFees {
3329 proportional_millionths: 0,
3331 vec![RouteHint(vec![RouteHintHop {
3332 src_node_id: nodes[3],
3333 short_channel_id: 8,
3335 cltv_expiry_delta: (8 << 4) | 1,
3336 htlc_minimum_msat: None,
3337 htlc_maximum_msat: None,
3338 }]), RouteHint(vec![
3340 ]), RouteHint(vec![RouteHintHop {
3341 src_node_id: nodes[5],
3342 short_channel_id: 10,
3344 cltv_expiry_delta: (10 << 4) | 1,
3345 htlc_minimum_msat: None,
3346 htlc_maximum_msat: None,
3351 fn ignores_empty_last_hops_test() {
3352 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3353 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3354 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3355 let scorer = ln_test_utils::TestScorer::new();
3356 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3357 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3359 // Test handling of an empty RouteHint passed in Invoice.
3361 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3362 assert_eq!(route.paths[0].hops.len(), 5);
3364 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3365 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3366 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3367 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3368 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3369 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3371 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3372 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3373 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3374 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3375 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3376 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3378 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3379 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3380 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3381 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3382 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3383 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3385 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3386 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3387 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3388 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3389 // If we have a peer in the node map, we'll use their features here since we don't have
3390 // a way of figuring out their features from the invoice:
3391 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3392 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3394 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3395 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3396 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3397 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3398 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3399 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3402 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3404 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3405 let zero_fees = RoutingFees {
3407 proportional_millionths: 0,
3409 vec![RouteHint(vec![RouteHintHop {
3410 src_node_id: hint_hops[0],
3411 short_channel_id: 0xff00,
3414 proportional_millionths: 0,
3416 cltv_expiry_delta: (5 << 4) | 1,
3417 htlc_minimum_msat: None,
3418 htlc_maximum_msat: None,
3420 src_node_id: hint_hops[1],
3421 short_channel_id: 0xff01,
3423 cltv_expiry_delta: (8 << 4) | 1,
3424 htlc_minimum_msat: None,
3425 htlc_maximum_msat: None,
3430 fn multi_hint_last_hops_test() {
3431 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3432 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3433 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3434 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3435 let scorer = ln_test_utils::TestScorer::new();
3436 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3437 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3438 // Test through channels 2, 3, 0xff00, 0xff01.
3439 // Test shows that multiple hop hints are considered.
3441 // Disabling channels 6 & 7 by flags=2
3442 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3443 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3444 short_channel_id: 6,
3446 flags: 2, // to disable
3447 cltv_expiry_delta: 0,
3448 htlc_minimum_msat: 0,
3449 htlc_maximum_msat: MAX_VALUE_MSAT,
3451 fee_proportional_millionths: 0,
3452 excess_data: Vec::new()
3454 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3455 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3456 short_channel_id: 7,
3458 flags: 2, // to disable
3459 cltv_expiry_delta: 0,
3460 htlc_minimum_msat: 0,
3461 htlc_maximum_msat: MAX_VALUE_MSAT,
3463 fee_proportional_millionths: 0,
3464 excess_data: Vec::new()
3467 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3468 assert_eq!(route.paths[0].hops.len(), 4);
3470 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3471 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3472 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3473 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3474 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3475 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3477 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3478 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3479 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3480 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3481 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3482 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3484 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3485 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3486 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3487 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3488 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3489 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3491 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3492 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3493 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3494 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3495 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3496 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3500 fn private_multi_hint_last_hops_test() {
3501 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3502 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3504 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3505 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3507 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3508 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3509 let scorer = ln_test_utils::TestScorer::new();
3510 // Test through channels 2, 3, 0xff00, 0xff01.
3511 // Test shows that multiple hop hints are considered.
3513 // Disabling channels 6 & 7 by flags=2
3514 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3515 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3516 short_channel_id: 6,
3518 flags: 2, // to disable
3519 cltv_expiry_delta: 0,
3520 htlc_minimum_msat: 0,
3521 htlc_maximum_msat: MAX_VALUE_MSAT,
3523 fee_proportional_millionths: 0,
3524 excess_data: Vec::new()
3526 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3527 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3528 short_channel_id: 7,
3530 flags: 2, // to disable
3531 cltv_expiry_delta: 0,
3532 htlc_minimum_msat: 0,
3533 htlc_maximum_msat: MAX_VALUE_MSAT,
3535 fee_proportional_millionths: 0,
3536 excess_data: Vec::new()
3539 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &[42u8; 32]).unwrap();
3540 assert_eq!(route.paths[0].hops.len(), 4);
3542 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3543 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3544 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3545 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3546 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3547 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3549 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3550 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3551 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3552 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3553 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3554 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3556 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3557 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3558 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3559 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3560 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3561 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3563 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3564 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3565 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3566 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3567 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3568 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3571 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3572 let zero_fees = RoutingFees {
3574 proportional_millionths: 0,
3576 vec![RouteHint(vec![RouteHintHop {
3577 src_node_id: nodes[4],
3578 short_channel_id: 11,
3580 cltv_expiry_delta: (11 << 4) | 1,
3581 htlc_minimum_msat: None,
3582 htlc_maximum_msat: None,
3584 src_node_id: nodes[3],
3585 short_channel_id: 8,
3587 cltv_expiry_delta: (8 << 4) | 1,
3588 htlc_minimum_msat: None,
3589 htlc_maximum_msat: None,
3590 }]), RouteHint(vec![RouteHintHop {
3591 src_node_id: nodes[4],
3592 short_channel_id: 9,
3595 proportional_millionths: 0,
3597 cltv_expiry_delta: (9 << 4) | 1,
3598 htlc_minimum_msat: None,
3599 htlc_maximum_msat: None,
3600 }]), RouteHint(vec![RouteHintHop {
3601 src_node_id: nodes[5],
3602 short_channel_id: 10,
3604 cltv_expiry_delta: (10 << 4) | 1,
3605 htlc_minimum_msat: None,
3606 htlc_maximum_msat: None,
3611 fn last_hops_with_public_channel_test() {
3612 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3613 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3614 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
3615 let scorer = ln_test_utils::TestScorer::new();
3616 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3617 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3618 // This test shows that public routes can be present in the invoice
3619 // which would be handled in the same manner.
3621 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3622 assert_eq!(route.paths[0].hops.len(), 5);
3624 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3625 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3626 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3627 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3628 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3629 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3631 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3632 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3633 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3634 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3635 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3636 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3638 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3639 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3640 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3641 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3642 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3643 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3645 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3646 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3647 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3648 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3649 // If we have a peer in the node map, we'll use their features here since we don't have
3650 // a way of figuring out their features from the invoice:
3651 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3652 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3654 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3655 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3656 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3657 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3658 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3659 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3663 fn our_chans_last_hop_connect_test() {
3664 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3665 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3666 let scorer = ln_test_utils::TestScorer::new();
3667 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3668 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3670 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3671 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3672 let mut last_hops = last_hops(&nodes);
3673 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3674 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3675 assert_eq!(route.paths[0].hops.len(), 2);
3677 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3678 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3679 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3680 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3681 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3682 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3684 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3685 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3686 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3687 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3688 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3689 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3691 last_hops[0].0[0].fees.base_msat = 1000;
3693 // Revert to via 6 as the fee on 8 goes up
3694 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops).unwrap();
3695 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3696 assert_eq!(route.paths[0].hops.len(), 4);
3698 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3699 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3700 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
3701 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3702 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3703 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3705 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3706 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3707 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3708 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
3709 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3710 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3712 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
3713 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3714 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3715 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3716 // If we have a peer in the node map, we'll use their features here since we don't have
3717 // a way of figuring out their features from the invoice:
3718 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3719 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3721 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3722 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3723 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3724 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3725 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3726 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3728 // ...but still use 8 for larger payments as 6 has a variable feerate
3729 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3730 assert_eq!(route.paths[0].hops.len(), 5);
3732 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3733 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3734 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3735 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3736 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3737 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3739 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3740 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3741 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3742 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3743 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3744 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3746 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3747 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3748 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3749 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3750 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3751 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3753 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3754 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3755 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
3756 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3757 // If we have a peer in the node map, we'll use their features here since we don't have
3758 // a way of figuring out their features from the invoice:
3759 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3760 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3762 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3763 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3764 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
3765 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3766 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3767 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3770 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> {
3771 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3772 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3773 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3775 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3776 let last_hops = RouteHint(vec![RouteHintHop {
3777 src_node_id: middle_node_id,
3778 short_channel_id: 8,
3781 proportional_millionths: last_hop_fee_prop,
3783 cltv_expiry_delta: (8 << 4) | 1,
3784 htlc_minimum_msat: None,
3785 htlc_maximum_msat: last_hop_htlc_max,
3787 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
3788 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3789 let scorer = ln_test_utils::TestScorer::new();
3790 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3791 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3792 let logger = ln_test_utils::TestLogger::new();
3793 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3794 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3795 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, &logger, &scorer, &(), &random_seed_bytes);
3800 fn unannounced_path_test() {
3801 // We should be able to send a payment to a destination without any help of a routing graph
3802 // if we have a channel with a common counterparty that appears in the first and last hop
3804 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3806 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3807 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3808 assert_eq!(route.paths[0].hops.len(), 2);
3810 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
3811 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3812 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
3813 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3814 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
3815 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3817 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
3818 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3819 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
3820 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3821 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3822 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3826 fn overflow_unannounced_path_test_liquidity_underflow() {
3827 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3828 // the last-hop had a fee which overflowed a u64, we'd panic.
3829 // This was due to us adding the first-hop from us unconditionally, causing us to think
3830 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3831 // In this test, we previously hit a subtraction underflow due to having less available
3832 // liquidity at the last hop than 0.
3833 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());
3837 fn overflow_unannounced_path_test_feerate_overflow() {
3838 // This tests for the same case as above, except instead of hitting a subtraction
3839 // underflow, we hit a case where the fee charged at a hop overflowed.
3840 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());
3844 fn available_amount_while_routing_test() {
3845 // Tests whether we choose the correct available channel amount while routing.
3847 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3848 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3849 let scorer = ln_test_utils::TestScorer::new();
3850 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3851 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3852 let config = UserConfig::default();
3853 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3855 // We will use a simple single-path route from
3856 // our node to node2 via node0: channels {1, 3}.
3858 // First disable all other paths.
3859 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3860 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3861 short_channel_id: 2,
3864 cltv_expiry_delta: 0,
3865 htlc_minimum_msat: 0,
3866 htlc_maximum_msat: 100_000,
3868 fee_proportional_millionths: 0,
3869 excess_data: Vec::new()
3871 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3872 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3873 short_channel_id: 12,
3876 cltv_expiry_delta: 0,
3877 htlc_minimum_msat: 0,
3878 htlc_maximum_msat: 100_000,
3880 fee_proportional_millionths: 0,
3881 excess_data: Vec::new()
3884 // Make the first channel (#1) very permissive,
3885 // and we will be testing all limits on the second channel.
3886 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3887 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3888 short_channel_id: 1,
3891 cltv_expiry_delta: 0,
3892 htlc_minimum_msat: 0,
3893 htlc_maximum_msat: 1_000_000_000,
3895 fee_proportional_millionths: 0,
3896 excess_data: Vec::new()
3899 // First, let's see if routing works if we have absolutely no idea about the available amount.
3900 // In this case, it should be set to 250_000 sats.
3901 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3902 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3903 short_channel_id: 3,
3906 cltv_expiry_delta: 0,
3907 htlc_minimum_msat: 0,
3908 htlc_maximum_msat: 250_000_000,
3910 fee_proportional_millionths: 0,
3911 excess_data: Vec::new()
3915 // Attempt to route more than available results in a failure.
3916 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3917 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3918 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3919 } else { panic!(); }
3923 // Now, attempt to route an exact amount we have should be fine.
3924 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000_000, Arc::clone(&logger), &scorer, &(),&random_seed_bytes).unwrap();
3925 assert_eq!(route.paths.len(), 1);
3926 let path = route.paths.last().unwrap();
3927 assert_eq!(path.hops.len(), 2);
3928 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3929 assert_eq!(path.final_value_msat(), 250_000_000);
3932 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3933 // Disable channel #1 and use another first hop.
3934 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3935 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3936 short_channel_id: 1,
3939 cltv_expiry_delta: 0,
3940 htlc_minimum_msat: 0,
3941 htlc_maximum_msat: 1_000_000_000,
3943 fee_proportional_millionths: 0,
3944 excess_data: Vec::new()
3947 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3948 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3951 // Attempt to route more than available results in a failure.
3952 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3953 &our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3954 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3955 } else { panic!(); }
3959 // Now, attempt to route an exact amount we have should be fine.
3960 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3961 assert_eq!(route.paths.len(), 1);
3962 let path = route.paths.last().unwrap();
3963 assert_eq!(path.hops.len(), 2);
3964 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3965 assert_eq!(path.final_value_msat(), 200_000_000);
3968 // Enable channel #1 back.
3969 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3970 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3971 short_channel_id: 1,
3974 cltv_expiry_delta: 0,
3975 htlc_minimum_msat: 0,
3976 htlc_maximum_msat: 1_000_000_000,
3978 fee_proportional_millionths: 0,
3979 excess_data: Vec::new()
3983 // Now let's see if routing works if we know only htlc_maximum_msat.
3984 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3985 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3986 short_channel_id: 3,
3989 cltv_expiry_delta: 0,
3990 htlc_minimum_msat: 0,
3991 htlc_maximum_msat: 15_000,
3993 fee_proportional_millionths: 0,
3994 excess_data: Vec::new()
3998 // Attempt to route more than available results in a failure.
3999 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4000 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4001 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4002 } else { panic!(); }
4006 // Now, attempt to route an exact amount we have should be fine.
4007 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4008 assert_eq!(route.paths.len(), 1);
4009 let path = route.paths.last().unwrap();
4010 assert_eq!(path.hops.len(), 2);
4011 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4012 assert_eq!(path.final_value_msat(), 15_000);
4015 // Now let's see if routing works if we know only capacity from the UTXO.
4017 // We can't change UTXO capacity on the fly, so we'll disable
4018 // the existing channel and add another one with the capacity we need.
4019 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4020 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4021 short_channel_id: 3,
4024 cltv_expiry_delta: 0,
4025 htlc_minimum_msat: 0,
4026 htlc_maximum_msat: MAX_VALUE_MSAT,
4028 fee_proportional_millionths: 0,
4029 excess_data: Vec::new()
4032 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4033 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4034 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4035 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4036 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4038 *chain_monitor.utxo_ret.lock().unwrap() =
4039 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4040 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4042 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4043 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4044 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4045 short_channel_id: 333,
4048 cltv_expiry_delta: (3 << 4) | 1,
4049 htlc_minimum_msat: 0,
4050 htlc_maximum_msat: 15_000,
4052 fee_proportional_millionths: 0,
4053 excess_data: Vec::new()
4055 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4056 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4057 short_channel_id: 333,
4060 cltv_expiry_delta: (3 << 4) | 2,
4061 htlc_minimum_msat: 0,
4062 htlc_maximum_msat: 15_000,
4064 fee_proportional_millionths: 0,
4065 excess_data: Vec::new()
4069 // Attempt to route more than available results in a failure.
4070 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4071 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4072 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4073 } else { panic!(); }
4077 // Now, attempt to route an exact amount we have should be fine.
4078 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4079 assert_eq!(route.paths.len(), 1);
4080 let path = route.paths.last().unwrap();
4081 assert_eq!(path.hops.len(), 2);
4082 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4083 assert_eq!(path.final_value_msat(), 15_000);
4086 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4087 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4088 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4089 short_channel_id: 333,
4092 cltv_expiry_delta: 0,
4093 htlc_minimum_msat: 0,
4094 htlc_maximum_msat: 10_000,
4096 fee_proportional_millionths: 0,
4097 excess_data: Vec::new()
4101 // Attempt to route more than available results in a failure.
4102 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4103 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4104 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4105 } else { panic!(); }
4109 // Now, attempt to route an exact amount we have should be fine.
4110 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4111 assert_eq!(route.paths.len(), 1);
4112 let path = route.paths.last().unwrap();
4113 assert_eq!(path.hops.len(), 2);
4114 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4115 assert_eq!(path.final_value_msat(), 10_000);
4120 fn available_liquidity_last_hop_test() {
4121 // Check that available liquidity properly limits the path even when only
4122 // one of the latter hops is limited.
4123 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4124 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4125 let scorer = ln_test_utils::TestScorer::new();
4126 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4127 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4128 let config = UserConfig::default();
4129 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4131 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4132 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4133 // Total capacity: 50 sats.
4135 // Disable other potential paths.
4136 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4137 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4138 short_channel_id: 2,
4141 cltv_expiry_delta: 0,
4142 htlc_minimum_msat: 0,
4143 htlc_maximum_msat: 100_000,
4145 fee_proportional_millionths: 0,
4146 excess_data: Vec::new()
4148 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4149 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4150 short_channel_id: 7,
4153 cltv_expiry_delta: 0,
4154 htlc_minimum_msat: 0,
4155 htlc_maximum_msat: 100_000,
4157 fee_proportional_millionths: 0,
4158 excess_data: Vec::new()
4163 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4164 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4165 short_channel_id: 12,
4168 cltv_expiry_delta: 0,
4169 htlc_minimum_msat: 0,
4170 htlc_maximum_msat: 100_000,
4172 fee_proportional_millionths: 0,
4173 excess_data: Vec::new()
4175 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4176 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4177 short_channel_id: 13,
4180 cltv_expiry_delta: 0,
4181 htlc_minimum_msat: 0,
4182 htlc_maximum_msat: 100_000,
4184 fee_proportional_millionths: 0,
4185 excess_data: Vec::new()
4188 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4189 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4190 short_channel_id: 6,
4193 cltv_expiry_delta: 0,
4194 htlc_minimum_msat: 0,
4195 htlc_maximum_msat: 50_000,
4197 fee_proportional_millionths: 0,
4198 excess_data: Vec::new()
4200 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4201 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4202 short_channel_id: 11,
4205 cltv_expiry_delta: 0,
4206 htlc_minimum_msat: 0,
4207 htlc_maximum_msat: 100_000,
4209 fee_proportional_millionths: 0,
4210 excess_data: Vec::new()
4213 // Attempt to route more than available results in a failure.
4214 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4215 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4216 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4217 } else { panic!(); }
4221 // Now, attempt to route 49 sats (just a bit below the capacity).
4222 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4223 assert_eq!(route.paths.len(), 1);
4224 let mut total_amount_paid_msat = 0;
4225 for path in &route.paths {
4226 assert_eq!(path.hops.len(), 4);
4227 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4228 total_amount_paid_msat += path.final_value_msat();
4230 assert_eq!(total_amount_paid_msat, 49_000);
4234 // Attempt to route an exact amount is also fine
4235 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4236 assert_eq!(route.paths.len(), 1);
4237 let mut total_amount_paid_msat = 0;
4238 for path in &route.paths {
4239 assert_eq!(path.hops.len(), 4);
4240 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4241 total_amount_paid_msat += path.final_value_msat();
4243 assert_eq!(total_amount_paid_msat, 50_000);
4248 fn ignore_fee_first_hop_test() {
4249 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4250 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4251 let scorer = ln_test_utils::TestScorer::new();
4252 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4253 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4254 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4256 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4257 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4258 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4259 short_channel_id: 1,
4262 cltv_expiry_delta: 0,
4263 htlc_minimum_msat: 0,
4264 htlc_maximum_msat: 100_000,
4265 fee_base_msat: 1_000_000,
4266 fee_proportional_millionths: 0,
4267 excess_data: Vec::new()
4269 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4270 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4271 short_channel_id: 3,
4274 cltv_expiry_delta: 0,
4275 htlc_minimum_msat: 0,
4276 htlc_maximum_msat: 50_000,
4278 fee_proportional_millionths: 0,
4279 excess_data: Vec::new()
4283 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4284 assert_eq!(route.paths.len(), 1);
4285 let mut total_amount_paid_msat = 0;
4286 for path in &route.paths {
4287 assert_eq!(path.hops.len(), 2);
4288 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4289 total_amount_paid_msat += path.final_value_msat();
4291 assert_eq!(total_amount_paid_msat, 50_000);
4296 fn simple_mpp_route_test() {
4297 let (secp_ctx, _, _, _, _) = build_graph();
4298 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4299 let config = UserConfig::default();
4300 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4301 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4302 do_simple_mpp_route_test(clear_payment_params);
4304 // MPP to a 1-hop blinded path for nodes[2]
4305 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
4306 let blinded_path = BlindedPath {
4307 introduction_node_id: nodes[2],
4308 blinding_point: ln_test_utils::pubkey(42),
4309 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4311 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4313 fee_proportional_millionths: 0,
4314 htlc_minimum_msat: 0,
4315 htlc_maximum_msat: 0,
4316 cltv_expiry_delta: 0,
4317 features: BlindedHopFeatures::empty(),
4319 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4320 .with_bolt12_features(bolt12_features.clone()).unwrap();
4321 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4323 // MPP to 3 2-hop blinded paths
4324 let mut blinded_path_node_0 = blinded_path.clone();
4325 blinded_path_node_0.introduction_node_id = nodes[0];
4326 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4327 let mut node_0_payinfo = blinded_payinfo.clone();
4328 node_0_payinfo.htlc_maximum_msat = 50_000;
4330 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4331 blinded_path_node_7.introduction_node_id = nodes[7];
4332 let mut node_7_payinfo = blinded_payinfo.clone();
4333 node_7_payinfo.htlc_maximum_msat = 60_000;
4335 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4336 blinded_path_node_1.introduction_node_id = nodes[1];
4337 let mut node_1_payinfo = blinded_payinfo.clone();
4338 node_1_payinfo.htlc_maximum_msat = 180_000;
4340 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4342 (node_0_payinfo, blinded_path_node_0),
4343 (node_7_payinfo, blinded_path_node_7),
4344 (node_1_payinfo, blinded_path_node_1)
4346 .with_bolt12_features(bolt12_features).unwrap();
4347 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4351 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4352 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4353 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4354 let scorer = ln_test_utils::TestScorer::new();
4355 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4356 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4358 // We need a route consisting of 3 paths:
4359 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4360 // To achieve this, the amount being transferred should be around
4361 // the total capacity of these 3 paths.
4363 // First, we set limits on these (previously unlimited) channels.
4364 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4366 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4367 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4368 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4369 short_channel_id: 1,
4372 cltv_expiry_delta: 0,
4373 htlc_minimum_msat: 0,
4374 htlc_maximum_msat: 100_000,
4376 fee_proportional_millionths: 0,
4377 excess_data: Vec::new()
4379 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4380 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4381 short_channel_id: 3,
4384 cltv_expiry_delta: 0,
4385 htlc_minimum_msat: 0,
4386 htlc_maximum_msat: 50_000,
4388 fee_proportional_millionths: 0,
4389 excess_data: Vec::new()
4392 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4393 // (total limit 60).
4394 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4395 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4396 short_channel_id: 12,
4399 cltv_expiry_delta: 0,
4400 htlc_minimum_msat: 0,
4401 htlc_maximum_msat: 60_000,
4403 fee_proportional_millionths: 0,
4404 excess_data: Vec::new()
4406 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4407 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4408 short_channel_id: 13,
4411 cltv_expiry_delta: 0,
4412 htlc_minimum_msat: 0,
4413 htlc_maximum_msat: 60_000,
4415 fee_proportional_millionths: 0,
4416 excess_data: Vec::new()
4419 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4420 // (total capacity 180 sats).
4421 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4422 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4423 short_channel_id: 2,
4426 cltv_expiry_delta: 0,
4427 htlc_minimum_msat: 0,
4428 htlc_maximum_msat: 200_000,
4430 fee_proportional_millionths: 0,
4431 excess_data: Vec::new()
4433 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4434 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4435 short_channel_id: 4,
4438 cltv_expiry_delta: 0,
4439 htlc_minimum_msat: 0,
4440 htlc_maximum_msat: 180_000,
4442 fee_proportional_millionths: 0,
4443 excess_data: Vec::new()
4447 // Attempt to route more than available results in a failure.
4448 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4449 &our_id, &payment_params, &network_graph.read_only(), None, 300_000,
4450 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4451 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4452 } else { panic!(); }
4456 // Attempt to route while setting max_path_count to 0 results in a failure.
4457 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4458 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4459 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100,
4460 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4461 assert_eq!(err, "Can't find a route with no paths allowed.");
4462 } else { panic!(); }
4466 // Attempt to route while setting max_path_count to 3 results in a failure.
4467 // This is the case because the minimal_value_contribution_msat would require each path
4468 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4469 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4470 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4471 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000,
4472 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4473 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4474 } else { panic!(); }
4478 // Now, attempt to route 250 sats (just a bit below the capacity).
4479 // Our algorithm should provide us with these 3 paths.
4480 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4481 250_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4482 assert_eq!(route.paths.len(), 3);
4483 let mut total_amount_paid_msat = 0;
4484 for path in &route.paths {
4485 if let Some(bt) = &path.blinded_tail {
4486 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4488 assert_eq!(path.hops.len(), 2);
4489 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4491 total_amount_paid_msat += path.final_value_msat();
4493 assert_eq!(total_amount_paid_msat, 250_000);
4497 // Attempt to route an exact amount is also fine
4498 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4499 290_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4500 assert_eq!(route.paths.len(), 3);
4501 let mut total_amount_paid_msat = 0;
4502 for path in &route.paths {
4503 if payment_params.payee.blinded_route_hints().len() != 0 {
4504 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
4505 if let Some(bt) = &path.blinded_tail {
4506 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4507 if bt.hops.len() > 1 {
4508 assert_eq!(path.hops.last().unwrap().pubkey,
4509 payment_params.payee.blinded_route_hints().iter()
4510 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
4511 .map(|(_, p)| p.introduction_node_id).unwrap());
4513 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4516 assert_eq!(path.hops.len(), 2);
4517 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4519 total_amount_paid_msat += path.final_value_msat();
4521 assert_eq!(total_amount_paid_msat, 290_000);
4526 fn long_mpp_route_test() {
4527 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4528 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4529 let scorer = ln_test_utils::TestScorer::new();
4530 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4531 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4532 let config = UserConfig::default();
4533 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4535 // We need a route consisting of 3 paths:
4536 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4537 // Note that these paths overlap (channels 5, 12, 13).
4538 // We will route 300 sats.
4539 // Each path will have 100 sats capacity, those channels which
4540 // are used twice will have 200 sats capacity.
4542 // Disable other potential paths.
4543 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4544 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4545 short_channel_id: 2,
4548 cltv_expiry_delta: 0,
4549 htlc_minimum_msat: 0,
4550 htlc_maximum_msat: 100_000,
4552 fee_proportional_millionths: 0,
4553 excess_data: Vec::new()
4555 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4556 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4557 short_channel_id: 7,
4560 cltv_expiry_delta: 0,
4561 htlc_minimum_msat: 0,
4562 htlc_maximum_msat: 100_000,
4564 fee_proportional_millionths: 0,
4565 excess_data: Vec::new()
4568 // Path via {node0, node2} is channels {1, 3, 5}.
4569 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4570 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4571 short_channel_id: 1,
4574 cltv_expiry_delta: 0,
4575 htlc_minimum_msat: 0,
4576 htlc_maximum_msat: 100_000,
4578 fee_proportional_millionths: 0,
4579 excess_data: Vec::new()
4581 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4582 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4583 short_channel_id: 3,
4586 cltv_expiry_delta: 0,
4587 htlc_minimum_msat: 0,
4588 htlc_maximum_msat: 100_000,
4590 fee_proportional_millionths: 0,
4591 excess_data: Vec::new()
4594 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4595 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4596 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4597 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4598 short_channel_id: 5,
4601 cltv_expiry_delta: 0,
4602 htlc_minimum_msat: 0,
4603 htlc_maximum_msat: 200_000,
4605 fee_proportional_millionths: 0,
4606 excess_data: Vec::new()
4609 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4610 // Add 100 sats to the capacities of {12, 13}, because these channels
4611 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4612 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4613 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4614 short_channel_id: 12,
4617 cltv_expiry_delta: 0,
4618 htlc_minimum_msat: 0,
4619 htlc_maximum_msat: 200_000,
4621 fee_proportional_millionths: 0,
4622 excess_data: Vec::new()
4624 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4625 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4626 short_channel_id: 13,
4629 cltv_expiry_delta: 0,
4630 htlc_minimum_msat: 0,
4631 htlc_maximum_msat: 200_000,
4633 fee_proportional_millionths: 0,
4634 excess_data: Vec::new()
4637 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4638 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4639 short_channel_id: 6,
4642 cltv_expiry_delta: 0,
4643 htlc_minimum_msat: 0,
4644 htlc_maximum_msat: 100_000,
4646 fee_proportional_millionths: 0,
4647 excess_data: Vec::new()
4649 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4650 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4651 short_channel_id: 11,
4654 cltv_expiry_delta: 0,
4655 htlc_minimum_msat: 0,
4656 htlc_maximum_msat: 100_000,
4658 fee_proportional_millionths: 0,
4659 excess_data: Vec::new()
4662 // Path via {node7, node2} is channels {12, 13, 5}.
4663 // We already limited them to 200 sats (they are used twice for 100 sats).
4664 // Nothing to do here.
4667 // Attempt to route more than available results in a failure.
4668 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4669 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4670 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4671 } else { panic!(); }
4675 // Now, attempt to route 300 sats (exact amount we can route).
4676 // Our algorithm should provide us with these 3 paths, 100 sats each.
4677 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4678 assert_eq!(route.paths.len(), 3);
4680 let mut total_amount_paid_msat = 0;
4681 for path in &route.paths {
4682 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4683 total_amount_paid_msat += path.final_value_msat();
4685 assert_eq!(total_amount_paid_msat, 300_000);
4691 fn mpp_cheaper_route_test() {
4692 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4693 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4694 let scorer = ln_test_utils::TestScorer::new();
4695 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4696 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4697 let config = UserConfig::default();
4698 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4700 // This test checks that if we have two cheaper paths and one more expensive path,
4701 // so that liquidity-wise any 2 of 3 combination is sufficient,
4702 // two cheaper paths will be taken.
4703 // These paths have equal available liquidity.
4705 // We need a combination of 3 paths:
4706 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4707 // Note that these paths overlap (channels 5, 12, 13).
4708 // Each path will have 100 sats capacity, those channels which
4709 // are used twice will have 200 sats capacity.
4711 // Disable other potential paths.
4712 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4713 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4714 short_channel_id: 2,
4717 cltv_expiry_delta: 0,
4718 htlc_minimum_msat: 0,
4719 htlc_maximum_msat: 100_000,
4721 fee_proportional_millionths: 0,
4722 excess_data: Vec::new()
4724 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4725 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4726 short_channel_id: 7,
4729 cltv_expiry_delta: 0,
4730 htlc_minimum_msat: 0,
4731 htlc_maximum_msat: 100_000,
4733 fee_proportional_millionths: 0,
4734 excess_data: Vec::new()
4737 // Path via {node0, node2} is channels {1, 3, 5}.
4738 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4739 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4740 short_channel_id: 1,
4743 cltv_expiry_delta: 0,
4744 htlc_minimum_msat: 0,
4745 htlc_maximum_msat: 100_000,
4747 fee_proportional_millionths: 0,
4748 excess_data: Vec::new()
4750 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4751 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4752 short_channel_id: 3,
4755 cltv_expiry_delta: 0,
4756 htlc_minimum_msat: 0,
4757 htlc_maximum_msat: 100_000,
4759 fee_proportional_millionths: 0,
4760 excess_data: Vec::new()
4763 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4764 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4765 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4766 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4767 short_channel_id: 5,
4770 cltv_expiry_delta: 0,
4771 htlc_minimum_msat: 0,
4772 htlc_maximum_msat: 200_000,
4774 fee_proportional_millionths: 0,
4775 excess_data: Vec::new()
4778 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4779 // Add 100 sats to the capacities of {12, 13}, because these channels
4780 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4781 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4782 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4783 short_channel_id: 12,
4786 cltv_expiry_delta: 0,
4787 htlc_minimum_msat: 0,
4788 htlc_maximum_msat: 200_000,
4790 fee_proportional_millionths: 0,
4791 excess_data: Vec::new()
4793 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4794 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4795 short_channel_id: 13,
4798 cltv_expiry_delta: 0,
4799 htlc_minimum_msat: 0,
4800 htlc_maximum_msat: 200_000,
4802 fee_proportional_millionths: 0,
4803 excess_data: Vec::new()
4806 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4807 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4808 short_channel_id: 6,
4811 cltv_expiry_delta: 0,
4812 htlc_minimum_msat: 0,
4813 htlc_maximum_msat: 100_000,
4814 fee_base_msat: 1_000,
4815 fee_proportional_millionths: 0,
4816 excess_data: Vec::new()
4818 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4819 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4820 short_channel_id: 11,
4823 cltv_expiry_delta: 0,
4824 htlc_minimum_msat: 0,
4825 htlc_maximum_msat: 100_000,
4827 fee_proportional_millionths: 0,
4828 excess_data: Vec::new()
4831 // Path via {node7, node2} is channels {12, 13, 5}.
4832 // We already limited them to 200 sats (they are used twice for 100 sats).
4833 // Nothing to do here.
4836 // Now, attempt to route 180 sats.
4837 // Our algorithm should provide us with these 2 paths.
4838 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4839 assert_eq!(route.paths.len(), 2);
4841 let mut total_value_transferred_msat = 0;
4842 let mut total_paid_msat = 0;
4843 for path in &route.paths {
4844 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4845 total_value_transferred_msat += path.final_value_msat();
4846 for hop in &path.hops {
4847 total_paid_msat += hop.fee_msat;
4850 // If we paid fee, this would be higher.
4851 assert_eq!(total_value_transferred_msat, 180_000);
4852 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4853 assert_eq!(total_fees_paid, 0);
4858 fn fees_on_mpp_route_test() {
4859 // This test makes sure that MPP algorithm properly takes into account
4860 // fees charged on the channels, by making the fees impactful:
4861 // if the fee is not properly accounted for, the behavior is different.
4862 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4863 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4864 let scorer = ln_test_utils::TestScorer::new();
4865 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4866 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4867 let config = UserConfig::default();
4868 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4870 // We need a route consisting of 2 paths:
4871 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4872 // We will route 200 sats, Each path will have 100 sats capacity.
4874 // This test is not particularly stable: e.g.,
4875 // there's a way to route via {node0, node2, node4}.
4876 // It works while pathfinding is deterministic, but can be broken otherwise.
4877 // It's fine to ignore this concern for now.
4879 // Disable other potential paths.
4880 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4881 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4882 short_channel_id: 2,
4885 cltv_expiry_delta: 0,
4886 htlc_minimum_msat: 0,
4887 htlc_maximum_msat: 100_000,
4889 fee_proportional_millionths: 0,
4890 excess_data: Vec::new()
4893 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4894 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4895 short_channel_id: 7,
4898 cltv_expiry_delta: 0,
4899 htlc_minimum_msat: 0,
4900 htlc_maximum_msat: 100_000,
4902 fee_proportional_millionths: 0,
4903 excess_data: Vec::new()
4906 // Path via {node0, node2} is channels {1, 3, 5}.
4907 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4908 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4909 short_channel_id: 1,
4912 cltv_expiry_delta: 0,
4913 htlc_minimum_msat: 0,
4914 htlc_maximum_msat: 100_000,
4916 fee_proportional_millionths: 0,
4917 excess_data: Vec::new()
4919 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4920 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4921 short_channel_id: 3,
4924 cltv_expiry_delta: 0,
4925 htlc_minimum_msat: 0,
4926 htlc_maximum_msat: 100_000,
4928 fee_proportional_millionths: 0,
4929 excess_data: Vec::new()
4932 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4933 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4934 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4935 short_channel_id: 5,
4938 cltv_expiry_delta: 0,
4939 htlc_minimum_msat: 0,
4940 htlc_maximum_msat: 100_000,
4942 fee_proportional_millionths: 0,
4943 excess_data: Vec::new()
4946 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4947 // All channels should be 100 sats capacity. But for the fee experiment,
4948 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4949 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4950 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4951 // so no matter how large are other channels,
4952 // the whole path will be limited by 100 sats with just these 2 conditions:
4953 // - channel 12 capacity is 250 sats
4954 // - fee for channel 6 is 150 sats
4955 // Let's test this by enforcing these 2 conditions and removing other limits.
4956 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4957 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4958 short_channel_id: 12,
4961 cltv_expiry_delta: 0,
4962 htlc_minimum_msat: 0,
4963 htlc_maximum_msat: 250_000,
4965 fee_proportional_millionths: 0,
4966 excess_data: Vec::new()
4968 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4969 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4970 short_channel_id: 13,
4973 cltv_expiry_delta: 0,
4974 htlc_minimum_msat: 0,
4975 htlc_maximum_msat: MAX_VALUE_MSAT,
4977 fee_proportional_millionths: 0,
4978 excess_data: Vec::new()
4981 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4982 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4983 short_channel_id: 6,
4986 cltv_expiry_delta: 0,
4987 htlc_minimum_msat: 0,
4988 htlc_maximum_msat: MAX_VALUE_MSAT,
4989 fee_base_msat: 150_000,
4990 fee_proportional_millionths: 0,
4991 excess_data: Vec::new()
4993 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4994 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4995 short_channel_id: 11,
4998 cltv_expiry_delta: 0,
4999 htlc_minimum_msat: 0,
5000 htlc_maximum_msat: MAX_VALUE_MSAT,
5002 fee_proportional_millionths: 0,
5003 excess_data: Vec::new()
5007 // Attempt to route more than available results in a failure.
5008 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5009 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5010 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5011 } else { panic!(); }
5015 // Now, attempt to route 200 sats (exact amount we can route).
5016 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5017 assert_eq!(route.paths.len(), 2);
5019 let mut total_amount_paid_msat = 0;
5020 for path in &route.paths {
5021 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5022 total_amount_paid_msat += path.final_value_msat();
5024 assert_eq!(total_amount_paid_msat, 200_000);
5025 assert_eq!(route.get_total_fees(), 150_000);
5030 fn mpp_with_last_hops() {
5031 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5032 // via a single last-hop route hint, we'd fail to route if we first collected routes
5033 // totaling close but not quite enough to fund the full payment.
5035 // This was because we considered last-hop hints to have exactly the sought payment amount
5036 // instead of the amount we were trying to collect, needlessly limiting our path searching
5037 // at the very first hop.
5039 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5040 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5041 // to only have the remaining to-collect amount in available liquidity.
5043 // This bug appeared in production in some specific channel configurations.
5044 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5045 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5046 let scorer = ln_test_utils::TestScorer::new();
5047 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5048 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5049 let config = UserConfig::default();
5050 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5051 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5052 src_node_id: nodes[2],
5053 short_channel_id: 42,
5054 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5055 cltv_expiry_delta: 42,
5056 htlc_minimum_msat: None,
5057 htlc_maximum_msat: None,
5058 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5060 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5061 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5062 // would first use the no-fee route and then fail to find a path along the second route as
5063 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5064 // under 5% of our payment amount.
5065 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5066 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5067 short_channel_id: 1,
5070 cltv_expiry_delta: (5 << 4) | 5,
5071 htlc_minimum_msat: 0,
5072 htlc_maximum_msat: 99_000,
5073 fee_base_msat: u32::max_value(),
5074 fee_proportional_millionths: u32::max_value(),
5075 excess_data: Vec::new()
5077 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5078 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5079 short_channel_id: 2,
5082 cltv_expiry_delta: (5 << 4) | 3,
5083 htlc_minimum_msat: 0,
5084 htlc_maximum_msat: 99_000,
5085 fee_base_msat: u32::max_value(),
5086 fee_proportional_millionths: u32::max_value(),
5087 excess_data: Vec::new()
5089 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5090 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5091 short_channel_id: 4,
5094 cltv_expiry_delta: (4 << 4) | 1,
5095 htlc_minimum_msat: 0,
5096 htlc_maximum_msat: MAX_VALUE_MSAT,
5098 fee_proportional_millionths: 0,
5099 excess_data: Vec::new()
5101 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5102 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5103 short_channel_id: 13,
5105 flags: 0|2, // Channel disabled
5106 cltv_expiry_delta: (13 << 4) | 1,
5107 htlc_minimum_msat: 0,
5108 htlc_maximum_msat: MAX_VALUE_MSAT,
5110 fee_proportional_millionths: 2000000,
5111 excess_data: Vec::new()
5114 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5116 let mut route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5117 assert_eq!(route.paths.len(), 2);
5118 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5119 // Paths are manually ordered ordered by SCID, so:
5120 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5121 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5122 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5123 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5124 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5125 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5126 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5127 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5128 assert_eq!(route.get_total_fees(), 1);
5129 assert_eq!(route.get_total_amount(), 100_000);
5133 fn drop_lowest_channel_mpp_route_test() {
5134 // This test checks that low-capacity channel is dropped when after
5135 // path finding we realize that we found more capacity than we need.
5136 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5137 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5138 let scorer = ln_test_utils::TestScorer::new();
5139 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5140 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5141 let config = UserConfig::default();
5142 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5143 .with_max_channel_saturation_power_of_half(0);
5145 // We need a route consisting of 3 paths:
5146 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5148 // The first and the second paths should be sufficient, but the third should be
5149 // cheaper, so that we select it but drop later.
5151 // First, we set limits on these (previously unlimited) channels.
5152 // Their aggregate capacity will be 50 + 60 + 20 = 130 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: genesis_block(Network::Testnet).header.block_hash(),
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: genesis_block(Network::Testnet).header.block_hash(),
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 (total limit 60);
5181 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5182 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5183 short_channel_id: 12,
5186 cltv_expiry_delta: 0,
5187 htlc_minimum_msat: 0,
5188 htlc_maximum_msat: 60_000,
5190 fee_proportional_millionths: 0,
5191 excess_data: Vec::new()
5193 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5194 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5195 short_channel_id: 13,
5198 cltv_expiry_delta: 0,
5199 htlc_minimum_msat: 0,
5200 htlc_maximum_msat: 60_000,
5202 fee_proportional_millionths: 0,
5203 excess_data: Vec::new()
5206 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5207 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5208 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5209 short_channel_id: 2,
5212 cltv_expiry_delta: 0,
5213 htlc_minimum_msat: 0,
5214 htlc_maximum_msat: 20_000,
5216 fee_proportional_millionths: 0,
5217 excess_data: Vec::new()
5219 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5220 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5221 short_channel_id: 4,
5224 cltv_expiry_delta: 0,
5225 htlc_minimum_msat: 0,
5226 htlc_maximum_msat: 20_000,
5228 fee_proportional_millionths: 0,
5229 excess_data: Vec::new()
5233 // Attempt to route more than available results in a failure.
5234 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5235 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5236 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5237 } else { panic!(); }
5241 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5242 // Our algorithm should provide us with these 3 paths.
5243 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5244 assert_eq!(route.paths.len(), 3);
5245 let mut total_amount_paid_msat = 0;
5246 for path in &route.paths {
5247 assert_eq!(path.hops.len(), 2);
5248 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5249 total_amount_paid_msat += path.final_value_msat();
5251 assert_eq!(total_amount_paid_msat, 125_000);
5255 // Attempt to route without the last small cheap channel
5256 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5257 assert_eq!(route.paths.len(), 2);
5258 let mut total_amount_paid_msat = 0;
5259 for path in &route.paths {
5260 assert_eq!(path.hops.len(), 2);
5261 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5262 total_amount_paid_msat += path.final_value_msat();
5264 assert_eq!(total_amount_paid_msat, 90_000);
5269 fn min_criteria_consistency() {
5270 // Test that we don't use an inconsistent metric between updating and walking nodes during
5271 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5272 // was updated with a different criterion from the heap sorting, resulting in loops in
5273 // calculated paths. We test for that specific case here.
5275 // We construct a network that looks like this:
5277 // node2 -1(3)2- node3
5281 // node1 -1(5)2- node4 -1(1)2- node6
5287 // We create a loop on the side of our real path - our destination is node 6, with a
5288 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5289 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5290 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5291 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5292 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5293 // "previous hop" being set to node 3, creating a loop in the path.
5294 let secp_ctx = Secp256k1::new();
5295 let logger = Arc::new(ln_test_utils::TestLogger::new());
5296 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5297 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5298 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5299 let scorer = ln_test_utils::TestScorer::new();
5300 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5301 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5302 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5304 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5305 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5306 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5307 short_channel_id: 6,
5310 cltv_expiry_delta: (6 << 4) | 0,
5311 htlc_minimum_msat: 0,
5312 htlc_maximum_msat: MAX_VALUE_MSAT,
5314 fee_proportional_millionths: 0,
5315 excess_data: Vec::new()
5317 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5319 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5320 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5321 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5322 short_channel_id: 5,
5325 cltv_expiry_delta: (5 << 4) | 0,
5326 htlc_minimum_msat: 0,
5327 htlc_maximum_msat: MAX_VALUE_MSAT,
5329 fee_proportional_millionths: 0,
5330 excess_data: Vec::new()
5332 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5334 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5335 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5336 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5337 short_channel_id: 4,
5340 cltv_expiry_delta: (4 << 4) | 0,
5341 htlc_minimum_msat: 0,
5342 htlc_maximum_msat: MAX_VALUE_MSAT,
5344 fee_proportional_millionths: 0,
5345 excess_data: Vec::new()
5347 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5349 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5350 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5351 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5352 short_channel_id: 3,
5355 cltv_expiry_delta: (3 << 4) | 0,
5356 htlc_minimum_msat: 0,
5357 htlc_maximum_msat: MAX_VALUE_MSAT,
5359 fee_proportional_millionths: 0,
5360 excess_data: Vec::new()
5362 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5364 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5365 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5366 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5367 short_channel_id: 2,
5370 cltv_expiry_delta: (2 << 4) | 0,
5371 htlc_minimum_msat: 0,
5372 htlc_maximum_msat: MAX_VALUE_MSAT,
5374 fee_proportional_millionths: 0,
5375 excess_data: Vec::new()
5378 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5379 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5380 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5381 short_channel_id: 1,
5384 cltv_expiry_delta: (1 << 4) | 0,
5385 htlc_minimum_msat: 100,
5386 htlc_maximum_msat: MAX_VALUE_MSAT,
5388 fee_proportional_millionths: 0,
5389 excess_data: Vec::new()
5391 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5394 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5395 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5396 assert_eq!(route.paths.len(), 1);
5397 assert_eq!(route.paths[0].hops.len(), 3);
5399 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5400 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5401 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5402 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5403 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5404 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5406 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5407 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5408 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5409 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5410 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5411 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5413 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5414 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5415 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5416 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5417 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5418 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5424 fn exact_fee_liquidity_limit() {
5425 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5426 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5427 // we calculated fees on a higher value, resulting in us ignoring such paths.
5428 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5429 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5430 let scorer = ln_test_utils::TestScorer::new();
5431 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5432 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5433 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5435 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5437 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5438 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5439 short_channel_id: 2,
5442 cltv_expiry_delta: 0,
5443 htlc_minimum_msat: 0,
5444 htlc_maximum_msat: 85_000,
5446 fee_proportional_millionths: 0,
5447 excess_data: Vec::new()
5450 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5451 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5452 short_channel_id: 12,
5455 cltv_expiry_delta: (4 << 4) | 1,
5456 htlc_minimum_msat: 0,
5457 htlc_maximum_msat: 270_000,
5459 fee_proportional_millionths: 1000000,
5460 excess_data: Vec::new()
5464 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5465 // 200% fee charged channel 13 in the 1-to-2 direction.
5466 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5467 assert_eq!(route.paths.len(), 1);
5468 assert_eq!(route.paths[0].hops.len(), 2);
5470 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5471 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5472 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5473 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5474 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5475 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5477 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5478 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5479 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5480 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5481 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5482 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5487 fn htlc_max_reduction_below_min() {
5488 // Test that if, while walking the graph, we reduce the value being sent to meet an
5489 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5490 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5491 // resulting in us thinking there is no possible path, even if other paths exist.
5492 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5493 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5494 let scorer = ln_test_utils::TestScorer::new();
5495 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5496 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5497 let config = UserConfig::default();
5498 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5500 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5501 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5502 // then try to send 90_000.
5503 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5504 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5505 short_channel_id: 2,
5508 cltv_expiry_delta: 0,
5509 htlc_minimum_msat: 0,
5510 htlc_maximum_msat: 80_000,
5512 fee_proportional_millionths: 0,
5513 excess_data: Vec::new()
5515 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5516 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5517 short_channel_id: 4,
5520 cltv_expiry_delta: (4 << 4) | 1,
5521 htlc_minimum_msat: 90_000,
5522 htlc_maximum_msat: MAX_VALUE_MSAT,
5524 fee_proportional_millionths: 0,
5525 excess_data: Vec::new()
5529 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5530 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5531 // expensive) channels 12-13 path.
5532 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5533 assert_eq!(route.paths.len(), 1);
5534 assert_eq!(route.paths[0].hops.len(), 2);
5536 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5537 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5538 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5539 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5540 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5541 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5543 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5544 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5545 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5546 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5547 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5548 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5553 fn multiple_direct_first_hops() {
5554 // Previously we'd only ever considered one first hop path per counterparty.
5555 // However, as we don't restrict users to one channel per peer, we really need to support
5556 // looking at all first hop paths.
5557 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5558 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5559 // route over multiple channels with the same first hop.
5560 let secp_ctx = Secp256k1::new();
5561 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5562 let logger = Arc::new(ln_test_utils::TestLogger::new());
5563 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5564 let scorer = ln_test_utils::TestScorer::new();
5565 let config = UserConfig::default();
5566 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5567 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5568 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5571 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5572 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5573 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5574 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5575 assert_eq!(route.paths.len(), 1);
5576 assert_eq!(route.paths[0].hops.len(), 1);
5578 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5579 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5580 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5583 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5584 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5585 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5586 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5587 assert_eq!(route.paths.len(), 2);
5588 assert_eq!(route.paths[0].hops.len(), 1);
5589 assert_eq!(route.paths[1].hops.len(), 1);
5591 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5592 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5594 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5595 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5597 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5598 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5602 // If we have a bunch of outbound channels to the same node, where most are not
5603 // sufficient to pay the full payment, but one is, we should default to just using the
5604 // one single channel that has sufficient balance, avoiding MPP.
5606 // If we have several options above the 3xpayment value threshold, we should pick the
5607 // smallest of them, avoiding further fragmenting our available outbound balance to
5609 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5610 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5611 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5612 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5613 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5614 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5615 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5616 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5617 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5618 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5619 assert_eq!(route.paths.len(), 1);
5620 assert_eq!(route.paths[0].hops.len(), 1);
5622 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5623 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5624 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5629 fn prefers_shorter_route_with_higher_fees() {
5630 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5631 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5632 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5634 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5635 let scorer = ln_test_utils::TestScorer::new();
5636 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5637 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5638 let route = get_route(
5639 &our_id, &payment_params, &network_graph.read_only(), None, 100,
5640 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5642 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5644 assert_eq!(route.get_total_fees(), 100);
5645 assert_eq!(route.get_total_amount(), 100);
5646 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5648 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5649 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5650 let scorer = FixedPenaltyScorer::with_penalty(100);
5651 let route = get_route(
5652 &our_id, &payment_params, &network_graph.read_only(), None, 100,
5653 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5655 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5657 assert_eq!(route.get_total_fees(), 300);
5658 assert_eq!(route.get_total_amount(), 100);
5659 assert_eq!(path, vec![2, 4, 7, 10]);
5662 struct BadChannelScorer {
5663 short_channel_id: u64,
5667 impl Writeable for BadChannelScorer {
5668 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5670 impl Score for BadChannelScorer {
5671 type ScoreParams = ();
5672 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5673 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5676 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5677 fn payment_path_successful(&mut self, _path: &Path) {}
5678 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5679 fn probe_successful(&mut self, _path: &Path) {}
5682 struct BadNodeScorer {
5687 impl Writeable for BadNodeScorer {
5688 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5691 impl Score for BadNodeScorer {
5692 type ScoreParams = ();
5693 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5694 if *target == self.node_id { u64::max_value() } else { 0 }
5697 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5698 fn payment_path_successful(&mut self, _path: &Path) {}
5699 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5700 fn probe_successful(&mut self, _path: &Path) {}
5704 fn avoids_routing_through_bad_channels_and_nodes() {
5705 let (secp_ctx, network, _, _, logger) = build_graph();
5706 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5707 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5708 let network_graph = network.read_only();
5710 // A path to nodes[6] exists when no penalties are applied to any channel.
5711 let scorer = ln_test_utils::TestScorer::new();
5712 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5713 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5714 let route = get_route(
5715 &our_id, &payment_params, &network_graph, None, 100,
5716 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5718 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5720 assert_eq!(route.get_total_fees(), 100);
5721 assert_eq!(route.get_total_amount(), 100);
5722 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5724 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5725 let scorer = BadChannelScorer { short_channel_id: 6 };
5726 let route = get_route(
5727 &our_id, &payment_params, &network_graph, None, 100,
5728 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5730 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5732 assert_eq!(route.get_total_fees(), 300);
5733 assert_eq!(route.get_total_amount(), 100);
5734 assert_eq!(path, vec![2, 4, 7, 10]);
5736 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5737 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5739 &our_id, &payment_params, &network_graph, None, 100,
5740 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5742 Err(LightningError { err, .. } ) => {
5743 assert_eq!(err, "Failed to find a path to the given destination");
5745 Ok(_) => panic!("Expected error"),
5750 fn total_fees_single_path() {
5752 paths: vec![Path { hops: vec![
5754 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5755 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5756 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5759 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5760 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5761 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5764 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5765 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5766 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5768 ], blinded_tail: None }],
5769 payment_params: None,
5772 assert_eq!(route.get_total_fees(), 250);
5773 assert_eq!(route.get_total_amount(), 225);
5777 fn total_fees_multi_path() {
5779 paths: vec![Path { hops: vec![
5781 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5782 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5783 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5786 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5787 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5788 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5790 ], blinded_tail: None }, Path { hops: vec![
5792 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5793 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5794 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5797 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5798 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5799 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5801 ], blinded_tail: None }],
5802 payment_params: None,
5805 assert_eq!(route.get_total_fees(), 200);
5806 assert_eq!(route.get_total_amount(), 300);
5810 fn total_empty_route_no_panic() {
5811 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5812 // would both panic if the route was completely empty. We test to ensure they return 0
5813 // here, even though its somewhat nonsensical as a route.
5814 let route = Route { paths: Vec::new(), payment_params: None };
5816 assert_eq!(route.get_total_fees(), 0);
5817 assert_eq!(route.get_total_amount(), 0);
5821 fn limits_total_cltv_delta() {
5822 let (secp_ctx, network, _, _, logger) = build_graph();
5823 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5824 let network_graph = network.read_only();
5826 let scorer = ln_test_utils::TestScorer::new();
5828 // Make sure that generally there is at least one route available
5829 let feasible_max_total_cltv_delta = 1008;
5830 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5831 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5832 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5833 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5834 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5835 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5836 assert_ne!(path.len(), 0);
5838 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5839 let fail_max_total_cltv_delta = 23;
5840 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5841 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5842 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5844 Err(LightningError { err, .. } ) => {
5845 assert_eq!(err, "Failed to find a path to the given destination");
5847 Ok(_) => panic!("Expected error"),
5852 fn avoids_recently_failed_paths() {
5853 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5854 // randomly inserting channels into it until we can't find a route anymore.
5855 let (secp_ctx, network, _, _, logger) = build_graph();
5856 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5857 let network_graph = network.read_only();
5859 let scorer = ln_test_utils::TestScorer::new();
5860 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5861 .with_max_path_count(1);
5862 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5863 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5865 // We should be able to find a route initially, and then after we fail a few random
5866 // channels eventually we won't be able to any longer.
5867 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).is_ok());
5869 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5870 for chan in route.paths[0].hops.iter() {
5871 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5873 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5874 % route.paths[0].hops.len();
5875 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
5881 fn limits_path_length() {
5882 let (secp_ctx, network, _, _, logger) = build_line_graph();
5883 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5884 let network_graph = network.read_only();
5886 let scorer = ln_test_utils::TestScorer::new();
5887 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5888 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5890 // First check we can actually create a long route on this graph.
5891 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
5892 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100,
5893 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5894 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5895 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5897 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5898 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
5899 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100,
5900 Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5902 Err(LightningError { err, .. } ) => {
5903 assert_eq!(err, "Failed to find a path to the given destination");
5905 Ok(_) => panic!("Expected error"),
5910 fn adds_and_limits_cltv_offset() {
5911 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5912 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5914 let scorer = ln_test_utils::TestScorer::new();
5916 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5917 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5918 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5919 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5920 assert_eq!(route.paths.len(), 1);
5922 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5924 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5925 let mut route_default = route.clone();
5926 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5927 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5928 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5929 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5930 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5932 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5933 let mut route_limited = route.clone();
5934 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5935 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5936 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5937 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5938 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5942 fn adds_plausible_cltv_offset() {
5943 let (secp_ctx, network, _, _, logger) = build_graph();
5944 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5945 let network_graph = network.read_only();
5946 let network_nodes = network_graph.nodes();
5947 let network_channels = network_graph.channels();
5948 let scorer = ln_test_utils::TestScorer::new();
5949 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5950 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5951 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5953 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100,
5954 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5955 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5957 let mut path_plausibility = vec![];
5959 for p in route.paths {
5960 // 1. Select random observation point
5961 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5962 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5964 prng.process_in_place(&mut random_bytes);
5965 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
5966 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
5968 // 2. Calculate what CLTV expiry delta we would observe there
5969 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5971 // 3. Starting from the observation point, find candidate paths
5972 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5973 candidates.push_back((observation_point, vec![]));
5975 let mut found_plausible_candidate = false;
5977 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5978 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5979 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5980 found_plausible_candidate = true;
5981 break 'candidate_loop;
5985 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5986 for channel_id in &cur_node.channels {
5987 if let Some(channel_info) = network_channels.get(&channel_id) {
5988 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5989 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
5990 if cur_path_cltv_deltas.iter().sum::<u32>()
5991 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5992 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5993 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5994 candidates.push_back((*next_id, new_path_cltv_deltas));
6002 path_plausibility.push(found_plausible_candidate);
6004 assert!(path_plausibility.iter().all(|x| *x));
6008 fn builds_correct_path_from_hops() {
6009 let (secp_ctx, network, _, _, logger) = build_graph();
6010 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6011 let network_graph = network.read_only();
6013 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6014 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6016 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6017 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6018 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
6019 &network_graph, 100, Arc::clone(&logger), &random_seed_bytes).unwrap();
6020 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6021 assert_eq!(hops.len(), route.paths[0].hops.len());
6022 for (idx, hop_pubkey) in hops.iter().enumerate() {
6023 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6028 fn avoids_saturating_channels() {
6029 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6030 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6031 let decay_params = ProbabilisticScoringDecayParameters::default();
6032 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6034 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6035 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6036 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6037 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6038 short_channel_id: 4,
6041 cltv_expiry_delta: (4 << 4) | 1,
6042 htlc_minimum_msat: 0,
6043 htlc_maximum_msat: 250_000_000,
6045 fee_proportional_millionths: 0,
6046 excess_data: Vec::new()
6048 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6049 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6050 short_channel_id: 13,
6053 cltv_expiry_delta: (13 << 4) | 1,
6054 htlc_minimum_msat: 0,
6055 htlc_maximum_msat: 250_000_000,
6057 fee_proportional_millionths: 0,
6058 excess_data: Vec::new()
6061 let config = UserConfig::default();
6062 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6063 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6064 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6065 // 100,000 sats is less than the available liquidity on each channel, set above.
6066 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000_000, Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6067 assert_eq!(route.paths.len(), 2);
6068 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6069 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6072 #[cfg(not(feature = "no-std"))]
6073 pub(super) fn random_init_seed() -> u64 {
6074 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6075 use core::hash::{BuildHasher, Hasher};
6076 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6077 println!("Using seed of {}", seed);
6082 #[cfg(not(feature = "no-std"))]
6083 fn generate_routes() {
6084 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6086 let logger = ln_test_utils::TestLogger::new();
6087 let graph = match super::bench_utils::read_network_graph(&logger) {
6095 let params = ProbabilisticScoringFeeParameters::default();
6096 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6097 let features = super::InvoiceFeatures::empty();
6099 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6103 #[cfg(not(feature = "no-std"))]
6104 fn generate_routes_mpp() {
6105 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6107 let logger = ln_test_utils::TestLogger::new();
6108 let graph = match super::bench_utils::read_network_graph(&logger) {
6116 let params = ProbabilisticScoringFeeParameters::default();
6117 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6118 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6120 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6124 #[cfg(not(feature = "no-std"))]
6125 fn generate_large_mpp_routes() {
6126 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6128 let logger = ln_test_utils::TestLogger::new();
6129 let graph = match super::bench_utils::read_network_graph(&logger) {
6137 let params = ProbabilisticScoringFeeParameters::default();
6138 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6139 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6141 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6145 fn honors_manual_penalties() {
6146 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6147 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6149 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6150 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6152 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6153 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6155 // First check set manual penalties are returned by the scorer.
6156 let usage = ChannelUsage {
6158 inflight_htlc_msat: 0,
6159 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6161 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6162 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6163 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
6165 // Then check we can get a normal route
6166 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6167 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6168 assert!(route.is_ok());
6170 // Then check that we can't get a route if we ban an intermediate node.
6171 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6172 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6173 assert!(route.is_err());
6175 // Finally make sure we can route again, when we remove the ban.
6176 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6177 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6178 assert!(route.is_ok());
6182 fn abide_by_route_hint_max_htlc() {
6183 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6184 // params in the final route.
6185 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6186 let netgraph = network_graph.read_only();
6187 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6188 let scorer = ln_test_utils::TestScorer::new();
6189 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6190 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6191 let config = UserConfig::default();
6193 let max_htlc_msat = 50_000;
6194 let route_hint_1 = RouteHint(vec![RouteHintHop {
6195 src_node_id: nodes[2],
6196 short_channel_id: 42,
6199 proportional_millionths: 0,
6201 cltv_expiry_delta: 10,
6202 htlc_minimum_msat: None,
6203 htlc_maximum_msat: Some(max_htlc_msat),
6205 let dest_node_id = ln_test_utils::pubkey(42);
6206 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6207 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6208 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6210 // Make sure we'll error if our route hints don't have enough liquidity according to their
6211 // htlc_maximum_msat.
6212 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6213 &payment_params, &netgraph, None, max_htlc_msat + 1, Arc::clone(&logger), &scorer, &(),
6216 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6217 } else { panic!(); }
6219 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6220 let mut route_hint_2 = route_hint_1.clone();
6221 route_hint_2.0[0].short_channel_id = 43;
6222 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6223 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6224 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6225 let route = get_route(&our_id, &payment_params, &netgraph, None, max_htlc_msat + 1,
6226 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6227 assert_eq!(route.paths.len(), 2);
6228 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6229 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6233 fn direct_channel_to_hints_with_max_htlc() {
6234 // Check that if we have a first hop channel peer that's connected to multiple provided route
6235 // hints, that we properly split the payment between the route hints if needed.
6236 let logger = Arc::new(ln_test_utils::TestLogger::new());
6237 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6238 let scorer = ln_test_utils::TestScorer::new();
6239 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6240 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6241 let config = UserConfig::default();
6243 let our_node_id = ln_test_utils::pubkey(42);
6244 let intermed_node_id = ln_test_utils::pubkey(43);
6245 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6247 let amt_msat = 900_000;
6248 let max_htlc_msat = 500_000;
6249 let route_hint_1 = RouteHint(vec![RouteHintHop {
6250 src_node_id: intermed_node_id,
6251 short_channel_id: 44,
6254 proportional_millionths: 0,
6256 cltv_expiry_delta: 10,
6257 htlc_minimum_msat: None,
6258 htlc_maximum_msat: Some(max_htlc_msat),
6260 src_node_id: intermed_node_id,
6261 short_channel_id: 45,
6264 proportional_millionths: 0,
6266 cltv_expiry_delta: 10,
6267 htlc_minimum_msat: None,
6268 // Check that later route hint max htlcs don't override earlier ones
6269 htlc_maximum_msat: Some(max_htlc_msat - 50),
6271 let mut route_hint_2 = route_hint_1.clone();
6272 route_hint_2.0[0].short_channel_id = 46;
6273 route_hint_2.0[1].short_channel_id = 47;
6274 let dest_node_id = ln_test_utils::pubkey(44);
6275 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6276 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6277 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6279 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6280 Some(&first_hop.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6281 &random_seed_bytes).unwrap();
6282 assert_eq!(route.paths.len(), 2);
6283 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6284 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6285 assert_eq!(route.get_total_amount(), amt_msat);
6287 // Re-run but with two first hop channels connected to the same route hint peers that must be
6289 let first_hops = vec![
6290 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6291 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6293 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6294 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6295 &random_seed_bytes).unwrap();
6296 assert_eq!(route.paths.len(), 2);
6297 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6298 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6299 assert_eq!(route.get_total_amount(), amt_msat);
6301 // Make sure this works for blinded route hints.
6302 let blinded_path = BlindedPath {
6303 introduction_node_id: intermed_node_id,
6304 blinding_point: ln_test_utils::pubkey(42),
6306 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6307 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6310 let blinded_payinfo = BlindedPayInfo {
6312 fee_proportional_millionths: 0,
6313 htlc_minimum_msat: 1,
6314 htlc_maximum_msat: max_htlc_msat,
6315 cltv_expiry_delta: 10,
6316 features: BlindedHopFeatures::empty(),
6318 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6319 let payment_params = PaymentParameters::blinded(vec![
6320 (blinded_payinfo.clone(), blinded_path.clone()),
6321 (blinded_payinfo.clone(), blinded_path.clone())])
6322 .with_bolt12_features(bolt12_features).unwrap();
6323 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6324 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6325 &random_seed_bytes).unwrap();
6326 assert_eq!(route.paths.len(), 2);
6327 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6328 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6329 assert_eq!(route.get_total_amount(), amt_msat);
6333 fn blinded_route_ser() {
6334 let blinded_path_1 = BlindedPath {
6335 introduction_node_id: ln_test_utils::pubkey(42),
6336 blinding_point: ln_test_utils::pubkey(43),
6338 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6339 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6342 let blinded_path_2 = BlindedPath {
6343 introduction_node_id: ln_test_utils::pubkey(46),
6344 blinding_point: ln_test_utils::pubkey(47),
6346 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6347 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6350 // (De)serialize a Route with 1 blinded path out of two total paths.
6351 let mut route = Route { paths: vec![Path {
6352 hops: vec![RouteHop {
6353 pubkey: ln_test_utils::pubkey(50),
6354 node_features: NodeFeatures::empty(),
6355 short_channel_id: 42,
6356 channel_features: ChannelFeatures::empty(),
6358 cltv_expiry_delta: 0,
6360 blinded_tail: Some(BlindedTail {
6361 hops: blinded_path_1.blinded_hops,
6362 blinding_point: blinded_path_1.blinding_point,
6363 excess_final_cltv_expiry_delta: 40,
6364 final_value_msat: 100,
6366 hops: vec![RouteHop {
6367 pubkey: ln_test_utils::pubkey(51),
6368 node_features: NodeFeatures::empty(),
6369 short_channel_id: 43,
6370 channel_features: ChannelFeatures::empty(),
6372 cltv_expiry_delta: 0,
6373 }], blinded_tail: None }],
6374 payment_params: None,
6376 let encoded_route = route.encode();
6377 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6378 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6379 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6381 // (De)serialize a Route with two paths, each containing a blinded tail.
6382 route.paths[1].blinded_tail = Some(BlindedTail {
6383 hops: blinded_path_2.blinded_hops,
6384 blinding_point: blinded_path_2.blinding_point,
6385 excess_final_cltv_expiry_delta: 41,
6386 final_value_msat: 101,
6388 let encoded_route = route.encode();
6389 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6390 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6391 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6395 fn blinded_path_inflight_processing() {
6396 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6397 // account for the blinded tail's final amount_msat.
6398 let mut inflight_htlcs = InFlightHtlcs::new();
6399 let blinded_path = BlindedPath {
6400 introduction_node_id: ln_test_utils::pubkey(43),
6401 blinding_point: ln_test_utils::pubkey(48),
6402 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
6405 hops: vec![RouteHop {
6406 pubkey: ln_test_utils::pubkey(42),
6407 node_features: NodeFeatures::empty(),
6408 short_channel_id: 42,
6409 channel_features: ChannelFeatures::empty(),
6411 cltv_expiry_delta: 0,
6414 pubkey: blinded_path.introduction_node_id,
6415 node_features: NodeFeatures::empty(),
6416 short_channel_id: 43,
6417 channel_features: ChannelFeatures::empty(),
6419 cltv_expiry_delta: 0,
6421 blinded_tail: Some(BlindedTail {
6422 hops: blinded_path.blinded_hops,
6423 blinding_point: blinded_path.blinding_point,
6424 excess_final_cltv_expiry_delta: 0,
6425 final_value_msat: 200,
6428 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
6429 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
6430 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
6434 fn blinded_path_cltv_shadow_offset() {
6435 // Make sure we add a shadow offset when sending to blinded paths.
6436 let blinded_path = BlindedPath {
6437 introduction_node_id: ln_test_utils::pubkey(43),
6438 blinding_point: ln_test_utils::pubkey(44),
6440 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
6441 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
6444 let mut route = Route { paths: vec![Path {
6445 hops: vec![RouteHop {
6446 pubkey: ln_test_utils::pubkey(42),
6447 node_features: NodeFeatures::empty(),
6448 short_channel_id: 42,
6449 channel_features: ChannelFeatures::empty(),
6451 cltv_expiry_delta: 0,
6454 pubkey: blinded_path.introduction_node_id,
6455 node_features: NodeFeatures::empty(),
6456 short_channel_id: 43,
6457 channel_features: ChannelFeatures::empty(),
6459 cltv_expiry_delta: 0,
6462 blinded_tail: Some(BlindedTail {
6463 hops: blinded_path.blinded_hops,
6464 blinding_point: blinded_path.blinding_point,
6465 excess_final_cltv_expiry_delta: 0,
6466 final_value_msat: 200,
6468 }], payment_params: None};
6470 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
6471 let (_, network_graph, _, _, _) = build_line_graph();
6472 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
6473 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
6474 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
6478 fn simple_blinded_route_hints() {
6479 do_simple_blinded_route_hints(1);
6480 do_simple_blinded_route_hints(2);
6481 do_simple_blinded_route_hints(3);
6484 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
6485 // Check that we can generate a route to a blinded path with the expected hops.
6486 let (secp_ctx, network, _, _, logger) = build_graph();
6487 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6488 let network_graph = network.read_only();
6490 let scorer = ln_test_utils::TestScorer::new();
6491 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6492 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6494 let mut blinded_path = BlindedPath {
6495 introduction_node_id: nodes[2],
6496 blinding_point: ln_test_utils::pubkey(42),
6497 blinded_hops: Vec::with_capacity(num_blinded_hops),
6499 for i in 0..num_blinded_hops {
6500 blinded_path.blinded_hops.push(
6501 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
6504 let blinded_payinfo = BlindedPayInfo {
6506 fee_proportional_millionths: 500,
6507 htlc_minimum_msat: 1000,
6508 htlc_maximum_msat: 100_000_000,
6509 cltv_expiry_delta: 15,
6510 features: BlindedHopFeatures::empty(),
6513 let final_amt_msat = 1001;
6514 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
6515 let route = get_route(&our_id, &payment_params, &network_graph, None, final_amt_msat , Arc::clone(&logger),
6516 &scorer, &(), &random_seed_bytes).unwrap();
6517 assert_eq!(route.paths.len(), 1);
6518 assert_eq!(route.paths[0].hops.len(), 2);
6520 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
6521 assert_eq!(tail.hops, blinded_path.blinded_hops);
6522 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
6523 assert_eq!(tail.final_value_msat, 1001);
6525 let final_hop = route.paths[0].hops.last().unwrap();
6526 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
6527 if tail.hops.len() > 1 {
6528 assert_eq!(final_hop.fee_msat,
6529 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
6530 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
6532 assert_eq!(final_hop.fee_msat, 0);
6533 assert_eq!(final_hop.cltv_expiry_delta, 0);
6538 fn blinded_path_routing_errors() {
6539 // Check that we can generate a route to a blinded path with the expected hops.
6540 let (secp_ctx, network, _, _, logger) = build_graph();
6541 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6542 let network_graph = network.read_only();
6544 let scorer = ln_test_utils::TestScorer::new();
6545 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6546 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6548 let mut invalid_blinded_path = BlindedPath {
6549 introduction_node_id: nodes[2],
6550 blinding_point: ln_test_utils::pubkey(42),
6552 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
6555 let blinded_payinfo = BlindedPayInfo {
6557 fee_proportional_millionths: 500,
6558 htlc_minimum_msat: 1000,
6559 htlc_maximum_msat: 100_000_000,
6560 cltv_expiry_delta: 15,
6561 features: BlindedHopFeatures::empty(),
6564 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
6565 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
6566 let payment_params = PaymentParameters::blinded(vec![
6567 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
6568 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
6569 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6570 &scorer, &(), &random_seed_bytes)
6572 Err(LightningError { err, .. }) => {
6573 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
6575 _ => panic!("Expected error")
6578 invalid_blinded_path.introduction_node_id = our_id;
6579 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
6580 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6581 &scorer, &(), &random_seed_bytes)
6583 Err(LightningError { err, .. }) => {
6584 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
6586 _ => panic!("Expected error")
6589 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
6590 invalid_blinded_path.blinded_hops.clear();
6591 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
6592 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6593 &scorer, &(), &random_seed_bytes)
6595 Err(LightningError { err, .. }) => {
6596 assert_eq!(err, "0-hop blinded path provided");
6598 _ => panic!("Expected error")
6603 fn matching_intro_node_paths_provided() {
6604 // Check that if multiple blinded paths with the same intro node are provided in payment
6605 // parameters, we'll return the correct paths in the resulting MPP route.
6606 let (secp_ctx, network, _, _, logger) = build_graph();
6607 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6608 let network_graph = network.read_only();
6610 let scorer = ln_test_utils::TestScorer::new();
6611 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6612 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6613 let config = UserConfig::default();
6615 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6616 let blinded_path_1 = BlindedPath {
6617 introduction_node_id: nodes[2],
6618 blinding_point: ln_test_utils::pubkey(42),
6620 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6621 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6624 let blinded_payinfo_1 = BlindedPayInfo {
6626 fee_proportional_millionths: 0,
6627 htlc_minimum_msat: 0,
6628 htlc_maximum_msat: 30_000,
6629 cltv_expiry_delta: 0,
6630 features: BlindedHopFeatures::empty(),
6633 let mut blinded_path_2 = blinded_path_1.clone();
6634 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
6635 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
6636 blinded_payinfo_2.htlc_maximum_msat = 70_000;
6638 let blinded_hints = vec![
6639 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
6640 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
6642 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
6643 .with_bolt12_features(bolt12_features.clone()).unwrap();
6645 let route = get_route(&our_id, &payment_params, &network_graph, None,
6646 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6647 assert_eq!(route.paths.len(), 2);
6648 let mut total_amount_paid_msat = 0;
6649 for path in route.paths.into_iter() {
6650 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6651 if let Some(bt) = &path.blinded_tail {
6652 assert_eq!(bt.blinding_point,
6653 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
6654 .map(|(_, bp)| bp.blinding_point).unwrap());
6655 } else { panic!(); }
6656 total_amount_paid_msat += path.final_value_msat();
6658 assert_eq!(total_amount_paid_msat, 100_000);
6662 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
6663 pub(crate) mod bench_utils {
6667 use bitcoin::hashes::Hash;
6668 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
6670 use crate::chain::transaction::OutPoint;
6671 use crate::sign::{EntropySource, KeysManager};
6672 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
6673 use crate::ln::features::InvoiceFeatures;
6674 use crate::routing::gossip::NetworkGraph;
6675 use crate::util::config::UserConfig;
6676 use crate::util::ser::ReadableArgs;
6677 use crate::util::test_utils::TestLogger;
6679 /// Tries to open a network graph file, or panics with a URL to fetch it.
6680 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
6681 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
6682 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
6683 .or_else(|_| { // Fall back to guessing based on the binary location
6684 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
6685 let mut path = std::env::current_exe().unwrap();
6686 path.pop(); // lightning-...
6688 path.pop(); // debug
6689 path.pop(); // target
6690 path.push("lightning");
6691 path.push("net_graph-2023-01-18.bin");
6694 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
6695 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
6696 let mut path = std::env::current_exe().unwrap();
6697 path.pop(); // bench...
6699 path.pop(); // debug
6700 path.pop(); // target
6701 path.pop(); // bench
6702 path.push("lightning");
6703 path.push("net_graph-2023-01-18.bin");
6706 .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");
6707 #[cfg(require_route_graph_test)]
6708 return Ok(res.unwrap());
6709 #[cfg(not(require_route_graph_test))]
6713 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
6714 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
6717 pub(crate) fn payer_pubkey() -> PublicKey {
6718 let secp_ctx = Secp256k1::new();
6719 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
6723 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
6725 channel_id: [0; 32],
6726 counterparty: ChannelCounterparty {
6727 features: channelmanager::provided_init_features(&UserConfig::default()),
6729 unspendable_punishment_reserve: 0,
6730 forwarding_info: None,
6731 outbound_htlc_minimum_msat: None,
6732 outbound_htlc_maximum_msat: None,
6734 funding_txo: Some(OutPoint {
6735 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
6738 short_channel_id: Some(1),
6739 inbound_scid_alias: None,
6740 outbound_scid_alias: None,
6741 channel_value_satoshis: 10_000_000_000,
6743 balance_msat: 10_000_000_000,
6744 outbound_capacity_msat: 10_000_000_000,
6745 next_outbound_htlc_minimum_msat: 0,
6746 next_outbound_htlc_limit_msat: 10_000_000_000,
6747 inbound_capacity_msat: 0,
6748 unspendable_punishment_reserve: None,
6749 confirmations_required: None,
6750 confirmations: None,
6751 force_close_spend_delay: None,
6753 is_channel_ready: true,
6756 inbound_htlc_minimum_msat: None,
6757 inbound_htlc_maximum_msat: None,
6759 feerate_sat_per_1000_weight: None,
6763 pub(crate) fn generate_test_routes<S: Score>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
6764 score_params: &S::ScoreParams, features: InvoiceFeatures, mut seed: u64,
6765 starting_amount: u64, route_count: usize,
6766 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
6767 let payer = payer_pubkey();
6768 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
6769 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6771 let nodes = graph.read_only().nodes().clone();
6772 let mut route_endpoints = Vec::new();
6773 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
6774 // with some routes we picked being un-routable.
6775 for _ in 0..route_count * 3 / 2 {
6777 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6778 let src = PublicKey::from_slice(nodes.unordered_keys()
6779 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6780 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6781 let dst = PublicKey::from_slice(nodes.unordered_keys()
6782 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6783 let params = PaymentParameters::from_node_id(dst, 42)
6784 .with_bolt11_features(features.clone()).unwrap();
6785 let first_hop = first_hop(src);
6786 let amt = starting_amount + seed % 1_000_000;
6788 get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]),
6789 amt, &TestLogger::new(), &scorer, score_params, &random_seed_bytes).is_ok();
6791 // ...and seed the scorer with success and failure data...
6792 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6793 let mut score_amt = seed % 1_000_000_000;
6795 // Generate fail/success paths for a wider range of potential amounts with
6796 // MPP enabled to give us a chance to apply penalties for more potential
6798 let mpp_features = channelmanager::provided_invoice_features(&UserConfig::default());
6799 let params = PaymentParameters::from_node_id(dst, 42)
6800 .with_bolt11_features(mpp_features).unwrap();
6802 let route_res = get_route(&payer, ¶ms, &graph.read_only(),
6803 Some(&[&first_hop]), score_amt, &TestLogger::new(), &scorer,
6804 score_params, &random_seed_bytes);
6805 if let Ok(route) = route_res {
6806 for path in route.paths {
6807 if seed & 0x80 == 0 {
6808 scorer.payment_path_successful(&path);
6810 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
6811 scorer.payment_path_failed(&path, short_channel_id);
6813 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6817 // If we couldn't find a path with a higer amount, reduce and try again.
6821 route_endpoints.push((first_hop, params, amt));
6827 // Because we've changed channel scores, it's possible we'll take different routes to the
6828 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
6829 // requires a too-high CLTV delta.
6830 route_endpoints.retain(|(first_hop, params, amt)| {
6831 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
6832 &TestLogger::new(), &scorer, score_params, &random_seed_bytes).is_ok()
6834 route_endpoints.truncate(route_count);
6835 assert_eq!(route_endpoints.len(), route_count);
6843 use crate::sign::{EntropySource, KeysManager};
6844 use crate::ln::channelmanager;
6845 use crate::ln::features::InvoiceFeatures;
6846 use crate::routing::gossip::NetworkGraph;
6847 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
6848 use crate::util::config::UserConfig;
6849 use crate::util::logger::{Logger, Record};
6850 use crate::util::test_utils::TestLogger;
6852 use criterion::Criterion;
6854 struct DummyLogger {}
6855 impl Logger for DummyLogger {
6856 fn log(&self, _record: &Record) {}
6859 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
6860 let logger = TestLogger::new();
6861 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6862 let scorer = FixedPenaltyScorer::with_penalty(0);
6863 generate_routes(bench, &network_graph, scorer, &(), InvoiceFeatures::empty(), 0,
6864 "generate_routes_with_zero_penalty_scorer");
6867 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
6868 let logger = TestLogger::new();
6869 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6870 let scorer = FixedPenaltyScorer::with_penalty(0);
6871 generate_routes(bench, &network_graph, scorer, &(),
6872 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
6873 "generate_mpp_routes_with_zero_penalty_scorer");
6876 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6877 let logger = TestLogger::new();
6878 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6879 let params = ProbabilisticScoringFeeParameters::default();
6880 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6881 generate_routes(bench, &network_graph, scorer, ¶ms, InvoiceFeatures::empty(), 0,
6882 "generate_routes_with_probabilistic_scorer");
6885 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6886 let logger = TestLogger::new();
6887 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6888 let params = ProbabilisticScoringFeeParameters::default();
6889 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6890 generate_routes(bench, &network_graph, scorer, ¶ms,
6891 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
6892 "generate_mpp_routes_with_probabilistic_scorer");
6895 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6896 let logger = TestLogger::new();
6897 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6898 let params = ProbabilisticScoringFeeParameters::default();
6899 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6900 generate_routes(bench, &network_graph, scorer, ¶ms,
6901 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
6902 "generate_large_mpp_routes_with_probabilistic_scorer");
6905 fn generate_routes<S: Score>(
6906 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
6907 score_params: &S::ScoreParams, features: InvoiceFeatures, starting_amount: u64,
6908 bench_name: &'static str,
6910 let payer = bench_utils::payer_pubkey();
6911 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
6912 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6914 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
6915 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
6917 // ...then benchmark finding paths between the nodes we learned.
6919 bench.bench_function(bench_name, |b| b.iter(|| {
6920 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
6921 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
6922 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());