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, MutexGuard};
31 use alloc::collections::BinaryHeap;
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, Locked = MutexGuard<'a, 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, Locked = MutexGuard<'a, 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, Locked = MutexGuard<'a, 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(), 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> {
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> ScorerAccountingForInFlightHtlcs<'a, S> {
114 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
115 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
116 ScorerAccountingForInFlightHtlcs {
124 impl<'a, S: Score> Writeable for ScorerAccountingForInFlightHtlcs<'a, S> {
125 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.scorer.write(writer) }
128 impl<'a, S: Score> Score for ScorerAccountingForInFlightHtlcs<'a, S> {
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, {
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 (mut 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, vec_type),
554 (5, self.max_channel_saturation_power_of_half, required),
555 (6, self.expiry_time, option),
556 (7, self.previously_failed_channels, vec_type),
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, route_hints, vec_type),
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, vec_type),
575 (8, blinded_route_hints, optional_vec),
576 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
578 let clear_route_hints = route_hints.unwrap_or(vec![]);
579 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
580 let payee = if blinded_route_hints.len() != 0 {
581 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
583 route_hints: blinded_route_hints,
584 features: features.and_then(|f: Features| f.bolt12()),
588 route_hints: clear_route_hints,
589 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
590 features: features.and_then(|f| f.bolt11()),
591 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
595 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
596 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
598 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
600 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
606 impl PaymentParameters {
607 /// Creates a payee with the node id of the given `pubkey`.
609 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
611 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
613 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
615 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
616 max_path_count: DEFAULT_MAX_PATH_COUNT,
617 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
618 previously_failed_channels: Vec::new(),
622 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
624 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
627 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
628 /// whether your router will be allowed to find a multi-part route for this payment. If you
629 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
630 /// [`RecipientOnionFields::secret_only`].
632 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
633 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
634 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
635 .with_bolt11_features(InvoiceFeatures::for_keysend(allow_mpp))
636 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
639 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
640 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
641 /// [`PaymentParameters::expiry_time`].
642 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
643 Self::blinded(invoice.payment_paths().to_vec())
644 .with_bolt12_features(invoice.features().clone()).unwrap()
645 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
648 fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
650 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
652 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
653 max_path_count: DEFAULT_MAX_PATH_COUNT,
654 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
655 previously_failed_channels: Vec::new(),
659 /// Includes the payee's features. Errors if the parameters were not initialized with
660 /// [`PaymentParameters::from_bolt12_invoice`].
662 /// This is not exported to bindings users since bindings don't support move semantics
663 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
665 Payee::Clear { .. } => Err(()),
666 Payee::Blinded { route_hints, .. } =>
667 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
671 /// Includes the payee's features. Errors if the parameters were initialized with
672 /// [`PaymentParameters::from_bolt12_invoice`].
674 /// This is not exported to bindings users since bindings don't support move semantics
675 pub fn with_bolt11_features(self, features: InvoiceFeatures) -> Result<Self, ()> {
677 Payee::Blinded { .. } => Err(()),
678 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
680 payee: Payee::Clear {
681 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
687 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
688 /// [`PaymentParameters::from_bolt12_invoice`].
690 /// This is not exported to bindings users since bindings don't support move semantics
691 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
693 Payee::Blinded { .. } => Err(()),
694 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
696 payee: Payee::Clear {
697 route_hints, node_id, features, final_cltv_expiry_delta,
703 /// Includes a payment expiration in seconds relative to the UNIX epoch.
705 /// This is not exported to bindings users since bindings don't support move semantics
706 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
707 Self { expiry_time: Some(expiry_time), ..self }
710 /// Includes a limit for the total CLTV expiry delta which is considered during routing
712 /// This is not exported to bindings users since bindings don't support move semantics
713 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
714 Self { max_total_cltv_expiry_delta, ..self }
717 /// Includes a limit for the maximum number of payment paths that may be used.
719 /// This is not exported to bindings users since bindings don't support move semantics
720 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
721 Self { max_path_count, ..self }
724 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
725 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
727 /// This is not exported to bindings users since bindings don't support move semantics
728 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
729 Self { max_channel_saturation_power_of_half, ..self }
733 /// The recipient of a payment, differing based on whether they've hidden their identity with route
735 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
737 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
738 /// will be included in the final [`Route`].
740 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
742 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
743 /// Features supported by the payee.
745 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
747 features: Option<Bolt12InvoiceFeatures>,
749 /// The recipient included these route hints in their BOLT11 invoice.
751 /// The node id of the payee.
753 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
754 route_hints: Vec<RouteHint>,
755 /// Features supported by the payee.
757 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
758 /// does not contain any features.
760 /// [`for_keysend`]: PaymentParameters::for_keysend
761 features: Option<InvoiceFeatures>,
762 /// The minimum CLTV delta at the end of the route. This value must not be zero.
763 final_cltv_expiry_delta: u32,
768 fn node_id(&self) -> Option<PublicKey> {
770 Self::Clear { node_id, .. } => Some(*node_id),
774 fn node_features(&self) -> Option<NodeFeatures> {
776 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
777 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
780 fn supports_basic_mpp(&self) -> bool {
782 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
783 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
786 fn features(&self) -> Option<FeaturesRef> {
788 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
789 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
792 fn final_cltv_expiry_delta(&self) -> Option<u32> {
794 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
798 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
800 Self::Blinded { route_hints, .. } => &route_hints[..],
801 Self::Clear { .. } => &[]
805 fn unblinded_route_hints(&self) -> &[RouteHint] {
807 Self::Blinded { .. } => &[],
808 Self::Clear { route_hints, .. } => &route_hints[..]
813 enum FeaturesRef<'a> {
814 Bolt11(&'a InvoiceFeatures),
815 Bolt12(&'a Bolt12InvoiceFeatures),
818 Bolt11(InvoiceFeatures),
819 Bolt12(Bolt12InvoiceFeatures),
823 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
825 Self::Bolt12(f) => Some(f),
829 fn bolt11(self) -> Option<InvoiceFeatures> {
831 Self::Bolt11(f) => Some(f),
837 impl<'a> Writeable for FeaturesRef<'a> {
838 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
840 Self::Bolt11(f) => Ok(f.write(w)?),
841 Self::Bolt12(f) => Ok(f.write(w)?),
846 impl ReadableArgs<bool> for Features {
847 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
848 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
849 Ok(Self::Bolt12(Readable::read(reader)?))
853 /// A list of hops along a payment path terminating with a channel to the recipient.
854 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
855 pub struct RouteHint(pub Vec<RouteHintHop>);
857 impl Writeable for RouteHint {
858 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
859 (self.0.len() as u64).write(writer)?;
860 for hop in self.0.iter() {
867 impl Readable for RouteHint {
868 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
869 let hop_count: u64 = Readable::read(reader)?;
870 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
871 for _ in 0..hop_count {
872 hops.push(Readable::read(reader)?);
878 /// A channel descriptor for a hop along a payment path.
879 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
880 pub struct RouteHintHop {
881 /// The node_id of the non-target end of the route
882 pub src_node_id: PublicKey,
883 /// The short_channel_id of this channel
884 pub short_channel_id: u64,
885 /// The fees which must be paid to use this channel
886 pub fees: RoutingFees,
887 /// The difference in CLTV values between this node and the next node.
888 pub cltv_expiry_delta: u16,
889 /// The minimum value, in msat, which must be relayed to the next hop.
890 pub htlc_minimum_msat: Option<u64>,
891 /// The maximum value in msat available for routing with a single HTLC.
892 pub htlc_maximum_msat: Option<u64>,
895 impl_writeable_tlv_based!(RouteHintHop, {
896 (0, src_node_id, required),
897 (1, htlc_minimum_msat, option),
898 (2, short_channel_id, required),
899 (3, htlc_maximum_msat, option),
901 (6, cltv_expiry_delta, required),
904 #[derive(Eq, PartialEq)]
905 struct RouteGraphNode {
907 lowest_fee_to_node: u64,
908 total_cltv_delta: u32,
909 // The maximum value a yet-to-be-constructed payment path might flow through this node.
910 // This value is upper-bounded by us by:
911 // - how much is needed for a path being constructed
912 // - how much value can channels following this node (up to the destination) can contribute,
913 // considering their capacity and fees
914 value_contribution_msat: u64,
915 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
916 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
917 path_htlc_minimum_msat: u64,
918 /// All penalties incurred from this hop on the way to the destination, as calculated using
920 path_penalty_msat: u64,
921 /// The number of hops walked up to this node.
922 path_length_to_node: u8,
925 impl cmp::Ord for RouteGraphNode {
926 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
927 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
928 .saturating_add(other.path_penalty_msat);
929 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
930 .saturating_add(self.path_penalty_msat);
931 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
935 impl cmp::PartialOrd for RouteGraphNode {
936 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
937 Some(self.cmp(other))
941 /// A wrapper around the various hop representations.
943 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
944 #[derive(Clone, Debug)]
945 enum CandidateRouteHop<'a> {
946 /// A hop from the payer, where the outbound liquidity is known.
948 details: &'a ChannelDetails,
950 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
952 info: DirectedChannelInfo<'a>,
953 short_channel_id: u64,
955 /// A hop to the payee found in the BOLT 11 payment invoice, though not necessarily a direct
958 hint: &'a RouteHintHop,
960 /// The payee's identity is concealed behind blinded paths provided in a BOLT 12 invoice.
962 hint: &'a (BlindedPayInfo, BlindedPath),
965 /// Similar to [`Self::Blinded`], but the path here has 1 blinded hop. `BlindedPayInfo` provided
966 /// for 1-hop blinded paths is ignored because it is meant to apply to the hops *between* the
967 /// introduction node and the destination. Useful for tracking that we need to include a blinded
968 /// path at the end of our [`Route`].
970 hint: &'a (BlindedPayInfo, BlindedPath),
975 impl<'a> CandidateRouteHop<'a> {
976 fn short_channel_id(&self) -> Option<u64> {
978 CandidateRouteHop::FirstHop { details } => Some(details.get_outbound_payment_scid().unwrap()),
979 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
980 CandidateRouteHop::PrivateHop { hint } => Some(hint.short_channel_id),
981 CandidateRouteHop::Blinded { .. } => None,
982 CandidateRouteHop::OneHopBlinded { .. } => None,
986 // NOTE: This may alloc memory so avoid calling it in a hot code path.
987 fn features(&self) -> ChannelFeatures {
989 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
990 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
991 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
992 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
993 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
997 fn cltv_expiry_delta(&self) -> u32 {
999 CandidateRouteHop::FirstHop { .. } => 0,
1000 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1001 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
1002 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1003 CandidateRouteHop::OneHopBlinded { .. } => 0,
1007 fn htlc_minimum_msat(&self) -> u64 {
1009 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_minimum_msat,
1010 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1011 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
1012 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1013 CandidateRouteHop::OneHopBlinded { .. } => 0,
1017 fn fees(&self) -> RoutingFees {
1019 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1020 base_msat: 0, proportional_millionths: 0,
1022 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1023 CandidateRouteHop::PrivateHop { hint } => hint.fees,
1024 CandidateRouteHop::Blinded { hint, .. } => {
1026 base_msat: hint.0.fee_base_msat,
1027 proportional_millionths: hint.0.fee_proportional_millionths
1030 CandidateRouteHop::OneHopBlinded { .. } =>
1031 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1035 fn effective_capacity(&self) -> EffectiveCapacity {
1037 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
1038 liquidity_msat: details.next_outbound_htlc_limit_msat,
1040 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1041 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }} =>
1042 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1043 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }} =>
1044 EffectiveCapacity::Infinite,
1045 CandidateRouteHop::Blinded { hint, .. } =>
1046 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1047 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1051 fn id(&self, channel_direction: bool /* src_node_id < target_node_id */) -> CandidateHopId {
1053 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1054 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1055 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), channel_direction)),
1058 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1060 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1068 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1069 enum CandidateHopId {
1070 /// Contains (scid, src_node_id < target_node_id)
1072 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1077 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1078 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1080 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1081 EffectiveCapacity::Infinite => u64::max_value(),
1082 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1083 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1084 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1085 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1086 // expected to have been generated from up-to-date capacity information.
1087 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1088 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1089 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1093 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1094 -> bool where I1::Item: PartialEq<I2::Item> {
1096 let a = iter_a.next();
1097 let b = iter_b.next();
1098 if a.is_none() && b.is_none() { return true; }
1099 if a.is_none() || b.is_none() { return false; }
1100 if a.unwrap().ne(&b.unwrap()) { return false; }
1104 /// It's useful to keep track of the hops associated with the fees required to use them,
1105 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1106 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1107 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1109 struct PathBuildingHop<'a> {
1110 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
1111 // is a larger refactor and will require careful performance analysis.
1113 candidate: CandidateRouteHop<'a>,
1116 /// All the fees paid *after* this channel on the way to the destination
1117 next_hops_fee_msat: u64,
1118 /// Fee paid for the use of the current channel (see candidate.fees()).
1119 /// The value will be actually deducted from the counterparty balance on the previous link.
1120 hop_use_fee_msat: u64,
1121 /// Used to compare channels when choosing the for routing.
1122 /// Includes paying for the use of a hop and the following hops, as well as
1123 /// an estimated cost of reaching this hop.
1124 /// Might get stale when fees are recomputed. Primarily for internal use.
1125 total_fee_msat: u64,
1126 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1127 /// walk and may be invalid thereafter.
1128 path_htlc_minimum_msat: u64,
1129 /// All penalties incurred from this channel on the way to the destination, as calculated using
1130 /// channel scoring.
1131 path_penalty_msat: u64,
1132 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1133 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1134 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1135 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1136 /// avoid processing them again.
1137 was_processed: bool,
1138 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1139 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1140 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1141 // value_contribution_msat, which requires tracking it here. See comments below where it is
1142 // used for more info.
1143 value_contribution_msat: u64,
1146 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1147 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1148 let mut debug_struct = f.debug_struct("PathBuildingHop");
1150 .field("node_id", &self.node_id)
1151 .field("short_channel_id", &self.candidate.short_channel_id())
1152 .field("total_fee_msat", &self.total_fee_msat)
1153 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1154 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1155 .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)))
1156 .field("path_penalty_msat", &self.path_penalty_msat)
1157 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1158 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1159 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1160 let debug_struct = debug_struct
1161 .field("value_contribution_msat", &self.value_contribution_msat);
1162 debug_struct.finish()
1166 // Instantiated with a list of hops with correct data in them collected during path finding,
1167 // an instance of this struct should be further modified only via given methods.
1169 struct PaymentPath<'a> {
1170 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1173 impl<'a> PaymentPath<'a> {
1174 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1175 fn get_value_msat(&self) -> u64 {
1176 self.hops.last().unwrap().0.fee_msat
1179 fn get_path_penalty_msat(&self) -> u64 {
1180 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1183 fn get_total_fee_paid_msat(&self) -> u64 {
1184 if self.hops.len() < 1 {
1188 // Can't use next_hops_fee_msat because it gets outdated.
1189 for (i, (hop, _)) in self.hops.iter().enumerate() {
1190 if i != self.hops.len() - 1 {
1191 result += hop.fee_msat;
1197 fn get_cost_msat(&self) -> u64 {
1198 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1201 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1202 // to change fees may result in an inconsistency.
1204 // Sometimes we call this function right after constructing a path which is inconsistent in
1205 // that it the value being transferred has decreased while we were doing path finding, leading
1206 // to the fees being paid not lining up with the actual limits.
1208 // Note that this function is not aware of the available_liquidity limit, and thus does not
1209 // support increasing the value being transferred beyond what was selected during the initial
1211 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
1212 let mut total_fee_paid_msat = 0 as u64;
1213 for i in (0..self.hops.len()).rev() {
1214 let last_hop = i == self.hops.len() - 1;
1216 // For non-last-hop, this value will represent the fees paid on the current hop. It
1217 // will consist of the fees for the use of the next hop, and extra fees to match
1218 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1219 let mut cur_hop_fees_msat = 0;
1221 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1224 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1225 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1226 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1227 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1228 // set it too high just to maliciously take more fees by exploiting this
1229 // match htlc_minimum_msat logic.
1230 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1231 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1232 // Note that there is a risk that *previous hops* (those closer to us, as we go
1233 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1235 // This might make us end up with a broken route, although this should be super-rare
1236 // in practice, both because of how healthy channels look like, and how we pick
1237 // channels in add_entry.
1238 // Also, this can't be exploited more heavily than *announce a free path and fail
1240 cur_hop_transferred_amount_msat += extra_fees_msat;
1241 total_fee_paid_msat += extra_fees_msat;
1242 cur_hop_fees_msat += extra_fees_msat;
1246 // Final hop is a special case: it usually has just value_msat (by design), but also
1247 // it still could overpay for the htlc_minimum_msat.
1248 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1250 // Propagate updated fees for the use of the channels to one hop back, where they
1251 // will be actually paid (fee_msat). The last hop is handled above separately.
1252 cur_hop.fee_msat = cur_hop_fees_msat;
1255 // Fee for the use of the current hop which will be deducted on the previous hop.
1256 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1257 // this channel is free for us.
1259 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1260 cur_hop.hop_use_fee_msat = new_fee;
1261 total_fee_paid_msat += new_fee;
1263 // It should not be possible because this function is called only to reduce the
1264 // value. In that case, compute_fee was already called with the same fees for
1265 // larger amount and there was no overflow.
1274 /// Calculate the fees required to route the given amount over a channel with the given fees.
1275 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1276 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1277 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1281 /// Calculate the fees required to route the given amount over a channel with the given fees,
1282 /// saturating to [`u64::max_value`].
1283 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1284 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1285 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1286 .saturating_add(channel_fees.base_msat as u64)
1289 /// The default `features` we assume for a node in a route, when no `features` are known about that
1292 /// Default features are:
1293 /// * variable_length_onion_optional
1294 fn default_node_features() -> NodeFeatures {
1295 let mut features = NodeFeatures::empty();
1296 features.set_variable_length_onion_optional();
1300 struct LoggedPayeePubkey(Option<PublicKey>);
1301 impl fmt::Display for LoggedPayeePubkey {
1302 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1305 "payee node id ".fmt(f)?;
1309 "blinded payee".fmt(f)
1315 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1316 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1317 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1319 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1320 "blinded route hint with introduction node id ".fmt(f)?;
1321 hint.1.introduction_node_id.fmt(f)?;
1322 " and blinding point ".fmt(f)?;
1323 hint.1.blinding_point.fmt(f)
1327 self.0.short_channel_id().unwrap().fmt(f)
1334 fn sort_first_hop_channels(
1335 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1336 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1338 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1339 // most like to use.
1341 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1342 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1345 // Second, because simply always sorting in descending order would always use our largest
1346 // available outbound capacity, needlessly fragmenting our available channel capacities,
1347 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1348 // which have enough, but not too much, capacity for the payment.
1350 // Available outbound balances factor in liquidity already reserved for previously found paths.
1351 channels.sort_unstable_by(|chan_a, chan_b| {
1352 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1353 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1354 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1355 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1356 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1357 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1358 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1359 // Sort in descending order
1360 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1362 // Sort in ascending order
1363 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1368 /// Finds a route from us (payer) to the given target node (payee).
1370 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
1371 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1373 /// Private routing paths between a public node and the target may be included in `params.payee`.
1375 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1376 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1377 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1379 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1380 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1381 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1385 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
1386 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
1391 /// Panics if first_hops contains channels without short_channel_ids;
1392 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1394 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1395 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1396 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1397 pub fn find_route<L: Deref, GL: Deref, S: Score>(
1398 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1399 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1400 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1401 ) -> Result<Route, LightningError>
1402 where L::Target: Logger, GL::Target: Logger {
1403 let graph_lock = network_graph.read_only();
1404 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
1405 route_params.final_value_msat, logger, scorer, score_params,
1406 random_seed_bytes)?;
1407 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1411 pub(crate) fn get_route<L: Deref, S: Score>(
1412 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
1413 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, logger: L, scorer: &S, score_params: &S::ScoreParams,
1414 _random_seed_bytes: &[u8; 32]
1415 ) -> Result<Route, LightningError>
1416 where L::Target: Logger {
1417 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1418 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1419 // so use a dummy id for this in the blinded case.
1420 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1421 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1422 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1423 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1424 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1426 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1427 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1430 if final_value_msat > MAX_VALUE_MSAT {
1431 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1434 if final_value_msat == 0 {
1435 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1438 match &payment_params.payee {
1439 Payee::Clear { route_hints, node_id, .. } => {
1440 for route in route_hints.iter() {
1441 for hop in &route.0 {
1442 if hop.src_node_id == *node_id {
1443 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1448 Payee::Blinded { route_hints, .. } => {
1449 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1450 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});
1452 for (_, blinded_path) in route_hints.iter() {
1453 if blinded_path.blinded_hops.len() == 0 {
1454 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1455 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1456 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1457 } else if blinded_path.blinded_hops.len() == 1 &&
1458 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1459 && p.introduction_node_id != blinded_path.introduction_node_id)
1461 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1466 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1467 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1468 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});
1471 // The general routing idea is the following:
1472 // 1. Fill first/last hops communicated by the caller.
1473 // 2. Attempt to construct a path from payer to payee for transferring
1474 // any ~sufficient (described later) value.
1475 // If succeed, remember which channels were used and how much liquidity they have available,
1476 // so that future paths don't rely on the same liquidity.
1477 // 3. Proceed to the next step if:
1478 // - we hit the recommended target value;
1479 // - OR if we could not construct a new path. Any next attempt will fail too.
1480 // Otherwise, repeat step 2.
1481 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1482 // (not recommended value).
1483 // 5. If yes, proceed. If not, fail routing.
1484 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1485 // transferred up to the transfer target value.
1486 // 7. Reduce the value of the last path until we are sending only the target value.
1487 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1488 // them so that we're not sending two HTLCs along the same path.
1490 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1491 // distance from the payee
1493 // We are not a faithful Dijkstra's implementation because we can change values which impact
1494 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1495 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1496 // the value we are currently attempting to send over a path, we simply reduce the value being
1497 // sent along the path for any hops after that channel. This may imply that later fees (which
1498 // we've already tabulated) are lower because a smaller value is passing through the channels
1499 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1500 // channels which were selected earlier (and which may still be used for other paths without a
1501 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1504 // One potentially problematic case for this algorithm would be if there are many
1505 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1506 // graph walking), we may never find a path which is not liquidity-limited and has lower
1507 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1508 // Because we only consider paths with at least 5% of the total value being sent, the damage
1509 // from such a case should be limited, however this could be further reduced in the future by
1510 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1511 // limits for the purposes of fee calculation.
1513 // Alternatively, we could store more detailed path information in the heap (targets, below)
1514 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1515 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1516 // and practically (as we would need to store dynamically-allocated path information in heap
1517 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1518 // results of such an algorithm would likely be biased towards lower-value paths.
1520 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1521 // outside of our current search value, running a path search more times to gather candidate
1522 // paths at different values. While this may be acceptable, further path searches may increase
1523 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1524 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1525 // the same time, remaining generic across different payment values.
1527 let network_channels = network_graph.channels();
1528 let network_nodes = network_graph.nodes();
1530 if payment_params.max_path_count == 0 {
1531 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1534 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1535 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1537 let allow_mpp = if payment_params.max_path_count == 1 {
1539 } else if payment_params.payee.supports_basic_mpp() {
1541 } else if let Some(payee) = payee_node_id_opt {
1542 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1543 |info| info.features.supports_basic_mpp()))
1546 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1547 LoggedPayeePubkey(payment_params.payee.node_id()), if allow_mpp { "with" } else { "without" },
1548 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1551 // Prepare the data we'll use for payee-to-payer search by
1552 // inserting first hops suggested by the caller as targets.
1553 // Our search will then attempt to reach them while traversing from the payee node.
1554 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1555 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1556 if let Some(hops) = first_hops {
1558 if chan.get_outbound_payment_scid().is_none() {
1559 panic!("first_hops should be filled in with usable channels, not pending ones");
1561 if chan.counterparty.node_id == *our_node_pubkey {
1562 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1565 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1566 .or_insert(Vec::new())
1569 if first_hop_targets.is_empty() {
1570 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1574 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1575 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1576 // adding duplicate entries when we find a better path to a given node.
1577 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1579 // Map from node_id to information about the best current path to that node, including feerate
1581 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1583 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1584 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1585 // htlc_minimum with extra fees while still finding a cheaper path.
1586 let mut hit_minimum_limit;
1588 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1589 // We start with a path_value of the exact amount we want, and if that generates a route we may
1590 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1591 // amount we want in total across paths, selecting the best subset at the end.
1592 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1593 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1594 let mut path_value_msat = final_value_msat;
1596 // Routing Fragmentation Mitigation heuristic:
1598 // Routing fragmentation across many payment paths increases the overall routing
1599 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1600 // Taking too many smaller paths also increases the chance of payment failure.
1601 // Thus to avoid this effect, we require from our collected links to provide
1602 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1603 // This requirement is currently set to be 1/max_path_count of the payment
1604 // value to ensure we only ever return routes that do not violate this limit.
1605 let minimal_value_contribution_msat: u64 = if allow_mpp {
1606 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1611 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1612 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1613 // drop the requirement by setting this to 0.
1614 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1616 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1617 // determine if the channel can be used by additional MPP paths or to inform path finding
1618 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1619 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1621 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1622 HashMap::with_capacity(network_nodes.len());
1624 // Keeping track of how much value we already collected across other paths. Helps to decide
1625 // when we want to stop looking for new paths.
1626 let mut already_collected_value_msat = 0;
1628 for (_, channels) in first_hop_targets.iter_mut() {
1629 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1633 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1634 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1636 macro_rules! add_entry {
1637 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1638 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1639 // since that value has to be transferred over this channel.
1640 // Returns whether this channel caused an update to `targets`.
1641 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1642 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1643 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1644 // We "return" whether we updated the path at the end, and how much we can route via
1645 // this channel, via this:
1646 let mut did_add_update_path_to_src_node = None;
1647 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1648 // practice these cases should be caught earlier:
1649 // - for regular channels at channel announcement (TODO)
1650 // - for first and last hops early in get_route
1651 if $src_node_id != $dest_node_id {
1652 let scid_opt = $candidate.short_channel_id();
1653 let effective_capacity = $candidate.effective_capacity();
1654 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1656 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1657 // It may be misleading because we might later choose to reduce the value transferred
1658 // over these channels, and the channel which was insufficient might become sufficient.
1659 // Worst case: we drop a good channel here because it can't cover the high following
1660 // fees caused by one expensive channel, but then this channel could have been used
1661 // if the amount being transferred over this path is lower.
1662 // We do this for now, but this is a subject for removal.
1663 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1664 let used_liquidity_msat = used_liquidities
1665 .get(&$candidate.id($src_node_id < $dest_node_id))
1666 .map_or(0, |used_liquidity_msat| {
1667 available_value_contribution_msat = available_value_contribution_msat
1668 .saturating_sub(*used_liquidity_msat);
1669 *used_liquidity_msat
1672 // Verify the liquidity offered by this channel complies to the minimal contribution.
1673 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1674 // Do not consider candidate hops that would exceed the maximum path length.
1675 let path_length_to_node = $next_hops_path_length + 1;
1676 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1678 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1679 // In order to already account for some of the privacy enhancing random CLTV
1680 // expiry delta offset we add on top later, we subtract a rough estimate
1681 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1682 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1683 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1684 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1685 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1686 .saturating_add($candidate.cltv_expiry_delta());
1687 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1689 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1690 // Includes paying fees for the use of the following channels.
1691 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1692 Some(result) => result,
1693 // Can't overflow due to how the values were computed right above.
1694 None => unreachable!(),
1696 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1697 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1698 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1700 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1701 let may_overpay_to_meet_path_minimum_msat =
1702 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1703 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1704 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1705 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1707 let payment_failed_on_this_channel = scid_opt.map_or(false,
1708 |scid| payment_params.previously_failed_channels.contains(&scid));
1710 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1711 // bother considering this channel. If retrying with recommended_value_msat may
1712 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1713 // around again with a higher amount.
1714 if !contributes_sufficient_value || exceeds_max_path_length ||
1715 exceeds_cltv_delta_limit || payment_failed_on_this_channel {
1716 // Path isn't useful, ignore it and move on.
1717 } else if may_overpay_to_meet_path_minimum_msat {
1718 hit_minimum_limit = true;
1719 } else if over_path_minimum_msat {
1720 // Note that low contribution here (limited by available_liquidity_msat)
1721 // might violate htlc_minimum_msat on the hops which are next along the
1722 // payment path (upstream to the payee). To avoid that, we recompute
1723 // path fees knowing the final path contribution after constructing it.
1724 let path_htlc_minimum_msat = cmp::max(
1725 compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1726 .saturating_add($next_hops_path_htlc_minimum_msat),
1727 $candidate.htlc_minimum_msat());
1728 let hm_entry = dist.entry($src_node_id);
1729 let old_entry = hm_entry.or_insert_with(|| {
1730 // If there was previously no known way to access the source node
1731 // (recall it goes payee-to-payer) of short_channel_id, first add a
1732 // semi-dummy record just to compute the fees to reach the source node.
1733 // This will affect our decision on selecting short_channel_id
1734 // as a way to reach the $dest_node_id.
1736 node_id: $dest_node_id.clone(),
1737 candidate: $candidate.clone(),
1739 next_hops_fee_msat: u64::max_value(),
1740 hop_use_fee_msat: u64::max_value(),
1741 total_fee_msat: u64::max_value(),
1742 path_htlc_minimum_msat,
1743 path_penalty_msat: u64::max_value(),
1744 was_processed: false,
1745 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1746 value_contribution_msat,
1750 #[allow(unused_mut)] // We only use the mut in cfg(test)
1751 let mut should_process = !old_entry.was_processed;
1752 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1754 // In test/fuzzing builds, we do extra checks to make sure the skipping
1755 // of already-seen nodes only happens in cases we expect (see below).
1756 if !should_process { should_process = true; }
1760 let mut hop_use_fee_msat = 0;
1761 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1763 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1764 // will have the same effective-fee
1765 if $src_node_id != our_node_id {
1766 // Note that `u64::max_value` means we'll always fail the
1767 // `old_entry.total_fee_msat > total_fee_msat` check below
1768 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1769 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1772 let channel_usage = ChannelUsage {
1773 amount_msat: amount_to_transfer_over_msat,
1774 inflight_htlc_msat: used_liquidity_msat,
1777 let channel_penalty_msat = scid_opt.map_or(0,
1778 |scid| scorer.channel_penalty_msat(scid, &$src_node_id, &$dest_node_id,
1779 channel_usage, score_params));
1780 let path_penalty_msat = $next_hops_path_penalty_msat
1781 .saturating_add(channel_penalty_msat);
1782 let new_graph_node = RouteGraphNode {
1783 node_id: $src_node_id,
1784 lowest_fee_to_node: total_fee_msat,
1785 total_cltv_delta: hop_total_cltv_delta,
1786 value_contribution_msat,
1787 path_htlc_minimum_msat,
1789 path_length_to_node,
1792 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1793 // if this way is cheaper than the already known
1794 // (considering the cost to "reach" this channel from the route destination,
1795 // the cost of using this channel,
1796 // and the cost of routing to the source node of this channel).
1797 // Also, consider that htlc_minimum_msat_difference, because we might end up
1798 // paying it. Consider the following exploit:
1799 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1800 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1801 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1802 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1804 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1805 // but it may require additional tracking - we don't want to double-count
1806 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1807 // can't use something that may decrease on future hops.
1808 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1809 .saturating_add(old_entry.path_penalty_msat);
1810 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1811 .saturating_add(path_penalty_msat);
1813 if !old_entry.was_processed && new_cost < old_cost {
1814 targets.push(new_graph_node);
1815 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1816 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1817 old_entry.total_fee_msat = total_fee_msat;
1818 old_entry.node_id = $dest_node_id.clone();
1819 old_entry.candidate = $candidate.clone();
1820 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1821 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1822 old_entry.path_penalty_msat = path_penalty_msat;
1823 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1825 old_entry.value_contribution_msat = value_contribution_msat;
1827 did_add_update_path_to_src_node = Some(value_contribution_msat);
1828 } else if old_entry.was_processed && new_cost < old_cost {
1829 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1831 // If we're skipping processing a node which was previously
1832 // processed even though we found another path to it with a
1833 // cheaper fee, check that it was because the second path we
1834 // found (which we are processing now) has a lower value
1835 // contribution due to an HTLC minimum limit.
1837 // e.g. take a graph with two paths from node 1 to node 2, one
1838 // through channel A, and one through channel B. Channel A and
1839 // B are both in the to-process heap, with their scores set by
1840 // a higher htlc_minimum than fee.
1841 // Channel A is processed first, and the channels onwards from
1842 // node 1 are added to the to-process heap. Thereafter, we pop
1843 // Channel B off of the heap, note that it has a much more
1844 // restrictive htlc_maximum_msat, and recalculate the fees for
1845 // all of node 1's channels using the new, reduced, amount.
1847 // This would be bogus - we'd be selecting a higher-fee path
1848 // with a lower htlc_maximum_msat instead of the one we'd
1849 // already decided to use.
1850 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1852 value_contribution_msat + path_penalty_msat <
1853 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1861 did_add_update_path_to_src_node
1865 let default_node_features = default_node_features();
1867 // Find ways (channels with destination) to reach a given node and store them
1868 // in the corresponding data structures (routing graph etc).
1869 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1870 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1871 // This data can later be helpful to optimize routing (pay lower fees).
1872 macro_rules! add_entries_to_cheapest_to_target_node {
1873 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1874 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1875 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1876 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1877 let was_processed = elem.was_processed;
1878 elem.was_processed = true;
1881 // Entries are added to dist in add_entry!() when there is a channel from a node.
1882 // Because there are no channels from payee, it will not have a dist entry at this point.
1883 // If we're processing any other node, it is always be the result of a channel from it.
1884 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
1889 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1890 for details in first_channels {
1891 let candidate = CandidateRouteHop::FirstHop { details };
1892 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1893 $next_hops_value_contribution,
1894 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1895 $next_hops_cltv_delta, $next_hops_path_length);
1899 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1902 &default_node_features
1905 if !features.requires_unknown_bits() {
1906 for chan_id in $node.channels.iter() {
1907 let chan = network_channels.get(chan_id).unwrap();
1908 if !chan.features.requires_unknown_bits() {
1909 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1910 if first_hops.is_none() || *source != our_node_id {
1911 if directed_channel.direction().enabled {
1912 let candidate = CandidateRouteHop::PublicHop {
1913 info: directed_channel,
1914 short_channel_id: *chan_id,
1916 add_entry!(candidate, *source, $node_id,
1917 $fee_to_target_msat,
1918 $next_hops_value_contribution,
1919 $next_hops_path_htlc_minimum_msat,
1920 $next_hops_path_penalty_msat,
1921 $next_hops_cltv_delta, $next_hops_path_length);
1932 let mut payment_paths = Vec::<PaymentPath>::new();
1934 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1935 'paths_collection: loop {
1936 // For every new path, start from scratch, except for used_liquidities, which
1937 // helps to avoid reusing previously selected paths in future iterations.
1940 hit_minimum_limit = false;
1942 // If first hop is a private channel and the only way to reach the payee, this is the only
1943 // place where it could be added.
1944 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
1945 for details in first_channels {
1946 let candidate = CandidateRouteHop::FirstHop { details };
1947 let added = add_entry!(candidate, our_node_id, payee, 0, path_value_msat,
1948 0, 0u64, 0, 0).is_some();
1949 log_trace!(logger, "{} direct route to payee via {}",
1950 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
1954 // Add the payee as a target, so that the payee-to-payer
1955 // search algorithm knows what to start with.
1956 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
1957 // The payee is not in our network graph, so nothing to add here.
1958 // There is still a chance of reaching them via last_hops though,
1959 // so don't yet fail the payment here.
1960 // If not, targets.pop() will not even let us enter the loop in step 2.
1963 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
1968 // If a caller provided us with last hops, add them to routing targets. Since this happens
1969 // earlier than general path finding, they will be somewhat prioritized, although currently
1970 // it matters only if the fees are exactly the same.
1971 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
1972 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
1973 let have_intro_node_in_graph =
1974 // Only add the hops in this route to our candidate set if either
1975 // we have a direct channel to the first hop or the first hop is
1976 // in the regular network graph.
1977 first_hop_targets.get(&intro_node_id).is_some() ||
1978 network_nodes.get(&intro_node_id).is_some();
1979 if !have_intro_node_in_graph { continue }
1980 let candidate = if hint.1.blinded_hops.len() == 1 {
1981 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
1982 } else { CandidateRouteHop::Blinded { hint, hint_idx } };
1983 let mut path_contribution_msat = path_value_msat;
1984 if let Some(hop_used_msat) = add_entry!(candidate, intro_node_id, maybe_dummy_payee_node_id,
1985 0, path_contribution_msat, 0, 0_u64, 0, 0)
1987 path_contribution_msat = hop_used_msat;
1989 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
1990 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
1992 for details in first_channels {
1993 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
1994 add_entry!(first_hop_candidate, our_node_id, intro_node_id, 0, path_contribution_msat, 0,
1999 for route in payment_params.payee.unblinded_route_hints().iter()
2000 .filter(|route| !route.0.is_empty())
2002 let first_hop_in_route = &(route.0)[0];
2003 let have_hop_src_in_graph =
2004 // Only add the hops in this route to our candidate set if either
2005 // we have a direct channel to the first hop or the first hop is
2006 // in the regular network graph.
2007 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
2008 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
2009 if have_hop_src_in_graph {
2010 // We start building the path from reverse, i.e., from payee
2011 // to the first RouteHintHop in the path.
2012 let hop_iter = route.0.iter().rev();
2013 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2014 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2015 let mut hop_used = true;
2016 let mut aggregate_next_hops_fee_msat: u64 = 0;
2017 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2018 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2019 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2020 let mut aggregate_next_hops_path_length: u8 = 0;
2021 let mut aggregate_path_contribution_msat = path_value_msat;
2023 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2024 let source = NodeId::from_pubkey(&hop.src_node_id);
2025 let target = NodeId::from_pubkey(&prev_hop_id);
2026 let candidate = network_channels
2027 .get(&hop.short_channel_id)
2028 .and_then(|channel| channel.as_directed_to(&target))
2029 .map(|(info, _)| CandidateRouteHop::PublicHop {
2031 short_channel_id: hop.short_channel_id,
2033 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
2035 if let Some(hop_used_msat) = add_entry!(candidate, source, target,
2036 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2037 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2038 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2040 aggregate_path_contribution_msat = hop_used_msat;
2042 // If this hop was not used then there is no use checking the preceding
2043 // hops in the RouteHint. We can break by just searching for a direct
2044 // channel between last checked hop and first_hop_targets.
2048 let used_liquidity_msat = used_liquidities
2049 .get(&candidate.id(source < target)).copied()
2051 let channel_usage = ChannelUsage {
2052 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2053 inflight_htlc_msat: used_liquidity_msat,
2054 effective_capacity: candidate.effective_capacity(),
2056 let channel_penalty_msat = scorer.channel_penalty_msat(
2057 hop.short_channel_id, &source, &target, channel_usage, score_params
2059 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2060 .saturating_add(channel_penalty_msat);
2062 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2063 .saturating_add(hop.cltv_expiry_delta as u32);
2065 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2068 // Searching for a direct channel between last checked hop and first_hop_targets
2069 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&prev_hop_id)) {
2070 sort_first_hop_channels(first_channels, &used_liquidities,
2071 recommended_value_msat, our_node_pubkey);
2072 for details in first_channels {
2073 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2074 add_entry!(first_hop_candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
2075 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2076 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2077 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2085 // In the next values of the iterator, the aggregate fees already reflects
2086 // the sum of value sent from payer (final_value_msat) and routing fees
2087 // for the last node in the RouteHint. We need to just add the fees to
2088 // route through the current node so that the preceding node (next iteration)
2090 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2091 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2092 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2094 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
2095 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
2096 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
2097 .checked_add(hop_htlc_minimum_msat_inc);
2098 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
2100 if idx == route.0.len() - 1 {
2101 // The last hop in this iterator is the first hop in
2102 // overall RouteHint.
2103 // If this hop connects to a node with which we have a direct channel,
2104 // ignore the network graph and, if the last hop was added, add our
2105 // direct channel to the candidate set.
2107 // Note that we *must* check if the last hop was added as `add_entry`
2108 // always assumes that the third argument is a node to which we have a
2110 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2111 sort_first_hop_channels(first_channels, &used_liquidities,
2112 recommended_value_msat, our_node_pubkey);
2113 for details in first_channels {
2114 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2115 add_entry!(first_hop_candidate, our_node_id,
2116 NodeId::from_pubkey(&hop.src_node_id),
2117 aggregate_next_hops_fee_msat,
2118 aggregate_path_contribution_msat,
2119 aggregate_next_hops_path_htlc_minimum_msat,
2120 aggregate_next_hops_path_penalty_msat,
2121 aggregate_next_hops_cltv_delta,
2122 aggregate_next_hops_path_length);
2130 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2132 // At this point, targets are filled with the data from first and
2133 // last hops communicated by the caller, and the payment receiver.
2134 let mut found_new_path = false;
2137 // If this loop terminates due the exhaustion of targets, two situations are possible:
2138 // - not enough outgoing liquidity:
2139 // 0 < already_collected_value_msat < final_value_msat
2140 // - enough outgoing liquidity:
2141 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2142 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2143 // paths_collection will be stopped because found_new_path==false.
2144 // This is not necessarily a routing failure.
2145 '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() {
2147 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2148 // traversing the graph and arrange the path out of what we found.
2149 if node_id == our_node_id {
2150 let mut new_entry = dist.remove(&our_node_id).unwrap();
2151 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2154 let mut features_set = false;
2155 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
2156 for details in first_channels {
2157 if let Some(scid) = ordered_hops.last().unwrap().0.candidate.short_channel_id() {
2158 if details.get_outbound_payment_scid().unwrap() == scid {
2159 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2160 features_set = true;
2167 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
2168 if let Some(node_info) = node.announcement_info.as_ref() {
2169 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2171 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2174 // We can fill in features for everything except hops which were
2175 // provided via the invoice we're paying. We could guess based on the
2176 // recipient's features but for now we simply avoid guessing at all.
2180 // Means we succesfully traversed from the payer to the payee, now
2181 // save this path for the payment route. Also, update the liquidity
2182 // remaining on the used hops, so that we take them into account
2183 // while looking for more paths.
2184 if ordered_hops.last().unwrap().0.node_id == maybe_dummy_payee_node_id {
2188 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
2189 Some(payment_hop) => payment_hop,
2190 // We can't arrive at None because, if we ever add an entry to targets,
2191 // we also fill in the entry in dist (see add_entry!).
2192 None => unreachable!(),
2194 // We "propagate" the fees one hop backward (topologically) here,
2195 // so that fees paid for a HTLC forwarding on the current channel are
2196 // associated with the previous channel (where they will be subtracted).
2197 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2198 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2200 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2201 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2203 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2204 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2206 let mut payment_path = PaymentPath {hops: ordered_hops};
2208 // We could have possibly constructed a slightly inconsistent path: since we reduce
2209 // value being transferred along the way, we could have violated htlc_minimum_msat
2210 // on some channels we already passed (assuming dest->source direction). Here, we
2211 // recompute the fees again, so that if that's the case, we match the currently
2212 // underpaid htlc_minimum_msat with fees.
2213 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2214 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
2215 payment_path.update_value_and_recompute_fees(value_contribution_msat);
2217 // Since a path allows to transfer as much value as
2218 // the smallest channel it has ("bottleneck"), we should recompute
2219 // the fees so sender HTLC don't overpay fees when traversing
2220 // larger channels than the bottleneck. This may happen because
2221 // when we were selecting those channels we were not aware how much value
2222 // this path will transfer, and the relative fee for them
2223 // might have been computed considering a larger value.
2224 // Remember that we used these channels so that we don't rely
2225 // on the same liquidity in future paths.
2226 let mut prevented_redundant_path_selection = false;
2227 let prev_hop_iter = core::iter::once(&our_node_id)
2228 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
2229 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
2230 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2231 let used_liquidity_msat = used_liquidities
2232 .entry(hop.candidate.id(*prev_hop < hop.node_id))
2233 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2234 .or_insert(spent_on_hop_msat);
2235 let hop_capacity = hop.candidate.effective_capacity();
2236 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2237 if *used_liquidity_msat == hop_max_msat {
2238 // If this path used all of this channel's available liquidity, we know
2239 // this path will not be selected again in the next loop iteration.
2240 prevented_redundant_path_selection = true;
2242 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2244 if !prevented_redundant_path_selection {
2245 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2246 // we'll probably end up picking the same path again on the next iteration.
2247 // Decrease the available liquidity of a hop in the middle of the path.
2248 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2249 let exhausted = u64::max_value();
2250 log_trace!(logger, "Disabling route candidate {} for future path building iterations to
2251 avoid duplicates.", LoggedCandidateHop(victim_candidate));
2252 *used_liquidities.entry(victim_candidate.id(false)).or_default() = exhausted;
2253 *used_liquidities.entry(victim_candidate.id(true)).or_default() = exhausted;
2256 // Track the total amount all our collected paths allow to send so that we know
2257 // when to stop looking for more paths
2258 already_collected_value_msat += value_contribution_msat;
2260 payment_paths.push(payment_path);
2261 found_new_path = true;
2262 break 'path_construction;
2265 // If we found a path back to the payee, we shouldn't try to process it again. This is
2266 // the equivalent of the `elem.was_processed` check in
2267 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2268 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2270 // Otherwise, since the current target node is not us,
2271 // keep "unrolling" the payment graph from payee to payer by
2272 // finding a way to reach the current target from the payer side.
2273 match network_nodes.get(&node_id) {
2276 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2277 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2278 total_cltv_delta, path_length_to_node);
2284 if !found_new_path && channel_saturation_pow_half != 0 {
2285 channel_saturation_pow_half = 0;
2286 continue 'paths_collection;
2288 // If we don't support MPP, no use trying to gather more value ever.
2289 break 'paths_collection;
2293 // Stop either when the recommended value is reached or if no new path was found in this
2295 // In the latter case, making another path finding attempt won't help,
2296 // because we deterministically terminated the search due to low liquidity.
2297 if !found_new_path && channel_saturation_pow_half != 0 {
2298 channel_saturation_pow_half = 0;
2299 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2300 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2301 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2302 break 'paths_collection;
2303 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2304 // Further, if this was our first walk of the graph, and we weren't limited by an
2305 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2306 // limited by an htlc_minimum_msat value, find another path with a higher value,
2307 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2308 // still keeping a lower total fee than this path.
2309 if !hit_minimum_limit {
2310 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2311 break 'paths_collection;
2313 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
2314 path_value_msat = recommended_value_msat;
2319 if payment_paths.len() == 0 {
2320 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2323 if already_collected_value_msat < final_value_msat {
2324 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2328 let mut selected_route = payment_paths;
2330 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2331 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2333 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2334 // the value they contribute towards the payment amount.
2335 // We sort in descending order as we will remove from the front in `retain`, next.
2336 selected_route.sort_unstable_by(|a, b|
2337 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2338 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2341 // We should make sure that at least 1 path left.
2342 let mut paths_left = selected_route.len();
2343 selected_route.retain(|path| {
2344 if paths_left == 1 {
2347 let path_value_msat = path.get_value_msat();
2348 if path_value_msat <= overpaid_value_msat {
2349 overpaid_value_msat -= path_value_msat;
2355 debug_assert!(selected_route.len() > 0);
2357 if overpaid_value_msat != 0 {
2359 // Now, subtract the remaining overpaid value from the most-expensive path.
2360 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2361 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2362 selected_route.sort_unstable_by(|a, b| {
2363 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2364 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2365 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2367 let expensive_payment_path = selected_route.first_mut().unwrap();
2369 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2370 // can't go negative.
2371 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2372 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2376 // Sort by the path itself and combine redundant paths.
2377 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2378 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2380 selected_route.sort_unstable_by_key(|path| {
2381 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2382 debug_assert!(path.hops.len() <= key.len());
2383 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id(true)).zip(key.iter_mut()) {
2388 for idx in 0..(selected_route.len() - 1) {
2389 if idx + 1 >= selected_route.len() { break; }
2390 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id)),
2391 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id))) {
2392 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2393 selected_route[idx].update_value_and_recompute_fees(new_value);
2394 selected_route.remove(idx + 1);
2398 let mut paths = Vec::new();
2399 for payment_path in selected_route {
2400 let mut hops = Vec::with_capacity(payment_path.hops.len());
2401 for (hop, node_features) in payment_path.hops.iter()
2402 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2404 hops.push(RouteHop {
2405 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)})?,
2406 node_features: node_features.clone(),
2407 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2408 channel_features: hop.candidate.features(),
2409 fee_msat: hop.fee_msat,
2410 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2413 let mut final_cltv_delta = final_cltv_expiry_delta;
2414 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2415 if let Some(blinded_path) = h.candidate.blinded_path() {
2416 final_cltv_delta = h.candidate.cltv_expiry_delta();
2418 hops: blinded_path.blinded_hops.clone(),
2419 blinding_point: blinded_path.blinding_point,
2420 excess_final_cltv_expiry_delta: 0,
2421 final_value_msat: h.fee_msat,
2425 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2426 // applicable for the previous hop.
2427 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2428 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2431 paths.push(Path { hops, blinded_tail });
2433 // Make sure we would never create a route with more paths than we allow.
2434 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2436 if let Some(node_features) = payment_params.payee.node_features() {
2437 for path in paths.iter_mut() {
2438 path.hops.last_mut().unwrap().node_features = node_features.clone();
2442 let route = Route { paths, payment_params: Some(payment_params.clone()) };
2443 log_info!(logger, "Got route: {}", log_route!(route));
2447 // When an adversarial intermediary node observes a payment, it may be able to infer its
2448 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2449 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2450 // payment path by adding a randomized 'shadow route' offset to the final hop.
2451 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2452 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2454 let network_channels = network_graph.channels();
2455 let network_nodes = network_graph.nodes();
2457 for path in route.paths.iter_mut() {
2458 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2460 // Remember the last three nodes of the random walk and avoid looping back on them.
2461 // Init with the last three nodes from the actual path, if possible.
2462 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2463 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2464 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2466 // Choose the last publicly known node as the starting point for the random walk.
2467 let mut cur_hop: Option<NodeId> = None;
2468 let mut path_nonce = [0u8; 12];
2469 if let Some(starting_hop) = path.hops.iter().rev()
2470 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2471 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2472 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2475 // Init PRNG with the path-dependant nonce, which is static for private paths.
2476 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2477 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2479 // Pick a random path length in [1 .. 3]
2480 prng.process_in_place(&mut random_path_bytes);
2481 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2483 for random_hop in 0..random_walk_length {
2484 // If we don't find a suitable offset in the public network graph, we default to
2485 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2486 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2488 if let Some(cur_node_id) = cur_hop {
2489 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2490 // Randomly choose the next unvisited hop.
2491 prng.process_in_place(&mut random_path_bytes);
2492 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2493 .checked_rem(cur_node.channels.len())
2494 .and_then(|index| cur_node.channels.get(index))
2495 .and_then(|id| network_channels.get(id)) {
2496 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2497 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2498 nodes_to_avoid[random_hop] = *next_id;
2499 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2500 cur_hop = Some(*next_id);
2507 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2508 .checked_add(random_hop_offset)
2509 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2512 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2513 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2514 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2516 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2517 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2518 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2519 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2520 max_path_offset = cmp::max(
2521 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2522 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2523 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2525 // Add 'shadow' CLTV offset to the final hop
2526 if let Some(tail) = path.blinded_tail.as_mut() {
2527 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2528 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2530 if let Some(last_hop) = path.hops.last_mut() {
2531 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2532 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2537 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2538 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2540 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2541 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2542 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2543 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2544 ) -> Result<Route, LightningError>
2545 where L::Target: Logger, GL::Target: Logger {
2546 let graph_lock = network_graph.read_only();
2547 let mut route = build_route_from_hops_internal(
2548 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
2549 route_params.final_value_msat, logger, random_seed_bytes)?;
2550 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2554 fn build_route_from_hops_internal<L: Deref>(
2555 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
2556 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, logger: L,
2557 random_seed_bytes: &[u8; 32]
2558 ) -> Result<Route, LightningError> where L::Target: Logger {
2561 our_node_id: NodeId,
2562 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2565 impl Score for HopScorer {
2566 type ScoreParams = ();
2567 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2568 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2570 let mut cur_id = self.our_node_id;
2571 for i in 0..self.hop_ids.len() {
2572 if let Some(next_id) = self.hop_ids[i] {
2573 if cur_id == *source && next_id == *target {
2584 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
2586 fn payment_path_successful(&mut self, _path: &Path) {}
2588 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
2590 fn probe_successful(&mut self, _path: &Path) {}
2593 impl<'a> Writeable for HopScorer {
2595 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2600 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2601 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2604 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2605 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2606 for i in 0..hops.len() {
2607 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2610 let scorer = HopScorer { our_node_id, hop_ids };
2612 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
2613 logger, &scorer, &(), random_seed_bytes)
2618 use crate::blinded_path::{BlindedHop, BlindedPath};
2619 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2620 use crate::routing::utxo::UtxoResult;
2621 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2622 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2623 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
2624 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, Score, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2625 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2626 use crate::chain::transaction::OutPoint;
2627 use crate::sign::EntropySource;
2628 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2629 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2630 use crate::ln::channelmanager;
2631 use crate::offers::invoice::BlindedPayInfo;
2632 use crate::util::config::UserConfig;
2633 use crate::util::test_utils as ln_test_utils;
2634 use crate::util::chacha20::ChaCha20;
2635 use crate::util::ser::{Readable, Writeable};
2637 use crate::util::ser::Writer;
2639 use bitcoin::hashes::Hash;
2640 use bitcoin::network::constants::Network;
2641 use bitcoin::blockdata::constants::genesis_block;
2642 use bitcoin::blockdata::script::Builder;
2643 use bitcoin::blockdata::opcodes;
2644 use bitcoin::blockdata::transaction::TxOut;
2648 use bitcoin::secp256k1::{PublicKey,SecretKey};
2649 use bitcoin::secp256k1::Secp256k1;
2651 use crate::io::Cursor;
2652 use crate::prelude::*;
2653 use crate::sync::Arc;
2655 use core::convert::TryInto;
2657 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2658 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2659 channelmanager::ChannelDetails {
2660 channel_id: [0; 32],
2661 counterparty: channelmanager::ChannelCounterparty {
2664 unspendable_punishment_reserve: 0,
2665 forwarding_info: None,
2666 outbound_htlc_minimum_msat: None,
2667 outbound_htlc_maximum_msat: None,
2669 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2672 outbound_scid_alias: None,
2673 inbound_scid_alias: None,
2674 channel_value_satoshis: 0,
2677 outbound_capacity_msat,
2678 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2679 next_outbound_htlc_minimum_msat: 0,
2680 inbound_capacity_msat: 42,
2681 unspendable_punishment_reserve: None,
2682 confirmations_required: None,
2683 confirmations: None,
2684 force_close_spend_delay: None,
2685 is_outbound: true, is_channel_ready: true,
2686 is_usable: true, is_public: true,
2687 inbound_htlc_minimum_msat: None,
2688 inbound_htlc_maximum_msat: None,
2690 feerate_sat_per_1000_weight: None
2695 fn simple_route_test() {
2696 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2697 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2698 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2699 let scorer = ln_test_utils::TestScorer::new();
2700 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2701 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2703 // Simple route to 2 via 1
2705 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) {
2706 assert_eq!(err, "Cannot send a payment of 0 msat");
2707 } else { panic!(); }
2709 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2710 assert_eq!(route.paths[0].hops.len(), 2);
2712 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2713 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2714 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2715 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2716 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2717 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2719 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2720 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2721 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2722 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2723 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2724 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2728 fn invalid_first_hop_test() {
2729 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2730 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2731 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2732 let scorer = ln_test_utils::TestScorer::new();
2733 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2734 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2736 // Simple route to 2 via 1
2738 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2740 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2741 get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2742 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2743 } else { panic!(); }
2745 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2746 assert_eq!(route.paths[0].hops.len(), 2);
2750 fn htlc_minimum_test() {
2751 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2752 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2753 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2754 let scorer = ln_test_utils::TestScorer::new();
2755 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2756 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2758 // Simple route to 2 via 1
2760 // Disable other paths
2761 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2762 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2763 short_channel_id: 12,
2765 flags: 2, // to disable
2766 cltv_expiry_delta: 0,
2767 htlc_minimum_msat: 0,
2768 htlc_maximum_msat: MAX_VALUE_MSAT,
2770 fee_proportional_millionths: 0,
2771 excess_data: Vec::new()
2773 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2774 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2775 short_channel_id: 3,
2777 flags: 2, // to disable
2778 cltv_expiry_delta: 0,
2779 htlc_minimum_msat: 0,
2780 htlc_maximum_msat: MAX_VALUE_MSAT,
2782 fee_proportional_millionths: 0,
2783 excess_data: Vec::new()
2785 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2786 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2787 short_channel_id: 13,
2789 flags: 2, // to disable
2790 cltv_expiry_delta: 0,
2791 htlc_minimum_msat: 0,
2792 htlc_maximum_msat: MAX_VALUE_MSAT,
2794 fee_proportional_millionths: 0,
2795 excess_data: Vec::new()
2797 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2798 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2799 short_channel_id: 6,
2801 flags: 2, // to disable
2802 cltv_expiry_delta: 0,
2803 htlc_minimum_msat: 0,
2804 htlc_maximum_msat: MAX_VALUE_MSAT,
2806 fee_proportional_millionths: 0,
2807 excess_data: Vec::new()
2809 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2810 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2811 short_channel_id: 7,
2813 flags: 2, // to disable
2814 cltv_expiry_delta: 0,
2815 htlc_minimum_msat: 0,
2816 htlc_maximum_msat: MAX_VALUE_MSAT,
2818 fee_proportional_millionths: 0,
2819 excess_data: Vec::new()
2822 // Check against amount_to_transfer_over_msat.
2823 // Set minimal HTLC of 200_000_000 msat.
2824 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2825 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2826 short_channel_id: 2,
2829 cltv_expiry_delta: 0,
2830 htlc_minimum_msat: 200_000_000,
2831 htlc_maximum_msat: MAX_VALUE_MSAT,
2833 fee_proportional_millionths: 0,
2834 excess_data: Vec::new()
2837 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2839 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2840 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2841 short_channel_id: 4,
2844 cltv_expiry_delta: 0,
2845 htlc_minimum_msat: 0,
2846 htlc_maximum_msat: 199_999_999,
2848 fee_proportional_millionths: 0,
2849 excess_data: Vec::new()
2852 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2853 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) {
2854 assert_eq!(err, "Failed to find a path to the given destination");
2855 } else { panic!(); }
2857 // Lift the restriction on the first hop.
2858 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2859 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2860 short_channel_id: 2,
2863 cltv_expiry_delta: 0,
2864 htlc_minimum_msat: 0,
2865 htlc_maximum_msat: MAX_VALUE_MSAT,
2867 fee_proportional_millionths: 0,
2868 excess_data: Vec::new()
2871 // A payment above the minimum should pass
2872 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 199_999_999, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2873 assert_eq!(route.paths[0].hops.len(), 2);
2877 fn htlc_minimum_overpay_test() {
2878 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2879 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2880 let config = UserConfig::default();
2881 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
2882 let scorer = ln_test_utils::TestScorer::new();
2883 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2884 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2886 // A route to node#2 via two paths.
2887 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2888 // Thus, they can't send 60 without overpaying.
2889 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2890 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2891 short_channel_id: 2,
2894 cltv_expiry_delta: 0,
2895 htlc_minimum_msat: 35_000,
2896 htlc_maximum_msat: 40_000,
2898 fee_proportional_millionths: 0,
2899 excess_data: Vec::new()
2901 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2902 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2903 short_channel_id: 12,
2906 cltv_expiry_delta: 0,
2907 htlc_minimum_msat: 35_000,
2908 htlc_maximum_msat: 40_000,
2910 fee_proportional_millionths: 0,
2911 excess_data: Vec::new()
2915 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2916 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2917 short_channel_id: 13,
2920 cltv_expiry_delta: 0,
2921 htlc_minimum_msat: 0,
2922 htlc_maximum_msat: MAX_VALUE_MSAT,
2924 fee_proportional_millionths: 0,
2925 excess_data: Vec::new()
2927 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2928 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2929 short_channel_id: 4,
2932 cltv_expiry_delta: 0,
2933 htlc_minimum_msat: 0,
2934 htlc_maximum_msat: MAX_VALUE_MSAT,
2936 fee_proportional_millionths: 0,
2937 excess_data: Vec::new()
2940 // Disable other paths
2941 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2942 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2943 short_channel_id: 1,
2945 flags: 2, // to disable
2946 cltv_expiry_delta: 0,
2947 htlc_minimum_msat: 0,
2948 htlc_maximum_msat: MAX_VALUE_MSAT,
2950 fee_proportional_millionths: 0,
2951 excess_data: Vec::new()
2954 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2955 // Overpay fees to hit htlc_minimum_msat.
2956 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
2957 // TODO: this could be better balanced to overpay 10k and not 15k.
2958 assert_eq!(overpaid_fees, 15_000);
2960 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2961 // while taking even more fee to match htlc_minimum_msat.
2962 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2963 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2964 short_channel_id: 12,
2967 cltv_expiry_delta: 0,
2968 htlc_minimum_msat: 65_000,
2969 htlc_maximum_msat: 80_000,
2971 fee_proportional_millionths: 0,
2972 excess_data: Vec::new()
2974 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2975 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2976 short_channel_id: 2,
2979 cltv_expiry_delta: 0,
2980 htlc_minimum_msat: 0,
2981 htlc_maximum_msat: MAX_VALUE_MSAT,
2983 fee_proportional_millionths: 0,
2984 excess_data: Vec::new()
2986 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2987 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2988 short_channel_id: 4,
2991 cltv_expiry_delta: 0,
2992 htlc_minimum_msat: 0,
2993 htlc_maximum_msat: MAX_VALUE_MSAT,
2995 fee_proportional_millionths: 100_000,
2996 excess_data: Vec::new()
2999 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3000 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3001 assert_eq!(route.paths.len(), 1);
3002 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3003 let fees = route.paths[0].hops[0].fee_msat;
3004 assert_eq!(fees, 5_000);
3006 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3007 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3008 // the other channel.
3009 assert_eq!(route.paths.len(), 1);
3010 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3011 let fees = route.paths[0].hops[0].fee_msat;
3012 assert_eq!(fees, 5_000);
3016 fn disable_channels_test() {
3017 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3018 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3019 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3020 let scorer = ln_test_utils::TestScorer::new();
3021 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3022 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3024 // // Disable channels 4 and 12 by flags=2
3025 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3026 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3027 short_channel_id: 4,
3029 flags: 2, // to disable
3030 cltv_expiry_delta: 0,
3031 htlc_minimum_msat: 0,
3032 htlc_maximum_msat: MAX_VALUE_MSAT,
3034 fee_proportional_millionths: 0,
3035 excess_data: Vec::new()
3037 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3038 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3039 short_channel_id: 12,
3041 flags: 2, // to disable
3042 cltv_expiry_delta: 0,
3043 htlc_minimum_msat: 0,
3044 htlc_maximum_msat: MAX_VALUE_MSAT,
3046 fee_proportional_millionths: 0,
3047 excess_data: Vec::new()
3050 // If all the channels require some features we don't understand, route should fail
3051 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) {
3052 assert_eq!(err, "Failed to find a path to the given destination");
3053 } else { panic!(); }
3055 // If we specify a channel to node7, that overrides our local channel view and that gets used
3056 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3057 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();
3058 assert_eq!(route.paths[0].hops.len(), 2);
3060 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3061 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3062 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3063 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3064 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3065 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3067 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3068 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3069 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3070 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3071 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3072 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3076 fn disable_node_test() {
3077 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3078 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3079 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3080 let scorer = ln_test_utils::TestScorer::new();
3081 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3082 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3084 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3085 let mut unknown_features = NodeFeatures::empty();
3086 unknown_features.set_unknown_feature_required();
3087 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3088 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3089 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3091 // If all nodes require some features we don't understand, route should fail
3092 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) {
3093 assert_eq!(err, "Failed to find a path to the given destination");
3094 } else { panic!(); }
3096 // If we specify a channel to node7, that overrides our local channel view and that gets used
3097 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3098 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();
3099 assert_eq!(route.paths[0].hops.len(), 2);
3101 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3102 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3103 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3104 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3105 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3106 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3108 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3109 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3110 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3111 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3112 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3113 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3115 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3116 // naively) assume that the user checked the feature bits on the invoice, which override
3117 // the node_announcement.
3121 fn our_chans_test() {
3122 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3123 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3124 let scorer = ln_test_utils::TestScorer::new();
3125 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3126 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3128 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3129 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3130 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3131 assert_eq!(route.paths[0].hops.len(), 3);
3133 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3134 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3135 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3136 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3137 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3138 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3140 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3141 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3142 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3143 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3144 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3145 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3147 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3148 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3149 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3150 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3151 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3152 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3154 // If we specify a channel to node7, that overrides our local channel view and that gets used
3155 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3156 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3157 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();
3158 assert_eq!(route.paths[0].hops.len(), 2);
3160 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3161 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3162 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3163 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3164 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3165 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3167 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3168 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3169 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3170 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3171 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3172 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3175 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3176 let zero_fees = RoutingFees {
3178 proportional_millionths: 0,
3180 vec![RouteHint(vec![RouteHintHop {
3181 src_node_id: nodes[3],
3182 short_channel_id: 8,
3184 cltv_expiry_delta: (8 << 4) | 1,
3185 htlc_minimum_msat: None,
3186 htlc_maximum_msat: None,
3188 ]), RouteHint(vec![RouteHintHop {
3189 src_node_id: nodes[4],
3190 short_channel_id: 9,
3193 proportional_millionths: 0,
3195 cltv_expiry_delta: (9 << 4) | 1,
3196 htlc_minimum_msat: None,
3197 htlc_maximum_msat: None,
3198 }]), RouteHint(vec![RouteHintHop {
3199 src_node_id: nodes[5],
3200 short_channel_id: 10,
3202 cltv_expiry_delta: (10 << 4) | 1,
3203 htlc_minimum_msat: None,
3204 htlc_maximum_msat: None,
3208 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3209 let zero_fees = RoutingFees {
3211 proportional_millionths: 0,
3213 vec![RouteHint(vec![RouteHintHop {
3214 src_node_id: nodes[2],
3215 short_channel_id: 5,
3218 proportional_millionths: 0,
3220 cltv_expiry_delta: (5 << 4) | 1,
3221 htlc_minimum_msat: None,
3222 htlc_maximum_msat: None,
3224 src_node_id: nodes[3],
3225 short_channel_id: 8,
3227 cltv_expiry_delta: (8 << 4) | 1,
3228 htlc_minimum_msat: None,
3229 htlc_maximum_msat: None,
3231 ]), RouteHint(vec![RouteHintHop {
3232 src_node_id: nodes[4],
3233 short_channel_id: 9,
3236 proportional_millionths: 0,
3238 cltv_expiry_delta: (9 << 4) | 1,
3239 htlc_minimum_msat: None,
3240 htlc_maximum_msat: None,
3241 }]), RouteHint(vec![RouteHintHop {
3242 src_node_id: nodes[5],
3243 short_channel_id: 10,
3245 cltv_expiry_delta: (10 << 4) | 1,
3246 htlc_minimum_msat: None,
3247 htlc_maximum_msat: None,
3252 fn partial_route_hint_test() {
3253 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3254 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3255 let scorer = ln_test_utils::TestScorer::new();
3256 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3257 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3259 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3260 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3261 // RouteHint may be partially used by the algo to build the best path.
3263 // First check that last hop can't have its source as the payee.
3264 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3265 src_node_id: nodes[6],
3266 short_channel_id: 8,
3269 proportional_millionths: 0,
3271 cltv_expiry_delta: (8 << 4) | 1,
3272 htlc_minimum_msat: None,
3273 htlc_maximum_msat: None,
3276 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3277 invalid_last_hops.push(invalid_last_hop);
3279 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(invalid_last_hops).unwrap();
3280 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) {
3281 assert_eq!(err, "Route hint cannot have the payee as the source.");
3282 } else { panic!(); }
3285 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3286 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3287 assert_eq!(route.paths[0].hops.len(), 5);
3289 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3290 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3291 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3292 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3293 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3294 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3296 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3297 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3298 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3299 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3300 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3301 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3303 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3304 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3305 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3306 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3307 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3308 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3310 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3311 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3312 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3313 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3314 // If we have a peer in the node map, we'll use their features here since we don't have
3315 // a way of figuring out their features from the invoice:
3316 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3317 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3319 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3320 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3321 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3322 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3323 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3324 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3327 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3328 let zero_fees = RoutingFees {
3330 proportional_millionths: 0,
3332 vec![RouteHint(vec![RouteHintHop {
3333 src_node_id: nodes[3],
3334 short_channel_id: 8,
3336 cltv_expiry_delta: (8 << 4) | 1,
3337 htlc_minimum_msat: None,
3338 htlc_maximum_msat: None,
3339 }]), RouteHint(vec![
3341 ]), RouteHint(vec![RouteHintHop {
3342 src_node_id: nodes[5],
3343 short_channel_id: 10,
3345 cltv_expiry_delta: (10 << 4) | 1,
3346 htlc_minimum_msat: None,
3347 htlc_maximum_msat: None,
3352 fn ignores_empty_last_hops_test() {
3353 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3354 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3355 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3356 let scorer = ln_test_utils::TestScorer::new();
3357 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3358 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3360 // Test handling of an empty RouteHint passed in Invoice.
3362 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3363 assert_eq!(route.paths[0].hops.len(), 5);
3365 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3366 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3367 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3368 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3369 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3370 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3372 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3373 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3374 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3375 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3376 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3377 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3379 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3380 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3381 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3382 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3383 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3384 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3386 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3387 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3388 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3389 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3390 // If we have a peer in the node map, we'll use their features here since we don't have
3391 // a way of figuring out their features from the invoice:
3392 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3393 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3395 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3396 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3397 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3398 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3399 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3400 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3403 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3405 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3406 let zero_fees = RoutingFees {
3408 proportional_millionths: 0,
3410 vec![RouteHint(vec![RouteHintHop {
3411 src_node_id: hint_hops[0],
3412 short_channel_id: 0xff00,
3415 proportional_millionths: 0,
3417 cltv_expiry_delta: (5 << 4) | 1,
3418 htlc_minimum_msat: None,
3419 htlc_maximum_msat: None,
3421 src_node_id: hint_hops[1],
3422 short_channel_id: 0xff01,
3424 cltv_expiry_delta: (8 << 4) | 1,
3425 htlc_minimum_msat: None,
3426 htlc_maximum_msat: None,
3431 fn multi_hint_last_hops_test() {
3432 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3433 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3434 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3435 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3436 let scorer = ln_test_utils::TestScorer::new();
3437 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3438 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3439 // Test through channels 2, 3, 0xff00, 0xff01.
3440 // Test shows that multiple hop hints are considered.
3442 // Disabling channels 6 & 7 by flags=2
3443 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3444 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3445 short_channel_id: 6,
3447 flags: 2, // to disable
3448 cltv_expiry_delta: 0,
3449 htlc_minimum_msat: 0,
3450 htlc_maximum_msat: MAX_VALUE_MSAT,
3452 fee_proportional_millionths: 0,
3453 excess_data: Vec::new()
3455 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3456 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3457 short_channel_id: 7,
3459 flags: 2, // to disable
3460 cltv_expiry_delta: 0,
3461 htlc_minimum_msat: 0,
3462 htlc_maximum_msat: MAX_VALUE_MSAT,
3464 fee_proportional_millionths: 0,
3465 excess_data: Vec::new()
3468 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3469 assert_eq!(route.paths[0].hops.len(), 4);
3471 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3472 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3473 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3474 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3475 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3476 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3478 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3479 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3480 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3481 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3482 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3483 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3485 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3486 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3487 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3488 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3489 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3490 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3492 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3493 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3494 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3495 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3496 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3497 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3501 fn private_multi_hint_last_hops_test() {
3502 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3503 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3505 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3506 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3508 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3509 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3510 let scorer = ln_test_utils::TestScorer::new();
3511 // Test through channels 2, 3, 0xff00, 0xff01.
3512 // Test shows that multiple hop hints are considered.
3514 // Disabling channels 6 & 7 by flags=2
3515 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3516 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3517 short_channel_id: 6,
3519 flags: 2, // to disable
3520 cltv_expiry_delta: 0,
3521 htlc_minimum_msat: 0,
3522 htlc_maximum_msat: MAX_VALUE_MSAT,
3524 fee_proportional_millionths: 0,
3525 excess_data: Vec::new()
3527 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3528 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3529 short_channel_id: 7,
3531 flags: 2, // to disable
3532 cltv_expiry_delta: 0,
3533 htlc_minimum_msat: 0,
3534 htlc_maximum_msat: MAX_VALUE_MSAT,
3536 fee_proportional_millionths: 0,
3537 excess_data: Vec::new()
3540 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &[42u8; 32]).unwrap();
3541 assert_eq!(route.paths[0].hops.len(), 4);
3543 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3544 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3545 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3546 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3547 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3548 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3550 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3551 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3552 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3553 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3554 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3555 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3557 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3558 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3559 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3560 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3561 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3562 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3564 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3565 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3566 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3567 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3568 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3569 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3572 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3573 let zero_fees = RoutingFees {
3575 proportional_millionths: 0,
3577 vec![RouteHint(vec![RouteHintHop {
3578 src_node_id: nodes[4],
3579 short_channel_id: 11,
3581 cltv_expiry_delta: (11 << 4) | 1,
3582 htlc_minimum_msat: None,
3583 htlc_maximum_msat: None,
3585 src_node_id: nodes[3],
3586 short_channel_id: 8,
3588 cltv_expiry_delta: (8 << 4) | 1,
3589 htlc_minimum_msat: None,
3590 htlc_maximum_msat: None,
3591 }]), RouteHint(vec![RouteHintHop {
3592 src_node_id: nodes[4],
3593 short_channel_id: 9,
3596 proportional_millionths: 0,
3598 cltv_expiry_delta: (9 << 4) | 1,
3599 htlc_minimum_msat: None,
3600 htlc_maximum_msat: None,
3601 }]), RouteHint(vec![RouteHintHop {
3602 src_node_id: nodes[5],
3603 short_channel_id: 10,
3605 cltv_expiry_delta: (10 << 4) | 1,
3606 htlc_minimum_msat: None,
3607 htlc_maximum_msat: None,
3612 fn last_hops_with_public_channel_test() {
3613 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3614 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3615 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
3616 let scorer = ln_test_utils::TestScorer::new();
3617 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3618 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3619 // This test shows that public routes can be present in the invoice
3620 // which would be handled in the same manner.
3622 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3623 assert_eq!(route.paths[0].hops.len(), 5);
3625 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3626 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3627 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3628 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3629 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3630 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3632 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3633 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3634 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3635 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3636 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3637 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3639 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3640 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3641 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3642 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3643 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3644 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3646 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3647 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3648 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3649 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3650 // If we have a peer in the node map, we'll use their features here since we don't have
3651 // a way of figuring out their features from the invoice:
3652 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3653 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3655 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3656 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3657 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3658 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3659 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3660 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3664 fn our_chans_last_hop_connect_test() {
3665 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3666 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3667 let scorer = ln_test_utils::TestScorer::new();
3668 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3669 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3671 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3672 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3673 let mut last_hops = last_hops(&nodes);
3674 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3675 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();
3676 assert_eq!(route.paths[0].hops.len(), 2);
3678 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3679 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3680 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3681 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3682 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3683 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3685 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3686 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3687 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3688 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3689 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3690 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3692 last_hops[0].0[0].fees.base_msat = 1000;
3694 // Revert to via 6 as the fee on 8 goes up
3695 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops).unwrap();
3696 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3697 assert_eq!(route.paths[0].hops.len(), 4);
3699 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3700 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3701 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
3702 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3703 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3704 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3706 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3707 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3708 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3709 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
3710 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3711 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3713 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
3714 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3715 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3716 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3717 // If we have a peer in the node map, we'll use their features here since we don't have
3718 // a way of figuring out their features from the invoice:
3719 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3720 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3722 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3723 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3724 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3725 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3726 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3727 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3729 // ...but still use 8 for larger payments as 6 has a variable feerate
3730 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3731 assert_eq!(route.paths[0].hops.len(), 5);
3733 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3734 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3735 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3736 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3737 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3738 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3740 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3741 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3742 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3743 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3744 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3745 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3747 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3748 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3749 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3750 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3751 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3752 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3754 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3755 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3756 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
3757 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3758 // If we have a peer in the node map, we'll use their features here since we don't have
3759 // a way of figuring out their features from the invoice:
3760 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3761 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3763 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3764 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3765 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
3766 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3767 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3768 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3771 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> {
3772 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3773 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3774 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3776 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3777 let last_hops = RouteHint(vec![RouteHintHop {
3778 src_node_id: middle_node_id,
3779 short_channel_id: 8,
3782 proportional_millionths: last_hop_fee_prop,
3784 cltv_expiry_delta: (8 << 4) | 1,
3785 htlc_minimum_msat: None,
3786 htlc_maximum_msat: last_hop_htlc_max,
3788 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
3789 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3790 let scorer = ln_test_utils::TestScorer::new();
3791 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3792 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3793 let logger = ln_test_utils::TestLogger::new();
3794 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3795 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3796 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, &logger, &scorer, &(), &random_seed_bytes);
3801 fn unannounced_path_test() {
3802 // We should be able to send a payment to a destination without any help of a routing graph
3803 // if we have a channel with a common counterparty that appears in the first and last hop
3805 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3807 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3808 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3809 assert_eq!(route.paths[0].hops.len(), 2);
3811 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
3812 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3813 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
3814 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3815 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
3816 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3818 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
3819 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3820 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
3821 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3822 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3823 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3827 fn overflow_unannounced_path_test_liquidity_underflow() {
3828 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3829 // the last-hop had a fee which overflowed a u64, we'd panic.
3830 // This was due to us adding the first-hop from us unconditionally, causing us to think
3831 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3832 // In this test, we previously hit a subtraction underflow due to having less available
3833 // liquidity at the last hop than 0.
3834 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());
3838 fn overflow_unannounced_path_test_feerate_overflow() {
3839 // This tests for the same case as above, except instead of hitting a subtraction
3840 // underflow, we hit a case where the fee charged at a hop overflowed.
3841 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());
3845 fn available_amount_while_routing_test() {
3846 // Tests whether we choose the correct available channel amount while routing.
3848 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3849 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3850 let scorer = ln_test_utils::TestScorer::new();
3851 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3852 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3853 let config = UserConfig::default();
3854 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3856 // We will use a simple single-path route from
3857 // our node to node2 via node0: channels {1, 3}.
3859 // First disable all other paths.
3860 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3861 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3862 short_channel_id: 2,
3865 cltv_expiry_delta: 0,
3866 htlc_minimum_msat: 0,
3867 htlc_maximum_msat: 100_000,
3869 fee_proportional_millionths: 0,
3870 excess_data: Vec::new()
3872 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3873 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3874 short_channel_id: 12,
3877 cltv_expiry_delta: 0,
3878 htlc_minimum_msat: 0,
3879 htlc_maximum_msat: 100_000,
3881 fee_proportional_millionths: 0,
3882 excess_data: Vec::new()
3885 // Make the first channel (#1) very permissive,
3886 // and we will be testing all limits on the second channel.
3887 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3888 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3889 short_channel_id: 1,
3892 cltv_expiry_delta: 0,
3893 htlc_minimum_msat: 0,
3894 htlc_maximum_msat: 1_000_000_000,
3896 fee_proportional_millionths: 0,
3897 excess_data: Vec::new()
3900 // First, let's see if routing works if we have absolutely no idea about the available amount.
3901 // In this case, it should be set to 250_000 sats.
3902 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3903 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3904 short_channel_id: 3,
3907 cltv_expiry_delta: 0,
3908 htlc_minimum_msat: 0,
3909 htlc_maximum_msat: 250_000_000,
3911 fee_proportional_millionths: 0,
3912 excess_data: Vec::new()
3916 // Attempt to route more than available results in a failure.
3917 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3918 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3919 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3920 } else { panic!(); }
3924 // Now, attempt to route an exact amount we have should be fine.
3925 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000_000, Arc::clone(&logger), &scorer, &(),&random_seed_bytes).unwrap();
3926 assert_eq!(route.paths.len(), 1);
3927 let path = route.paths.last().unwrap();
3928 assert_eq!(path.hops.len(), 2);
3929 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3930 assert_eq!(path.final_value_msat(), 250_000_000);
3933 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3934 // Disable channel #1 and use another first hop.
3935 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3936 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3937 short_channel_id: 1,
3940 cltv_expiry_delta: 0,
3941 htlc_minimum_msat: 0,
3942 htlc_maximum_msat: 1_000_000_000,
3944 fee_proportional_millionths: 0,
3945 excess_data: Vec::new()
3948 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3949 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3952 // Attempt to route more than available results in a failure.
3953 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3954 &our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3955 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3956 } else { panic!(); }
3960 // Now, attempt to route an exact amount we have should be fine.
3961 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();
3962 assert_eq!(route.paths.len(), 1);
3963 let path = route.paths.last().unwrap();
3964 assert_eq!(path.hops.len(), 2);
3965 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3966 assert_eq!(path.final_value_msat(), 200_000_000);
3969 // Enable channel #1 back.
3970 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3971 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3972 short_channel_id: 1,
3975 cltv_expiry_delta: 0,
3976 htlc_minimum_msat: 0,
3977 htlc_maximum_msat: 1_000_000_000,
3979 fee_proportional_millionths: 0,
3980 excess_data: Vec::new()
3984 // Now let's see if routing works if we know only htlc_maximum_msat.
3985 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3986 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3987 short_channel_id: 3,
3990 cltv_expiry_delta: 0,
3991 htlc_minimum_msat: 0,
3992 htlc_maximum_msat: 15_000,
3994 fee_proportional_millionths: 0,
3995 excess_data: Vec::new()
3999 // Attempt to route more than available results in a failure.
4000 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4001 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4002 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4003 } else { panic!(); }
4007 // Now, attempt to route an exact amount we have should be fine.
4008 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4009 assert_eq!(route.paths.len(), 1);
4010 let path = route.paths.last().unwrap();
4011 assert_eq!(path.hops.len(), 2);
4012 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4013 assert_eq!(path.final_value_msat(), 15_000);
4016 // Now let's see if routing works if we know only capacity from the UTXO.
4018 // We can't change UTXO capacity on the fly, so we'll disable
4019 // the existing channel and add another one with the capacity we need.
4020 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4021 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4022 short_channel_id: 3,
4025 cltv_expiry_delta: 0,
4026 htlc_minimum_msat: 0,
4027 htlc_maximum_msat: MAX_VALUE_MSAT,
4029 fee_proportional_millionths: 0,
4030 excess_data: Vec::new()
4033 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4034 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4035 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4036 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4037 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4039 *chain_monitor.utxo_ret.lock().unwrap() =
4040 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4041 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4043 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4044 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4045 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4046 short_channel_id: 333,
4049 cltv_expiry_delta: (3 << 4) | 1,
4050 htlc_minimum_msat: 0,
4051 htlc_maximum_msat: 15_000,
4053 fee_proportional_millionths: 0,
4054 excess_data: Vec::new()
4056 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4057 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4058 short_channel_id: 333,
4061 cltv_expiry_delta: (3 << 4) | 2,
4062 htlc_minimum_msat: 0,
4063 htlc_maximum_msat: 15_000,
4065 fee_proportional_millionths: 0,
4066 excess_data: Vec::new()
4070 // Attempt to route more than available results in a failure.
4071 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4072 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4073 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4074 } else { panic!(); }
4078 // Now, attempt to route an exact amount we have should be fine.
4079 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4080 assert_eq!(route.paths.len(), 1);
4081 let path = route.paths.last().unwrap();
4082 assert_eq!(path.hops.len(), 2);
4083 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4084 assert_eq!(path.final_value_msat(), 15_000);
4087 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4088 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4089 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4090 short_channel_id: 333,
4093 cltv_expiry_delta: 0,
4094 htlc_minimum_msat: 0,
4095 htlc_maximum_msat: 10_000,
4097 fee_proportional_millionths: 0,
4098 excess_data: Vec::new()
4102 // Attempt to route more than available results in a failure.
4103 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4104 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4105 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4106 } else { panic!(); }
4110 // Now, attempt to route an exact amount we have should be fine.
4111 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4112 assert_eq!(route.paths.len(), 1);
4113 let path = route.paths.last().unwrap();
4114 assert_eq!(path.hops.len(), 2);
4115 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4116 assert_eq!(path.final_value_msat(), 10_000);
4121 fn available_liquidity_last_hop_test() {
4122 // Check that available liquidity properly limits the path even when only
4123 // one of the latter hops is limited.
4124 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4125 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4126 let scorer = ln_test_utils::TestScorer::new();
4127 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4128 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4129 let config = UserConfig::default();
4130 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4132 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4133 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4134 // Total capacity: 50 sats.
4136 // Disable other potential paths.
4137 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4138 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4139 short_channel_id: 2,
4142 cltv_expiry_delta: 0,
4143 htlc_minimum_msat: 0,
4144 htlc_maximum_msat: 100_000,
4146 fee_proportional_millionths: 0,
4147 excess_data: Vec::new()
4149 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4150 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4151 short_channel_id: 7,
4154 cltv_expiry_delta: 0,
4155 htlc_minimum_msat: 0,
4156 htlc_maximum_msat: 100_000,
4158 fee_proportional_millionths: 0,
4159 excess_data: Vec::new()
4164 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4165 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4166 short_channel_id: 12,
4169 cltv_expiry_delta: 0,
4170 htlc_minimum_msat: 0,
4171 htlc_maximum_msat: 100_000,
4173 fee_proportional_millionths: 0,
4174 excess_data: Vec::new()
4176 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4177 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4178 short_channel_id: 13,
4181 cltv_expiry_delta: 0,
4182 htlc_minimum_msat: 0,
4183 htlc_maximum_msat: 100_000,
4185 fee_proportional_millionths: 0,
4186 excess_data: Vec::new()
4189 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4190 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4191 short_channel_id: 6,
4194 cltv_expiry_delta: 0,
4195 htlc_minimum_msat: 0,
4196 htlc_maximum_msat: 50_000,
4198 fee_proportional_millionths: 0,
4199 excess_data: Vec::new()
4201 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4202 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4203 short_channel_id: 11,
4206 cltv_expiry_delta: 0,
4207 htlc_minimum_msat: 0,
4208 htlc_maximum_msat: 100_000,
4210 fee_proportional_millionths: 0,
4211 excess_data: Vec::new()
4214 // Attempt to route more than available results in a failure.
4215 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4216 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4217 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4218 } else { panic!(); }
4222 // Now, attempt to route 49 sats (just a bit below the capacity).
4223 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4224 assert_eq!(route.paths.len(), 1);
4225 let mut total_amount_paid_msat = 0;
4226 for path in &route.paths {
4227 assert_eq!(path.hops.len(), 4);
4228 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4229 total_amount_paid_msat += path.final_value_msat();
4231 assert_eq!(total_amount_paid_msat, 49_000);
4235 // Attempt to route an exact amount is also fine
4236 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4237 assert_eq!(route.paths.len(), 1);
4238 let mut total_amount_paid_msat = 0;
4239 for path in &route.paths {
4240 assert_eq!(path.hops.len(), 4);
4241 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4242 total_amount_paid_msat += path.final_value_msat();
4244 assert_eq!(total_amount_paid_msat, 50_000);
4249 fn ignore_fee_first_hop_test() {
4250 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4251 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4252 let scorer = ln_test_utils::TestScorer::new();
4253 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4254 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4255 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4257 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4258 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4259 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4260 short_channel_id: 1,
4263 cltv_expiry_delta: 0,
4264 htlc_minimum_msat: 0,
4265 htlc_maximum_msat: 100_000,
4266 fee_base_msat: 1_000_000,
4267 fee_proportional_millionths: 0,
4268 excess_data: Vec::new()
4270 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4271 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4272 short_channel_id: 3,
4275 cltv_expiry_delta: 0,
4276 htlc_minimum_msat: 0,
4277 htlc_maximum_msat: 50_000,
4279 fee_proportional_millionths: 0,
4280 excess_data: Vec::new()
4284 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4285 assert_eq!(route.paths.len(), 1);
4286 let mut total_amount_paid_msat = 0;
4287 for path in &route.paths {
4288 assert_eq!(path.hops.len(), 2);
4289 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4290 total_amount_paid_msat += path.final_value_msat();
4292 assert_eq!(total_amount_paid_msat, 50_000);
4297 fn simple_mpp_route_test() {
4298 let (secp_ctx, _, _, _, _) = build_graph();
4299 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4300 let config = UserConfig::default();
4301 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4302 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4303 do_simple_mpp_route_test(clear_payment_params);
4305 // MPP to a 1-hop blinded path for nodes[2]
4306 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
4307 let blinded_path = BlindedPath {
4308 introduction_node_id: nodes[2],
4309 blinding_point: ln_test_utils::pubkey(42),
4310 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4312 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4314 fee_proportional_millionths: 0,
4315 htlc_minimum_msat: 0,
4316 htlc_maximum_msat: 0,
4317 cltv_expiry_delta: 0,
4318 features: BlindedHopFeatures::empty(),
4320 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4321 .with_bolt12_features(bolt12_features.clone()).unwrap();
4322 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4324 // MPP to 3 2-hop blinded paths
4325 let mut blinded_path_node_0 = blinded_path.clone();
4326 blinded_path_node_0.introduction_node_id = nodes[0];
4327 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4328 let mut node_0_payinfo = blinded_payinfo.clone();
4329 node_0_payinfo.htlc_maximum_msat = 50_000;
4331 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4332 blinded_path_node_7.introduction_node_id = nodes[7];
4333 let mut node_7_payinfo = blinded_payinfo.clone();
4334 node_7_payinfo.htlc_maximum_msat = 60_000;
4336 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4337 blinded_path_node_1.introduction_node_id = nodes[1];
4338 let mut node_1_payinfo = blinded_payinfo.clone();
4339 node_1_payinfo.htlc_maximum_msat = 180_000;
4341 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4343 (node_0_payinfo, blinded_path_node_0),
4344 (node_7_payinfo, blinded_path_node_7),
4345 (node_1_payinfo, blinded_path_node_1)
4347 .with_bolt12_features(bolt12_features).unwrap();
4348 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4352 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4353 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4354 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4355 let scorer = ln_test_utils::TestScorer::new();
4356 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4357 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4359 // We need a route consisting of 3 paths:
4360 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4361 // To achieve this, the amount being transferred should be around
4362 // the total capacity of these 3 paths.
4364 // First, we set limits on these (previously unlimited) channels.
4365 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4367 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4368 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4370 short_channel_id: 1,
4373 cltv_expiry_delta: 0,
4374 htlc_minimum_msat: 0,
4375 htlc_maximum_msat: 100_000,
4377 fee_proportional_millionths: 0,
4378 excess_data: Vec::new()
4380 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4382 short_channel_id: 3,
4385 cltv_expiry_delta: 0,
4386 htlc_minimum_msat: 0,
4387 htlc_maximum_msat: 50_000,
4389 fee_proportional_millionths: 0,
4390 excess_data: Vec::new()
4393 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4394 // (total limit 60).
4395 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4396 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4397 short_channel_id: 12,
4400 cltv_expiry_delta: 0,
4401 htlc_minimum_msat: 0,
4402 htlc_maximum_msat: 60_000,
4404 fee_proportional_millionths: 0,
4405 excess_data: Vec::new()
4407 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4408 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4409 short_channel_id: 13,
4412 cltv_expiry_delta: 0,
4413 htlc_minimum_msat: 0,
4414 htlc_maximum_msat: 60_000,
4416 fee_proportional_millionths: 0,
4417 excess_data: Vec::new()
4420 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4421 // (total capacity 180 sats).
4422 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4423 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4424 short_channel_id: 2,
4427 cltv_expiry_delta: 0,
4428 htlc_minimum_msat: 0,
4429 htlc_maximum_msat: 200_000,
4431 fee_proportional_millionths: 0,
4432 excess_data: Vec::new()
4434 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4435 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4436 short_channel_id: 4,
4439 cltv_expiry_delta: 0,
4440 htlc_minimum_msat: 0,
4441 htlc_maximum_msat: 180_000,
4443 fee_proportional_millionths: 0,
4444 excess_data: Vec::new()
4448 // Attempt to route more than available results in a failure.
4449 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4450 &our_id, &payment_params, &network_graph.read_only(), None, 300_000,
4451 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4452 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4453 } else { panic!(); }
4457 // Attempt to route while setting max_path_count to 0 results in a failure.
4458 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4459 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4460 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100,
4461 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4462 assert_eq!(err, "Can't find a route with no paths allowed.");
4463 } else { panic!(); }
4467 // Attempt to route while setting max_path_count to 3 results in a failure.
4468 // This is the case because the minimal_value_contribution_msat would require each path
4469 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4470 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4471 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4472 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000,
4473 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4474 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4475 } else { panic!(); }
4479 // Now, attempt to route 250 sats (just a bit below the capacity).
4480 // Our algorithm should provide us with these 3 paths.
4481 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4482 250_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4483 assert_eq!(route.paths.len(), 3);
4484 let mut total_amount_paid_msat = 0;
4485 for path in &route.paths {
4486 if let Some(bt) = &path.blinded_tail {
4487 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4489 assert_eq!(path.hops.len(), 2);
4490 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4492 total_amount_paid_msat += path.final_value_msat();
4494 assert_eq!(total_amount_paid_msat, 250_000);
4498 // Attempt to route an exact amount is also fine
4499 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4500 290_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4501 assert_eq!(route.paths.len(), 3);
4502 let mut total_amount_paid_msat = 0;
4503 for path in &route.paths {
4504 if payment_params.payee.blinded_route_hints().len() != 0 {
4505 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
4506 if let Some(bt) = &path.blinded_tail {
4507 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4508 if bt.hops.len() > 1 {
4509 assert_eq!(path.hops.last().unwrap().pubkey,
4510 payment_params.payee.blinded_route_hints().iter()
4511 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
4512 .map(|(_, p)| p.introduction_node_id).unwrap());
4514 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4517 assert_eq!(path.hops.len(), 2);
4518 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4520 total_amount_paid_msat += path.final_value_msat();
4522 assert_eq!(total_amount_paid_msat, 290_000);
4527 fn long_mpp_route_test() {
4528 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4529 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4530 let scorer = ln_test_utils::TestScorer::new();
4531 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4532 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4533 let config = UserConfig::default();
4534 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4536 // We need a route consisting of 3 paths:
4537 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4538 // Note that these paths overlap (channels 5, 12, 13).
4539 // We will route 300 sats.
4540 // Each path will have 100 sats capacity, those channels which
4541 // are used twice will have 200 sats capacity.
4543 // Disable other potential paths.
4544 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4545 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4546 short_channel_id: 2,
4549 cltv_expiry_delta: 0,
4550 htlc_minimum_msat: 0,
4551 htlc_maximum_msat: 100_000,
4553 fee_proportional_millionths: 0,
4554 excess_data: Vec::new()
4556 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4557 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4558 short_channel_id: 7,
4561 cltv_expiry_delta: 0,
4562 htlc_minimum_msat: 0,
4563 htlc_maximum_msat: 100_000,
4565 fee_proportional_millionths: 0,
4566 excess_data: Vec::new()
4569 // Path via {node0, node2} is channels {1, 3, 5}.
4570 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4571 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4572 short_channel_id: 1,
4575 cltv_expiry_delta: 0,
4576 htlc_minimum_msat: 0,
4577 htlc_maximum_msat: 100_000,
4579 fee_proportional_millionths: 0,
4580 excess_data: Vec::new()
4582 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4583 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4584 short_channel_id: 3,
4587 cltv_expiry_delta: 0,
4588 htlc_minimum_msat: 0,
4589 htlc_maximum_msat: 100_000,
4591 fee_proportional_millionths: 0,
4592 excess_data: Vec::new()
4595 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4596 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4597 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4598 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4599 short_channel_id: 5,
4602 cltv_expiry_delta: 0,
4603 htlc_minimum_msat: 0,
4604 htlc_maximum_msat: 200_000,
4606 fee_proportional_millionths: 0,
4607 excess_data: Vec::new()
4610 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4611 // Add 100 sats to the capacities of {12, 13}, because these channels
4612 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4613 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4614 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4615 short_channel_id: 12,
4618 cltv_expiry_delta: 0,
4619 htlc_minimum_msat: 0,
4620 htlc_maximum_msat: 200_000,
4622 fee_proportional_millionths: 0,
4623 excess_data: Vec::new()
4625 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4626 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4627 short_channel_id: 13,
4630 cltv_expiry_delta: 0,
4631 htlc_minimum_msat: 0,
4632 htlc_maximum_msat: 200_000,
4634 fee_proportional_millionths: 0,
4635 excess_data: Vec::new()
4638 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4639 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4640 short_channel_id: 6,
4643 cltv_expiry_delta: 0,
4644 htlc_minimum_msat: 0,
4645 htlc_maximum_msat: 100_000,
4647 fee_proportional_millionths: 0,
4648 excess_data: Vec::new()
4650 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4651 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4652 short_channel_id: 11,
4655 cltv_expiry_delta: 0,
4656 htlc_minimum_msat: 0,
4657 htlc_maximum_msat: 100_000,
4659 fee_proportional_millionths: 0,
4660 excess_data: Vec::new()
4663 // Path via {node7, node2} is channels {12, 13, 5}.
4664 // We already limited them to 200 sats (they are used twice for 100 sats).
4665 // Nothing to do here.
4668 // Attempt to route more than available results in a failure.
4669 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4670 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4671 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4672 } else { panic!(); }
4676 // Now, attempt to route 300 sats (exact amount we can route).
4677 // Our algorithm should provide us with these 3 paths, 100 sats each.
4678 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4679 assert_eq!(route.paths.len(), 3);
4681 let mut total_amount_paid_msat = 0;
4682 for path in &route.paths {
4683 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4684 total_amount_paid_msat += path.final_value_msat();
4686 assert_eq!(total_amount_paid_msat, 300_000);
4692 fn mpp_cheaper_route_test() {
4693 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4694 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4695 let scorer = ln_test_utils::TestScorer::new();
4696 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4697 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4698 let config = UserConfig::default();
4699 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4701 // This test checks that if we have two cheaper paths and one more expensive path,
4702 // so that liquidity-wise any 2 of 3 combination is sufficient,
4703 // two cheaper paths will be taken.
4704 // These paths have equal available liquidity.
4706 // We need a combination of 3 paths:
4707 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4708 // Note that these paths overlap (channels 5, 12, 13).
4709 // Each path will have 100 sats capacity, those channels which
4710 // are used twice will have 200 sats capacity.
4712 // Disable other potential paths.
4713 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4714 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4715 short_channel_id: 2,
4718 cltv_expiry_delta: 0,
4719 htlc_minimum_msat: 0,
4720 htlc_maximum_msat: 100_000,
4722 fee_proportional_millionths: 0,
4723 excess_data: Vec::new()
4725 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4726 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4727 short_channel_id: 7,
4730 cltv_expiry_delta: 0,
4731 htlc_minimum_msat: 0,
4732 htlc_maximum_msat: 100_000,
4734 fee_proportional_millionths: 0,
4735 excess_data: Vec::new()
4738 // Path via {node0, node2} is channels {1, 3, 5}.
4739 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4740 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4741 short_channel_id: 1,
4744 cltv_expiry_delta: 0,
4745 htlc_minimum_msat: 0,
4746 htlc_maximum_msat: 100_000,
4748 fee_proportional_millionths: 0,
4749 excess_data: Vec::new()
4751 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4752 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4753 short_channel_id: 3,
4756 cltv_expiry_delta: 0,
4757 htlc_minimum_msat: 0,
4758 htlc_maximum_msat: 100_000,
4760 fee_proportional_millionths: 0,
4761 excess_data: Vec::new()
4764 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4765 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4766 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4767 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4768 short_channel_id: 5,
4771 cltv_expiry_delta: 0,
4772 htlc_minimum_msat: 0,
4773 htlc_maximum_msat: 200_000,
4775 fee_proportional_millionths: 0,
4776 excess_data: Vec::new()
4779 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4780 // Add 100 sats to the capacities of {12, 13}, because these channels
4781 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4782 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4783 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4784 short_channel_id: 12,
4787 cltv_expiry_delta: 0,
4788 htlc_minimum_msat: 0,
4789 htlc_maximum_msat: 200_000,
4791 fee_proportional_millionths: 0,
4792 excess_data: Vec::new()
4794 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4795 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4796 short_channel_id: 13,
4799 cltv_expiry_delta: 0,
4800 htlc_minimum_msat: 0,
4801 htlc_maximum_msat: 200_000,
4803 fee_proportional_millionths: 0,
4804 excess_data: Vec::new()
4807 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4808 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4809 short_channel_id: 6,
4812 cltv_expiry_delta: 0,
4813 htlc_minimum_msat: 0,
4814 htlc_maximum_msat: 100_000,
4815 fee_base_msat: 1_000,
4816 fee_proportional_millionths: 0,
4817 excess_data: Vec::new()
4819 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4820 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4821 short_channel_id: 11,
4824 cltv_expiry_delta: 0,
4825 htlc_minimum_msat: 0,
4826 htlc_maximum_msat: 100_000,
4828 fee_proportional_millionths: 0,
4829 excess_data: Vec::new()
4832 // Path via {node7, node2} is channels {12, 13, 5}.
4833 // We already limited them to 200 sats (they are used twice for 100 sats).
4834 // Nothing to do here.
4837 // Now, attempt to route 180 sats.
4838 // Our algorithm should provide us with these 2 paths.
4839 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4840 assert_eq!(route.paths.len(), 2);
4842 let mut total_value_transferred_msat = 0;
4843 let mut total_paid_msat = 0;
4844 for path in &route.paths {
4845 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4846 total_value_transferred_msat += path.final_value_msat();
4847 for hop in &path.hops {
4848 total_paid_msat += hop.fee_msat;
4851 // If we paid fee, this would be higher.
4852 assert_eq!(total_value_transferred_msat, 180_000);
4853 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4854 assert_eq!(total_fees_paid, 0);
4859 fn fees_on_mpp_route_test() {
4860 // This test makes sure that MPP algorithm properly takes into account
4861 // fees charged on the channels, by making the fees impactful:
4862 // if the fee is not properly accounted for, the behavior is different.
4863 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4864 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4865 let scorer = ln_test_utils::TestScorer::new();
4866 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4867 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4868 let config = UserConfig::default();
4869 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4871 // We need a route consisting of 2 paths:
4872 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4873 // We will route 200 sats, Each path will have 100 sats capacity.
4875 // This test is not particularly stable: e.g.,
4876 // there's a way to route via {node0, node2, node4}.
4877 // It works while pathfinding is deterministic, but can be broken otherwise.
4878 // It's fine to ignore this concern for now.
4880 // Disable other potential paths.
4881 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4882 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4883 short_channel_id: 2,
4886 cltv_expiry_delta: 0,
4887 htlc_minimum_msat: 0,
4888 htlc_maximum_msat: 100_000,
4890 fee_proportional_millionths: 0,
4891 excess_data: Vec::new()
4894 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4895 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4896 short_channel_id: 7,
4899 cltv_expiry_delta: 0,
4900 htlc_minimum_msat: 0,
4901 htlc_maximum_msat: 100_000,
4903 fee_proportional_millionths: 0,
4904 excess_data: Vec::new()
4907 // Path via {node0, node2} is channels {1, 3, 5}.
4908 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4909 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4910 short_channel_id: 1,
4913 cltv_expiry_delta: 0,
4914 htlc_minimum_msat: 0,
4915 htlc_maximum_msat: 100_000,
4917 fee_proportional_millionths: 0,
4918 excess_data: Vec::new()
4920 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4921 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4922 short_channel_id: 3,
4925 cltv_expiry_delta: 0,
4926 htlc_minimum_msat: 0,
4927 htlc_maximum_msat: 100_000,
4929 fee_proportional_millionths: 0,
4930 excess_data: Vec::new()
4933 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4934 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4935 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4936 short_channel_id: 5,
4939 cltv_expiry_delta: 0,
4940 htlc_minimum_msat: 0,
4941 htlc_maximum_msat: 100_000,
4943 fee_proportional_millionths: 0,
4944 excess_data: Vec::new()
4947 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4948 // All channels should be 100 sats capacity. But for the fee experiment,
4949 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4950 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4951 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4952 // so no matter how large are other channels,
4953 // the whole path will be limited by 100 sats with just these 2 conditions:
4954 // - channel 12 capacity is 250 sats
4955 // - fee for channel 6 is 150 sats
4956 // Let's test this by enforcing these 2 conditions and removing other limits.
4957 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4958 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4959 short_channel_id: 12,
4962 cltv_expiry_delta: 0,
4963 htlc_minimum_msat: 0,
4964 htlc_maximum_msat: 250_000,
4966 fee_proportional_millionths: 0,
4967 excess_data: Vec::new()
4969 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4970 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4971 short_channel_id: 13,
4974 cltv_expiry_delta: 0,
4975 htlc_minimum_msat: 0,
4976 htlc_maximum_msat: MAX_VALUE_MSAT,
4978 fee_proportional_millionths: 0,
4979 excess_data: Vec::new()
4982 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4983 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4984 short_channel_id: 6,
4987 cltv_expiry_delta: 0,
4988 htlc_minimum_msat: 0,
4989 htlc_maximum_msat: MAX_VALUE_MSAT,
4990 fee_base_msat: 150_000,
4991 fee_proportional_millionths: 0,
4992 excess_data: Vec::new()
4994 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4995 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4996 short_channel_id: 11,
4999 cltv_expiry_delta: 0,
5000 htlc_minimum_msat: 0,
5001 htlc_maximum_msat: MAX_VALUE_MSAT,
5003 fee_proportional_millionths: 0,
5004 excess_data: Vec::new()
5008 // Attempt to route more than available results in a failure.
5009 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5010 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5011 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5012 } else { panic!(); }
5016 // Now, attempt to route 200 sats (exact amount we can route).
5017 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5018 assert_eq!(route.paths.len(), 2);
5020 let mut total_amount_paid_msat = 0;
5021 for path in &route.paths {
5022 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5023 total_amount_paid_msat += path.final_value_msat();
5025 assert_eq!(total_amount_paid_msat, 200_000);
5026 assert_eq!(route.get_total_fees(), 150_000);
5031 fn mpp_with_last_hops() {
5032 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5033 // via a single last-hop route hint, we'd fail to route if we first collected routes
5034 // totaling close but not quite enough to fund the full payment.
5036 // This was because we considered last-hop hints to have exactly the sought payment amount
5037 // instead of the amount we were trying to collect, needlessly limiting our path searching
5038 // at the very first hop.
5040 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5041 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5042 // to only have the remaining to-collect amount in available liquidity.
5044 // This bug appeared in production in some specific channel configurations.
5045 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5046 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5047 let scorer = ln_test_utils::TestScorer::new();
5048 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5049 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5050 let config = UserConfig::default();
5051 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5052 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5053 src_node_id: nodes[2],
5054 short_channel_id: 42,
5055 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5056 cltv_expiry_delta: 42,
5057 htlc_minimum_msat: None,
5058 htlc_maximum_msat: None,
5059 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5061 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5062 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5063 // would first use the no-fee route and then fail to find a path along the second route as
5064 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5065 // under 5% of our payment amount.
5066 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5067 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5068 short_channel_id: 1,
5071 cltv_expiry_delta: (5 << 4) | 5,
5072 htlc_minimum_msat: 0,
5073 htlc_maximum_msat: 99_000,
5074 fee_base_msat: u32::max_value(),
5075 fee_proportional_millionths: u32::max_value(),
5076 excess_data: Vec::new()
5078 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5079 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5080 short_channel_id: 2,
5083 cltv_expiry_delta: (5 << 4) | 3,
5084 htlc_minimum_msat: 0,
5085 htlc_maximum_msat: 99_000,
5086 fee_base_msat: u32::max_value(),
5087 fee_proportional_millionths: u32::max_value(),
5088 excess_data: Vec::new()
5090 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5091 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5092 short_channel_id: 4,
5095 cltv_expiry_delta: (4 << 4) | 1,
5096 htlc_minimum_msat: 0,
5097 htlc_maximum_msat: MAX_VALUE_MSAT,
5099 fee_proportional_millionths: 0,
5100 excess_data: Vec::new()
5102 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5103 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5104 short_channel_id: 13,
5106 flags: 0|2, // Channel disabled
5107 cltv_expiry_delta: (13 << 4) | 1,
5108 htlc_minimum_msat: 0,
5109 htlc_maximum_msat: MAX_VALUE_MSAT,
5111 fee_proportional_millionths: 2000000,
5112 excess_data: Vec::new()
5115 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5117 let mut route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5118 assert_eq!(route.paths.len(), 2);
5119 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5120 // Paths are manually ordered ordered by SCID, so:
5121 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5122 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5123 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5124 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5125 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5126 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5127 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5128 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5129 assert_eq!(route.get_total_fees(), 1);
5130 assert_eq!(route.get_total_amount(), 100_000);
5134 fn drop_lowest_channel_mpp_route_test() {
5135 // This test checks that low-capacity channel is dropped when after
5136 // path finding we realize that we found more capacity than we need.
5137 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5138 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5139 let scorer = ln_test_utils::TestScorer::new();
5140 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5141 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5142 let config = UserConfig::default();
5143 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5144 .with_max_channel_saturation_power_of_half(0);
5146 // We need a route consisting of 3 paths:
5147 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5149 // The first and the second paths should be sufficient, but the third should be
5150 // cheaper, so that we select it but drop later.
5152 // First, we set limits on these (previously unlimited) channels.
5153 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5155 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5156 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5157 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5158 short_channel_id: 1,
5161 cltv_expiry_delta: 0,
5162 htlc_minimum_msat: 0,
5163 htlc_maximum_msat: 100_000,
5165 fee_proportional_millionths: 0,
5166 excess_data: Vec::new()
5168 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5169 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5170 short_channel_id: 3,
5173 cltv_expiry_delta: 0,
5174 htlc_minimum_msat: 0,
5175 htlc_maximum_msat: 50_000,
5177 fee_proportional_millionths: 0,
5178 excess_data: Vec::new()
5181 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5182 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5183 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5184 short_channel_id: 12,
5187 cltv_expiry_delta: 0,
5188 htlc_minimum_msat: 0,
5189 htlc_maximum_msat: 60_000,
5191 fee_proportional_millionths: 0,
5192 excess_data: Vec::new()
5194 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5195 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5196 short_channel_id: 13,
5199 cltv_expiry_delta: 0,
5200 htlc_minimum_msat: 0,
5201 htlc_maximum_msat: 60_000,
5203 fee_proportional_millionths: 0,
5204 excess_data: Vec::new()
5207 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5208 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5209 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5210 short_channel_id: 2,
5213 cltv_expiry_delta: 0,
5214 htlc_minimum_msat: 0,
5215 htlc_maximum_msat: 20_000,
5217 fee_proportional_millionths: 0,
5218 excess_data: Vec::new()
5220 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5221 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5222 short_channel_id: 4,
5225 cltv_expiry_delta: 0,
5226 htlc_minimum_msat: 0,
5227 htlc_maximum_msat: 20_000,
5229 fee_proportional_millionths: 0,
5230 excess_data: Vec::new()
5234 // Attempt to route more than available results in a failure.
5235 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5236 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5237 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5238 } else { panic!(); }
5242 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5243 // Our algorithm should provide us with these 3 paths.
5244 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5245 assert_eq!(route.paths.len(), 3);
5246 let mut total_amount_paid_msat = 0;
5247 for path in &route.paths {
5248 assert_eq!(path.hops.len(), 2);
5249 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5250 total_amount_paid_msat += path.final_value_msat();
5252 assert_eq!(total_amount_paid_msat, 125_000);
5256 // Attempt to route without the last small cheap channel
5257 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5258 assert_eq!(route.paths.len(), 2);
5259 let mut total_amount_paid_msat = 0;
5260 for path in &route.paths {
5261 assert_eq!(path.hops.len(), 2);
5262 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5263 total_amount_paid_msat += path.final_value_msat();
5265 assert_eq!(total_amount_paid_msat, 90_000);
5270 fn min_criteria_consistency() {
5271 // Test that we don't use an inconsistent metric between updating and walking nodes during
5272 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5273 // was updated with a different criterion from the heap sorting, resulting in loops in
5274 // calculated paths. We test for that specific case here.
5276 // We construct a network that looks like this:
5278 // node2 -1(3)2- node3
5282 // node1 -1(5)2- node4 -1(1)2- node6
5288 // We create a loop on the side of our real path - our destination is node 6, with a
5289 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5290 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5291 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5292 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5293 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5294 // "previous hop" being set to node 3, creating a loop in the path.
5295 let secp_ctx = Secp256k1::new();
5296 let logger = Arc::new(ln_test_utils::TestLogger::new());
5297 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5298 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5299 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5300 let scorer = ln_test_utils::TestScorer::new();
5301 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5302 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5303 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5305 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5306 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5307 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5308 short_channel_id: 6,
5311 cltv_expiry_delta: (6 << 4) | 0,
5312 htlc_minimum_msat: 0,
5313 htlc_maximum_msat: MAX_VALUE_MSAT,
5315 fee_proportional_millionths: 0,
5316 excess_data: Vec::new()
5318 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5320 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5321 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5322 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5323 short_channel_id: 5,
5326 cltv_expiry_delta: (5 << 4) | 0,
5327 htlc_minimum_msat: 0,
5328 htlc_maximum_msat: MAX_VALUE_MSAT,
5330 fee_proportional_millionths: 0,
5331 excess_data: Vec::new()
5333 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5335 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5336 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5337 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5338 short_channel_id: 4,
5341 cltv_expiry_delta: (4 << 4) | 0,
5342 htlc_minimum_msat: 0,
5343 htlc_maximum_msat: MAX_VALUE_MSAT,
5345 fee_proportional_millionths: 0,
5346 excess_data: Vec::new()
5348 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5350 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5351 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5352 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5353 short_channel_id: 3,
5356 cltv_expiry_delta: (3 << 4) | 0,
5357 htlc_minimum_msat: 0,
5358 htlc_maximum_msat: MAX_VALUE_MSAT,
5360 fee_proportional_millionths: 0,
5361 excess_data: Vec::new()
5363 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5365 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5366 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5367 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5368 short_channel_id: 2,
5371 cltv_expiry_delta: (2 << 4) | 0,
5372 htlc_minimum_msat: 0,
5373 htlc_maximum_msat: MAX_VALUE_MSAT,
5375 fee_proportional_millionths: 0,
5376 excess_data: Vec::new()
5379 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5380 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5382 short_channel_id: 1,
5385 cltv_expiry_delta: (1 << 4) | 0,
5386 htlc_minimum_msat: 100,
5387 htlc_maximum_msat: MAX_VALUE_MSAT,
5389 fee_proportional_millionths: 0,
5390 excess_data: Vec::new()
5392 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5395 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5396 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5397 assert_eq!(route.paths.len(), 1);
5398 assert_eq!(route.paths[0].hops.len(), 3);
5400 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5401 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5402 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5403 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5404 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5405 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5407 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5408 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5409 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5410 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5411 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5412 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5414 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5415 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5416 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5417 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5418 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5419 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5425 fn exact_fee_liquidity_limit() {
5426 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5427 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5428 // we calculated fees on a higher value, resulting in us ignoring such paths.
5429 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5430 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5431 let scorer = ln_test_utils::TestScorer::new();
5432 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5433 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5434 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5436 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5438 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5439 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5440 short_channel_id: 2,
5443 cltv_expiry_delta: 0,
5444 htlc_minimum_msat: 0,
5445 htlc_maximum_msat: 85_000,
5447 fee_proportional_millionths: 0,
5448 excess_data: Vec::new()
5451 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5452 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5453 short_channel_id: 12,
5456 cltv_expiry_delta: (4 << 4) | 1,
5457 htlc_minimum_msat: 0,
5458 htlc_maximum_msat: 270_000,
5460 fee_proportional_millionths: 1000000,
5461 excess_data: Vec::new()
5465 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5466 // 200% fee charged channel 13 in the 1-to-2 direction.
5467 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5468 assert_eq!(route.paths.len(), 1);
5469 assert_eq!(route.paths[0].hops.len(), 2);
5471 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5472 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5473 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5474 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5475 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5476 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5478 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5479 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5480 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5481 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5482 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5483 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5488 fn htlc_max_reduction_below_min() {
5489 // Test that if, while walking the graph, we reduce the value being sent to meet an
5490 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5491 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5492 // resulting in us thinking there is no possible path, even if other paths exist.
5493 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5494 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5495 let scorer = ln_test_utils::TestScorer::new();
5496 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5497 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5498 let config = UserConfig::default();
5499 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5501 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5502 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5503 // then try to send 90_000.
5504 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5505 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5506 short_channel_id: 2,
5509 cltv_expiry_delta: 0,
5510 htlc_minimum_msat: 0,
5511 htlc_maximum_msat: 80_000,
5513 fee_proportional_millionths: 0,
5514 excess_data: Vec::new()
5516 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5517 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5518 short_channel_id: 4,
5521 cltv_expiry_delta: (4 << 4) | 1,
5522 htlc_minimum_msat: 90_000,
5523 htlc_maximum_msat: MAX_VALUE_MSAT,
5525 fee_proportional_millionths: 0,
5526 excess_data: Vec::new()
5530 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5531 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5532 // expensive) channels 12-13 path.
5533 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5534 assert_eq!(route.paths.len(), 1);
5535 assert_eq!(route.paths[0].hops.len(), 2);
5537 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5538 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5539 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5540 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5541 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5542 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5544 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5545 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5546 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5547 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5548 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5549 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5554 fn multiple_direct_first_hops() {
5555 // Previously we'd only ever considered one first hop path per counterparty.
5556 // However, as we don't restrict users to one channel per peer, we really need to support
5557 // looking at all first hop paths.
5558 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5559 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5560 // route over multiple channels with the same first hop.
5561 let secp_ctx = Secp256k1::new();
5562 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5563 let logger = Arc::new(ln_test_utils::TestLogger::new());
5564 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5565 let scorer = ln_test_utils::TestScorer::new();
5566 let config = UserConfig::default();
5567 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5568 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5569 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5572 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5573 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5574 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5575 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5576 assert_eq!(route.paths.len(), 1);
5577 assert_eq!(route.paths[0].hops.len(), 1);
5579 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5580 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5581 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5584 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5585 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5586 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5587 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5588 assert_eq!(route.paths.len(), 2);
5589 assert_eq!(route.paths[0].hops.len(), 1);
5590 assert_eq!(route.paths[1].hops.len(), 1);
5592 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5593 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5595 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5596 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5598 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5599 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5603 // If we have a bunch of outbound channels to the same node, where most are not
5604 // sufficient to pay the full payment, but one is, we should default to just using the
5605 // one single channel that has sufficient balance, avoiding MPP.
5607 // If we have several options above the 3xpayment value threshold, we should pick the
5608 // smallest of them, avoiding further fragmenting our available outbound balance to
5610 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5611 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5612 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5613 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5614 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5615 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5616 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5617 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5618 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5619 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5620 assert_eq!(route.paths.len(), 1);
5621 assert_eq!(route.paths[0].hops.len(), 1);
5623 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5624 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5625 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5630 fn prefers_shorter_route_with_higher_fees() {
5631 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5632 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5633 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5635 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5636 let scorer = ln_test_utils::TestScorer::new();
5637 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5638 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5639 let route = get_route(
5640 &our_id, &payment_params, &network_graph.read_only(), None, 100,
5641 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5643 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5645 assert_eq!(route.get_total_fees(), 100);
5646 assert_eq!(route.get_total_amount(), 100);
5647 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5649 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5650 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5651 let scorer = FixedPenaltyScorer::with_penalty(100);
5652 let route = get_route(
5653 &our_id, &payment_params, &network_graph.read_only(), None, 100,
5654 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5656 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5658 assert_eq!(route.get_total_fees(), 300);
5659 assert_eq!(route.get_total_amount(), 100);
5660 assert_eq!(path, vec![2, 4, 7, 10]);
5663 struct BadChannelScorer {
5664 short_channel_id: u64,
5668 impl Writeable for BadChannelScorer {
5669 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5671 impl Score for BadChannelScorer {
5672 type ScoreParams = ();
5673 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5674 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5677 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5678 fn payment_path_successful(&mut self, _path: &Path) {}
5679 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5680 fn probe_successful(&mut self, _path: &Path) {}
5683 struct BadNodeScorer {
5688 impl Writeable for BadNodeScorer {
5689 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5692 impl Score for BadNodeScorer {
5693 type ScoreParams = ();
5694 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5695 if *target == self.node_id { u64::max_value() } else { 0 }
5698 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5699 fn payment_path_successful(&mut self, _path: &Path) {}
5700 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5701 fn probe_successful(&mut self, _path: &Path) {}
5705 fn avoids_routing_through_bad_channels_and_nodes() {
5706 let (secp_ctx, network, _, _, logger) = build_graph();
5707 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5708 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5709 let network_graph = network.read_only();
5711 // A path to nodes[6] exists when no penalties are applied to any channel.
5712 let scorer = ln_test_utils::TestScorer::new();
5713 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5714 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5715 let route = get_route(
5716 &our_id, &payment_params, &network_graph, None, 100,
5717 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5719 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5721 assert_eq!(route.get_total_fees(), 100);
5722 assert_eq!(route.get_total_amount(), 100);
5723 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5725 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5726 let scorer = BadChannelScorer { short_channel_id: 6 };
5727 let route = get_route(
5728 &our_id, &payment_params, &network_graph, None, 100,
5729 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5731 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5733 assert_eq!(route.get_total_fees(), 300);
5734 assert_eq!(route.get_total_amount(), 100);
5735 assert_eq!(path, vec![2, 4, 7, 10]);
5737 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5738 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5740 &our_id, &payment_params, &network_graph, None, 100,
5741 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5743 Err(LightningError { err, .. } ) => {
5744 assert_eq!(err, "Failed to find a path to the given destination");
5746 Ok(_) => panic!("Expected error"),
5751 fn total_fees_single_path() {
5753 paths: vec![Path { hops: vec![
5755 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5756 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5757 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5760 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5761 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5762 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5765 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5766 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5767 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5769 ], blinded_tail: None }],
5770 payment_params: None,
5773 assert_eq!(route.get_total_fees(), 250);
5774 assert_eq!(route.get_total_amount(), 225);
5778 fn total_fees_multi_path() {
5780 paths: vec![Path { hops: vec![
5782 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5783 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5784 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5787 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5788 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5789 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5791 ], blinded_tail: None }, Path { hops: vec![
5793 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5794 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5795 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5798 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5799 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5800 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5802 ], blinded_tail: None }],
5803 payment_params: None,
5806 assert_eq!(route.get_total_fees(), 200);
5807 assert_eq!(route.get_total_amount(), 300);
5811 fn total_empty_route_no_panic() {
5812 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5813 // would both panic if the route was completely empty. We test to ensure they return 0
5814 // here, even though its somewhat nonsensical as a route.
5815 let route = Route { paths: Vec::new(), payment_params: None };
5817 assert_eq!(route.get_total_fees(), 0);
5818 assert_eq!(route.get_total_amount(), 0);
5822 fn limits_total_cltv_delta() {
5823 let (secp_ctx, network, _, _, logger) = build_graph();
5824 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5825 let network_graph = network.read_only();
5827 let scorer = ln_test_utils::TestScorer::new();
5829 // Make sure that generally there is at least one route available
5830 let feasible_max_total_cltv_delta = 1008;
5831 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5832 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5833 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5834 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5835 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5836 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5837 assert_ne!(path.len(), 0);
5839 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5840 let fail_max_total_cltv_delta = 23;
5841 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5842 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5843 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5845 Err(LightningError { err, .. } ) => {
5846 assert_eq!(err, "Failed to find a path to the given destination");
5848 Ok(_) => panic!("Expected error"),
5853 fn avoids_recently_failed_paths() {
5854 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5855 // randomly inserting channels into it until we can't find a route anymore.
5856 let (secp_ctx, network, _, _, logger) = build_graph();
5857 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5858 let network_graph = network.read_only();
5860 let scorer = ln_test_utils::TestScorer::new();
5861 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5862 .with_max_path_count(1);
5863 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5864 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5866 // We should be able to find a route initially, and then after we fail a few random
5867 // channels eventually we won't be able to any longer.
5868 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).is_ok());
5870 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5871 for chan in route.paths[0].hops.iter() {
5872 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5874 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5875 % route.paths[0].hops.len();
5876 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
5882 fn limits_path_length() {
5883 let (secp_ctx, network, _, _, logger) = build_line_graph();
5884 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5885 let network_graph = network.read_only();
5887 let scorer = ln_test_utils::TestScorer::new();
5888 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5889 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5891 // First check we can actually create a long route on this graph.
5892 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
5893 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100,
5894 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5895 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5896 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5898 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5899 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
5900 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100,
5901 Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5903 Err(LightningError { err, .. } ) => {
5904 assert_eq!(err, "Failed to find a path to the given destination");
5906 Ok(_) => panic!("Expected error"),
5911 fn adds_and_limits_cltv_offset() {
5912 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5913 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5915 let scorer = ln_test_utils::TestScorer::new();
5917 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5918 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5919 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5920 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5921 assert_eq!(route.paths.len(), 1);
5923 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5925 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5926 let mut route_default = route.clone();
5927 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5928 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5929 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5930 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5931 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5933 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5934 let mut route_limited = route.clone();
5935 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5936 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5937 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5938 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5939 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5943 fn adds_plausible_cltv_offset() {
5944 let (secp_ctx, network, _, _, logger) = build_graph();
5945 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5946 let network_graph = network.read_only();
5947 let network_nodes = network_graph.nodes();
5948 let network_channels = network_graph.channels();
5949 let scorer = ln_test_utils::TestScorer::new();
5950 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5951 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5952 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5954 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100,
5955 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5956 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5958 let mut path_plausibility = vec![];
5960 for p in route.paths {
5961 // 1. Select random observation point
5962 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5963 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5965 prng.process_in_place(&mut random_bytes);
5966 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
5967 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
5969 // 2. Calculate what CLTV expiry delta we would observe there
5970 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5972 // 3. Starting from the observation point, find candidate paths
5973 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5974 candidates.push_back((observation_point, vec![]));
5976 let mut found_plausible_candidate = false;
5978 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5979 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5980 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5981 found_plausible_candidate = true;
5982 break 'candidate_loop;
5986 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5987 for channel_id in &cur_node.channels {
5988 if let Some(channel_info) = network_channels.get(&channel_id) {
5989 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5990 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
5991 if cur_path_cltv_deltas.iter().sum::<u32>()
5992 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5993 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5994 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5995 candidates.push_back((*next_id, new_path_cltv_deltas));
6003 path_plausibility.push(found_plausible_candidate);
6005 assert!(path_plausibility.iter().all(|x| *x));
6009 fn builds_correct_path_from_hops() {
6010 let (secp_ctx, network, _, _, logger) = build_graph();
6011 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6012 let network_graph = network.read_only();
6014 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6015 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6017 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6018 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6019 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
6020 &network_graph, 100, Arc::clone(&logger), &random_seed_bytes).unwrap();
6021 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6022 assert_eq!(hops.len(), route.paths[0].hops.len());
6023 for (idx, hop_pubkey) in hops.iter().enumerate() {
6024 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6029 fn avoids_saturating_channels() {
6030 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6031 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6032 let decay_params = ProbabilisticScoringDecayParameters::default();
6033 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6035 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6036 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6037 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6038 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6039 short_channel_id: 4,
6042 cltv_expiry_delta: (4 << 4) | 1,
6043 htlc_minimum_msat: 0,
6044 htlc_maximum_msat: 250_000_000,
6046 fee_proportional_millionths: 0,
6047 excess_data: Vec::new()
6049 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6050 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6051 short_channel_id: 13,
6054 cltv_expiry_delta: (13 << 4) | 1,
6055 htlc_minimum_msat: 0,
6056 htlc_maximum_msat: 250_000_000,
6058 fee_proportional_millionths: 0,
6059 excess_data: Vec::new()
6062 let config = UserConfig::default();
6063 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6064 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6065 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6066 // 100,000 sats is less than the available liquidity on each channel, set above.
6067 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();
6068 assert_eq!(route.paths.len(), 2);
6069 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6070 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6073 #[cfg(not(feature = "no-std"))]
6074 pub(super) fn random_init_seed() -> u64 {
6075 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6076 use core::hash::{BuildHasher, Hasher};
6077 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6078 println!("Using seed of {}", seed);
6083 #[cfg(not(feature = "no-std"))]
6084 fn generate_routes() {
6085 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6087 let logger = ln_test_utils::TestLogger::new();
6088 let graph = match super::bench_utils::read_network_graph(&logger) {
6096 let params = ProbabilisticScoringFeeParameters::default();
6097 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6098 let features = super::InvoiceFeatures::empty();
6100 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6104 #[cfg(not(feature = "no-std"))]
6105 fn generate_routes_mpp() {
6106 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6108 let logger = ln_test_utils::TestLogger::new();
6109 let graph = match super::bench_utils::read_network_graph(&logger) {
6117 let params = ProbabilisticScoringFeeParameters::default();
6118 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6119 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6121 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6125 #[cfg(not(feature = "no-std"))]
6126 fn generate_large_mpp_routes() {
6127 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6129 let logger = ln_test_utils::TestLogger::new();
6130 let graph = match super::bench_utils::read_network_graph(&logger) {
6138 let params = ProbabilisticScoringFeeParameters::default();
6139 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6140 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6142 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6146 fn honors_manual_penalties() {
6147 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6148 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6150 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6151 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6153 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6154 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6156 // First check set manual penalties are returned by the scorer.
6157 let usage = ChannelUsage {
6159 inflight_htlc_msat: 0,
6160 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6162 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6163 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6164 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
6166 // Then check we can get a normal route
6167 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6168 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6169 assert!(route.is_ok());
6171 // Then check that we can't get a route if we ban an intermediate node.
6172 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6173 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6174 assert!(route.is_err());
6176 // Finally make sure we can route again, when we remove the ban.
6177 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6178 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6179 assert!(route.is_ok());
6183 fn abide_by_route_hint_max_htlc() {
6184 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6185 // params in the final route.
6186 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6187 let netgraph = network_graph.read_only();
6188 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6189 let scorer = ln_test_utils::TestScorer::new();
6190 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6191 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6192 let config = UserConfig::default();
6194 let max_htlc_msat = 50_000;
6195 let route_hint_1 = RouteHint(vec![RouteHintHop {
6196 src_node_id: nodes[2],
6197 short_channel_id: 42,
6200 proportional_millionths: 0,
6202 cltv_expiry_delta: 10,
6203 htlc_minimum_msat: None,
6204 htlc_maximum_msat: Some(max_htlc_msat),
6206 let dest_node_id = ln_test_utils::pubkey(42);
6207 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6208 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6209 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6211 // Make sure we'll error if our route hints don't have enough liquidity according to their
6212 // htlc_maximum_msat.
6213 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6214 &payment_params, &netgraph, None, max_htlc_msat + 1, Arc::clone(&logger), &scorer, &(),
6217 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6218 } else { panic!(); }
6220 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6221 let mut route_hint_2 = route_hint_1.clone();
6222 route_hint_2.0[0].short_channel_id = 43;
6223 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6224 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6225 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6226 let route = get_route(&our_id, &payment_params, &netgraph, None, max_htlc_msat + 1,
6227 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6228 assert_eq!(route.paths.len(), 2);
6229 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6230 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6234 fn direct_channel_to_hints_with_max_htlc() {
6235 // Check that if we have a first hop channel peer that's connected to multiple provided route
6236 // hints, that we properly split the payment between the route hints if needed.
6237 let logger = Arc::new(ln_test_utils::TestLogger::new());
6238 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6239 let scorer = ln_test_utils::TestScorer::new();
6240 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6241 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6242 let config = UserConfig::default();
6244 let our_node_id = ln_test_utils::pubkey(42);
6245 let intermed_node_id = ln_test_utils::pubkey(43);
6246 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6248 let amt_msat = 900_000;
6249 let max_htlc_msat = 500_000;
6250 let route_hint_1 = RouteHint(vec![RouteHintHop {
6251 src_node_id: intermed_node_id,
6252 short_channel_id: 44,
6255 proportional_millionths: 0,
6257 cltv_expiry_delta: 10,
6258 htlc_minimum_msat: None,
6259 htlc_maximum_msat: Some(max_htlc_msat),
6261 src_node_id: intermed_node_id,
6262 short_channel_id: 45,
6265 proportional_millionths: 0,
6267 cltv_expiry_delta: 10,
6268 htlc_minimum_msat: None,
6269 // Check that later route hint max htlcs don't override earlier ones
6270 htlc_maximum_msat: Some(max_htlc_msat - 50),
6272 let mut route_hint_2 = route_hint_1.clone();
6273 route_hint_2.0[0].short_channel_id = 46;
6274 route_hint_2.0[1].short_channel_id = 47;
6275 let dest_node_id = ln_test_utils::pubkey(44);
6276 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6277 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6278 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6280 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6281 Some(&first_hop.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6282 &random_seed_bytes).unwrap();
6283 assert_eq!(route.paths.len(), 2);
6284 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6285 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6286 assert_eq!(route.get_total_amount(), amt_msat);
6288 // Re-run but with two first hop channels connected to the same route hint peers that must be
6290 let first_hops = vec![
6291 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6292 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6294 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6295 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6296 &random_seed_bytes).unwrap();
6297 assert_eq!(route.paths.len(), 2);
6298 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6299 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6300 assert_eq!(route.get_total_amount(), amt_msat);
6302 // Make sure this works for blinded route hints.
6303 let blinded_path = BlindedPath {
6304 introduction_node_id: intermed_node_id,
6305 blinding_point: ln_test_utils::pubkey(42),
6307 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6308 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6311 let blinded_payinfo = BlindedPayInfo {
6313 fee_proportional_millionths: 0,
6314 htlc_minimum_msat: 1,
6315 htlc_maximum_msat: max_htlc_msat,
6316 cltv_expiry_delta: 10,
6317 features: BlindedHopFeatures::empty(),
6319 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6320 let payment_params = PaymentParameters::blinded(vec![
6321 (blinded_payinfo.clone(), blinded_path.clone()),
6322 (blinded_payinfo.clone(), blinded_path.clone())])
6323 .with_bolt12_features(bolt12_features).unwrap();
6324 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6325 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6326 &random_seed_bytes).unwrap();
6327 assert_eq!(route.paths.len(), 2);
6328 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6329 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6330 assert_eq!(route.get_total_amount(), amt_msat);
6334 fn blinded_route_ser() {
6335 let blinded_path_1 = BlindedPath {
6336 introduction_node_id: ln_test_utils::pubkey(42),
6337 blinding_point: ln_test_utils::pubkey(43),
6339 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6340 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6343 let blinded_path_2 = BlindedPath {
6344 introduction_node_id: ln_test_utils::pubkey(46),
6345 blinding_point: ln_test_utils::pubkey(47),
6347 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6348 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6351 // (De)serialize a Route with 1 blinded path out of two total paths.
6352 let mut route = Route { paths: vec![Path {
6353 hops: vec![RouteHop {
6354 pubkey: ln_test_utils::pubkey(50),
6355 node_features: NodeFeatures::empty(),
6356 short_channel_id: 42,
6357 channel_features: ChannelFeatures::empty(),
6359 cltv_expiry_delta: 0,
6361 blinded_tail: Some(BlindedTail {
6362 hops: blinded_path_1.blinded_hops,
6363 blinding_point: blinded_path_1.blinding_point,
6364 excess_final_cltv_expiry_delta: 40,
6365 final_value_msat: 100,
6367 hops: vec![RouteHop {
6368 pubkey: ln_test_utils::pubkey(51),
6369 node_features: NodeFeatures::empty(),
6370 short_channel_id: 43,
6371 channel_features: ChannelFeatures::empty(),
6373 cltv_expiry_delta: 0,
6374 }], blinded_tail: None }],
6375 payment_params: None,
6377 let encoded_route = route.encode();
6378 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6379 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6380 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6382 // (De)serialize a Route with two paths, each containing a blinded tail.
6383 route.paths[1].blinded_tail = Some(BlindedTail {
6384 hops: blinded_path_2.blinded_hops,
6385 blinding_point: blinded_path_2.blinding_point,
6386 excess_final_cltv_expiry_delta: 41,
6387 final_value_msat: 101,
6389 let encoded_route = route.encode();
6390 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6391 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6392 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6396 fn blinded_path_inflight_processing() {
6397 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6398 // account for the blinded tail's final amount_msat.
6399 let mut inflight_htlcs = InFlightHtlcs::new();
6400 let blinded_path = BlindedPath {
6401 introduction_node_id: ln_test_utils::pubkey(43),
6402 blinding_point: ln_test_utils::pubkey(48),
6403 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
6406 hops: vec![RouteHop {
6407 pubkey: ln_test_utils::pubkey(42),
6408 node_features: NodeFeatures::empty(),
6409 short_channel_id: 42,
6410 channel_features: ChannelFeatures::empty(),
6412 cltv_expiry_delta: 0,
6415 pubkey: blinded_path.introduction_node_id,
6416 node_features: NodeFeatures::empty(),
6417 short_channel_id: 43,
6418 channel_features: ChannelFeatures::empty(),
6420 cltv_expiry_delta: 0,
6422 blinded_tail: Some(BlindedTail {
6423 hops: blinded_path.blinded_hops,
6424 blinding_point: blinded_path.blinding_point,
6425 excess_final_cltv_expiry_delta: 0,
6426 final_value_msat: 200,
6429 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
6430 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
6431 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
6435 fn blinded_path_cltv_shadow_offset() {
6436 // Make sure we add a shadow offset when sending to blinded paths.
6437 let blinded_path = BlindedPath {
6438 introduction_node_id: ln_test_utils::pubkey(43),
6439 blinding_point: ln_test_utils::pubkey(44),
6441 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
6442 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
6445 let mut route = Route { paths: vec![Path {
6446 hops: vec![RouteHop {
6447 pubkey: ln_test_utils::pubkey(42),
6448 node_features: NodeFeatures::empty(),
6449 short_channel_id: 42,
6450 channel_features: ChannelFeatures::empty(),
6452 cltv_expiry_delta: 0,
6455 pubkey: blinded_path.introduction_node_id,
6456 node_features: NodeFeatures::empty(),
6457 short_channel_id: 43,
6458 channel_features: ChannelFeatures::empty(),
6460 cltv_expiry_delta: 0,
6463 blinded_tail: Some(BlindedTail {
6464 hops: blinded_path.blinded_hops,
6465 blinding_point: blinded_path.blinding_point,
6466 excess_final_cltv_expiry_delta: 0,
6467 final_value_msat: 200,
6469 }], payment_params: None};
6471 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
6472 let (_, network_graph, _, _, _) = build_line_graph();
6473 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
6474 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
6475 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
6479 fn simple_blinded_route_hints() {
6480 do_simple_blinded_route_hints(1);
6481 do_simple_blinded_route_hints(2);
6482 do_simple_blinded_route_hints(3);
6485 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
6486 // Check that we can generate a route to a blinded path with the expected hops.
6487 let (secp_ctx, network, _, _, logger) = build_graph();
6488 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6489 let network_graph = network.read_only();
6491 let scorer = ln_test_utils::TestScorer::new();
6492 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6493 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6495 let mut blinded_path = BlindedPath {
6496 introduction_node_id: nodes[2],
6497 blinding_point: ln_test_utils::pubkey(42),
6498 blinded_hops: Vec::with_capacity(num_blinded_hops),
6500 for i in 0..num_blinded_hops {
6501 blinded_path.blinded_hops.push(
6502 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
6505 let blinded_payinfo = BlindedPayInfo {
6507 fee_proportional_millionths: 500,
6508 htlc_minimum_msat: 1000,
6509 htlc_maximum_msat: 100_000_000,
6510 cltv_expiry_delta: 15,
6511 features: BlindedHopFeatures::empty(),
6514 let final_amt_msat = 1001;
6515 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
6516 let route = get_route(&our_id, &payment_params, &network_graph, None, final_amt_msat , Arc::clone(&logger),
6517 &scorer, &(), &random_seed_bytes).unwrap();
6518 assert_eq!(route.paths.len(), 1);
6519 assert_eq!(route.paths[0].hops.len(), 2);
6521 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
6522 assert_eq!(tail.hops, blinded_path.blinded_hops);
6523 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
6524 assert_eq!(tail.final_value_msat, 1001);
6526 let final_hop = route.paths[0].hops.last().unwrap();
6527 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
6528 if tail.hops.len() > 1 {
6529 assert_eq!(final_hop.fee_msat,
6530 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
6531 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
6533 assert_eq!(final_hop.fee_msat, 0);
6534 assert_eq!(final_hop.cltv_expiry_delta, 0);
6539 fn blinded_path_routing_errors() {
6540 // Check that we can generate a route to a blinded path with the expected hops.
6541 let (secp_ctx, network, _, _, logger) = build_graph();
6542 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6543 let network_graph = network.read_only();
6545 let scorer = ln_test_utils::TestScorer::new();
6546 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6547 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6549 let mut invalid_blinded_path = BlindedPath {
6550 introduction_node_id: nodes[2],
6551 blinding_point: ln_test_utils::pubkey(42),
6553 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
6556 let blinded_payinfo = BlindedPayInfo {
6558 fee_proportional_millionths: 500,
6559 htlc_minimum_msat: 1000,
6560 htlc_maximum_msat: 100_000_000,
6561 cltv_expiry_delta: 15,
6562 features: BlindedHopFeatures::empty(),
6565 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
6566 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
6567 let payment_params = PaymentParameters::blinded(vec![
6568 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
6569 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
6570 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6571 &scorer, &(), &random_seed_bytes)
6573 Err(LightningError { err, .. }) => {
6574 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
6576 _ => panic!("Expected error")
6579 invalid_blinded_path.introduction_node_id = our_id;
6580 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
6581 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6582 &scorer, &(), &random_seed_bytes)
6584 Err(LightningError { err, .. }) => {
6585 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
6587 _ => panic!("Expected error")
6590 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
6591 invalid_blinded_path.blinded_hops.clear();
6592 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
6593 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6594 &scorer, &(), &random_seed_bytes)
6596 Err(LightningError { err, .. }) => {
6597 assert_eq!(err, "0-hop blinded path provided");
6599 _ => panic!("Expected error")
6604 fn matching_intro_node_paths_provided() {
6605 // Check that if multiple blinded paths with the same intro node are provided in payment
6606 // parameters, we'll return the correct paths in the resulting MPP route.
6607 let (secp_ctx, network, _, _, logger) = build_graph();
6608 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6609 let network_graph = network.read_only();
6611 let scorer = ln_test_utils::TestScorer::new();
6612 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6613 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6614 let config = UserConfig::default();
6616 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6617 let blinded_path_1 = BlindedPath {
6618 introduction_node_id: nodes[2],
6619 blinding_point: ln_test_utils::pubkey(42),
6621 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6622 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6625 let blinded_payinfo_1 = BlindedPayInfo {
6627 fee_proportional_millionths: 0,
6628 htlc_minimum_msat: 0,
6629 htlc_maximum_msat: 30_000,
6630 cltv_expiry_delta: 0,
6631 features: BlindedHopFeatures::empty(),
6634 let mut blinded_path_2 = blinded_path_1.clone();
6635 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
6636 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
6637 blinded_payinfo_2.htlc_maximum_msat = 70_000;
6639 let blinded_hints = vec![
6640 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
6641 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
6643 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
6644 .with_bolt12_features(bolt12_features.clone()).unwrap();
6646 let route = get_route(&our_id, &payment_params, &network_graph, None,
6647 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6648 assert_eq!(route.paths.len(), 2);
6649 let mut total_amount_paid_msat = 0;
6650 for path in route.paths.into_iter() {
6651 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6652 if let Some(bt) = &path.blinded_tail {
6653 assert_eq!(bt.blinding_point,
6654 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
6655 .map(|(_, bp)| bp.blinding_point).unwrap());
6656 } else { panic!(); }
6657 total_amount_paid_msat += path.final_value_msat();
6659 assert_eq!(total_amount_paid_msat, 100_000);
6663 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
6664 pub(crate) mod bench_utils {
6668 use bitcoin::hashes::Hash;
6669 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
6671 use crate::chain::transaction::OutPoint;
6672 use crate::sign::{EntropySource, KeysManager};
6673 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
6674 use crate::ln::features::InvoiceFeatures;
6675 use crate::routing::gossip::NetworkGraph;
6676 use crate::util::config::UserConfig;
6677 use crate::util::ser::ReadableArgs;
6678 use crate::util::test_utils::TestLogger;
6680 /// Tries to open a network graph file, or panics with a URL to fetch it.
6681 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
6682 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
6683 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
6684 .or_else(|_| { // Fall back to guessing based on the binary location
6685 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
6686 let mut path = std::env::current_exe().unwrap();
6687 path.pop(); // lightning-...
6689 path.pop(); // debug
6690 path.pop(); // target
6691 path.push("lightning");
6692 path.push("net_graph-2023-01-18.bin");
6695 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
6696 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
6697 let mut path = std::env::current_exe().unwrap();
6698 path.pop(); // bench...
6700 path.pop(); // debug
6701 path.pop(); // target
6702 path.pop(); // bench
6703 path.push("lightning");
6704 path.push("net_graph-2023-01-18.bin");
6707 .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");
6708 #[cfg(require_route_graph_test)]
6709 return Ok(res.unwrap());
6710 #[cfg(not(require_route_graph_test))]
6714 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
6715 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
6718 pub(crate) fn payer_pubkey() -> PublicKey {
6719 let secp_ctx = Secp256k1::new();
6720 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
6724 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
6726 channel_id: [0; 32],
6727 counterparty: ChannelCounterparty {
6728 features: channelmanager::provided_init_features(&UserConfig::default()),
6730 unspendable_punishment_reserve: 0,
6731 forwarding_info: None,
6732 outbound_htlc_minimum_msat: None,
6733 outbound_htlc_maximum_msat: None,
6735 funding_txo: Some(OutPoint {
6736 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
6739 short_channel_id: Some(1),
6740 inbound_scid_alias: None,
6741 outbound_scid_alias: None,
6742 channel_value_satoshis: 10_000_000_000,
6744 balance_msat: 10_000_000_000,
6745 outbound_capacity_msat: 10_000_000_000,
6746 next_outbound_htlc_minimum_msat: 0,
6747 next_outbound_htlc_limit_msat: 10_000_000_000,
6748 inbound_capacity_msat: 0,
6749 unspendable_punishment_reserve: None,
6750 confirmations_required: None,
6751 confirmations: None,
6752 force_close_spend_delay: None,
6754 is_channel_ready: true,
6757 inbound_htlc_minimum_msat: None,
6758 inbound_htlc_maximum_msat: None,
6760 feerate_sat_per_1000_weight: None,
6764 pub(crate) fn generate_test_routes<S: Score>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
6765 score_params: &S::ScoreParams, features: InvoiceFeatures, mut seed: u64,
6766 starting_amount: u64, route_count: usize,
6767 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
6768 let payer = payer_pubkey();
6769 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
6770 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6772 let nodes = graph.read_only().nodes().clone();
6773 let mut route_endpoints = Vec::new();
6774 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
6775 // with some routes we picked being un-routable.
6776 for _ in 0..route_count * 3 / 2 {
6778 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6779 let src = PublicKey::from_slice(nodes.unordered_keys()
6780 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6781 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6782 let dst = PublicKey::from_slice(nodes.unordered_keys()
6783 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6784 let params = PaymentParameters::from_node_id(dst, 42)
6785 .with_bolt11_features(features.clone()).unwrap();
6786 let first_hop = first_hop(src);
6787 let amt = starting_amount + seed % 1_000_000;
6789 get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]),
6790 amt, &TestLogger::new(), &scorer, score_params, &random_seed_bytes).is_ok();
6792 // ...and seed the scorer with success and failure data...
6793 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6794 let mut score_amt = seed % 1_000_000_000;
6796 // Generate fail/success paths for a wider range of potential amounts with
6797 // MPP enabled to give us a chance to apply penalties for more potential
6799 let mpp_features = channelmanager::provided_invoice_features(&UserConfig::default());
6800 let params = PaymentParameters::from_node_id(dst, 42)
6801 .with_bolt11_features(mpp_features).unwrap();
6803 let route_res = get_route(&payer, ¶ms, &graph.read_only(),
6804 Some(&[&first_hop]), score_amt, &TestLogger::new(), &scorer,
6805 score_params, &random_seed_bytes);
6806 if let Ok(route) = route_res {
6807 for path in route.paths {
6808 if seed & 0x80 == 0 {
6809 scorer.payment_path_successful(&path);
6811 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
6812 scorer.payment_path_failed(&path, short_channel_id);
6814 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6818 // If we couldn't find a path with a higer amount, reduce and try again.
6822 route_endpoints.push((first_hop, params, amt));
6828 // Because we've changed channel scores, it's possible we'll take different routes to the
6829 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
6830 // requires a too-high CLTV delta.
6831 route_endpoints.retain(|(first_hop, params, amt)| {
6832 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
6833 &TestLogger::new(), &scorer, score_params, &random_seed_bytes).is_ok()
6835 route_endpoints.truncate(route_count);
6836 assert_eq!(route_endpoints.len(), route_count);
6844 use crate::sign::{EntropySource, KeysManager};
6845 use crate::ln::channelmanager;
6846 use crate::ln::features::InvoiceFeatures;
6847 use crate::routing::gossip::NetworkGraph;
6848 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
6849 use crate::util::config::UserConfig;
6850 use crate::util::logger::{Logger, Record};
6851 use crate::util::test_utils::TestLogger;
6853 use criterion::Criterion;
6855 struct DummyLogger {}
6856 impl Logger for DummyLogger {
6857 fn log(&self, _record: &Record) {}
6860 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
6861 let logger = TestLogger::new();
6862 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6863 let scorer = FixedPenaltyScorer::with_penalty(0);
6864 generate_routes(bench, &network_graph, scorer, &(), InvoiceFeatures::empty(), 0,
6865 "generate_routes_with_zero_penalty_scorer");
6868 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
6869 let logger = TestLogger::new();
6870 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6871 let scorer = FixedPenaltyScorer::with_penalty(0);
6872 generate_routes(bench, &network_graph, scorer, &(),
6873 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
6874 "generate_mpp_routes_with_zero_penalty_scorer");
6877 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6878 let logger = TestLogger::new();
6879 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6880 let params = ProbabilisticScoringFeeParameters::default();
6881 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6882 generate_routes(bench, &network_graph, scorer, ¶ms, InvoiceFeatures::empty(), 0,
6883 "generate_routes_with_probabilistic_scorer");
6886 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6887 let logger = TestLogger::new();
6888 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6889 let params = ProbabilisticScoringFeeParameters::default();
6890 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6891 generate_routes(bench, &network_graph, scorer, ¶ms,
6892 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
6893 "generate_mpp_routes_with_probabilistic_scorer");
6896 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6897 let logger = TestLogger::new();
6898 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6899 let params = ProbabilisticScoringFeeParameters::default();
6900 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6901 generate_routes(bench, &network_graph, scorer, ¶ms,
6902 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
6903 "generate_large_mpp_routes_with_probabilistic_scorer");
6906 fn generate_routes<S: Score>(
6907 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
6908 score_params: &S::ScoreParams, features: InvoiceFeatures, starting_amount: u64,
6909 bench_name: &'static str,
6911 let payer = bench_utils::payer_pubkey();
6912 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
6913 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6915 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
6916 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
6918 // ...then benchmark finding paths between the nodes we learned.
6920 bench.bench_function(bench_name, |b| b.iter(|| {
6921 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
6922 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
6923 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());