1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The router finds paths within a [`NetworkGraph`] for a payment.
12 use bitcoin::secp256k1::PublicKey;
13 use bitcoin::hashes::Hash;
14 use bitcoin::hashes::sha256::Hash as Sha256;
16 use crate::blinded_path::{BlindedHop, BlindedPath};
17 use crate::ln::PaymentHash;
18 use crate::ln::channelmanager::{ChannelDetails, PaymentId};
19 use crate::ln::features::{Bolt12InvoiceFeatures, ChannelFeatures, InvoiceFeatures, NodeFeatures};
20 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
21 use crate::offers::invoice::{BlindedPayInfo, Invoice as Bolt12Invoice};
22 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
23 use crate::routing::scoring::{ChannelUsage, LockableScore, Score};
24 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
25 use crate::util::logger::{Level, Logger};
26 use crate::util::chacha20::ChaCha20;
29 use crate::prelude::*;
30 use crate::sync::{Mutex};
31 use alloc::collections::BinaryHeap;
33 use core::ops::{Deref, DerefMut};
35 /// A [`Router`] implemented using [`find_route`].
36 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: Score<ScoreParams = SP>> where
38 S::Target: for <'a> LockableScore<'a, Score = Sc>,
42 random_seed_bytes: Mutex<[u8; 32]>,
47 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: Score<ScoreParams = SP>> DefaultRouter<G, L, S, SP, Sc> where
49 S::Target: for <'a> LockableScore<'a, Score = Sc>,
51 /// Creates a new router.
52 pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32], scorer: S, score_params: SP) -> Self {
53 let random_seed_bytes = Mutex::new(random_seed_bytes);
54 Self { network_graph, logger, random_seed_bytes, scorer, score_params }
58 impl< G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: Score<ScoreParams = SP>> Router for DefaultRouter<G, L, S, SP, Sc> where
60 S::Target: for <'a> LockableScore<'a, Score = Sc>,
65 params: &RouteParameters,
66 first_hops: Option<&[&ChannelDetails]>,
67 inflight_htlcs: &InFlightHtlcs
68 ) -> Result<Route, LightningError> {
69 let random_seed_bytes = {
70 let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
71 *locked_random_seed_bytes = Sha256::hash(&*locked_random_seed_bytes).into_inner();
72 *locked_random_seed_bytes
75 payer, params, &self.network_graph, first_hops, &*self.logger,
76 &ScorerAccountingForInFlightHtlcs::new(self.scorer.lock().deref_mut(), inflight_htlcs),
83 /// A trait defining behavior for routing a payment.
85 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
87 &self, payer: &PublicKey, route_params: &RouteParameters,
88 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs
89 ) -> Result<Route, LightningError>;
90 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes
91 /// `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment.
92 fn find_route_with_id(
93 &self, payer: &PublicKey, route_params: &RouteParameters,
94 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs,
95 _payment_hash: PaymentHash, _payment_id: PaymentId
96 ) -> Result<Route, LightningError> {
97 self.find_route(payer, route_params, first_hops, inflight_htlcs)
101 /// [`Score`] implementation that factors in in-flight HTLC liquidity.
103 /// Useful for custom [`Router`] implementations to wrap their [`Score`] on-the-fly when calling
106 /// [`Score`]: crate::routing::scoring::Score
107 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Score<ScoreParams = SP>, SP: Sized> {
109 // Maps a channel's short channel id and its direction to the liquidity used up.
110 inflight_htlcs: &'a InFlightHtlcs,
113 impl<'a, S: Score<ScoreParams = SP>, SP: Sized> ScorerAccountingForInFlightHtlcs<'a, S, SP> {
114 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
115 pub fn new(scorer: &'a mut S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
116 ScorerAccountingForInFlightHtlcs {
124 impl<'a, S: Score<ScoreParams = SP>, SP: Sized> Writeable for ScorerAccountingForInFlightHtlcs<'a, S, SP> {
125 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.scorer.write(writer) }
128 impl<'a, S: Score<ScoreParams = SP>, SP: Sized> Score for ScorerAccountingForInFlightHtlcs<'a, S, SP> {
129 type ScoreParams = S::ScoreParams;
130 fn channel_penalty_msat(&self, short_channel_id: u64, source: &NodeId, target: &NodeId, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
131 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
132 source, target, short_channel_id
134 let usage = ChannelUsage {
135 inflight_htlc_msat: usage.inflight_htlc_msat + used_liquidity,
139 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
141 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
145 fn payment_path_failed(&mut self, path: &Path, short_channel_id: u64) {
146 self.scorer.payment_path_failed(path, short_channel_id)
149 fn payment_path_successful(&mut self, path: &Path) {
150 self.scorer.payment_path_successful(path)
153 fn probe_failed(&mut self, path: &Path, short_channel_id: u64) {
154 self.scorer.probe_failed(path, short_channel_id)
157 fn probe_successful(&mut self, path: &Path) {
158 self.scorer.probe_successful(path)
162 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
163 /// in-use channel liquidity.
165 pub struct InFlightHtlcs(
166 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
167 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
168 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
170 HashMap<(u64, bool), u64>
174 /// Constructs an empty `InFlightHtlcs`.
175 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
177 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
178 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
179 if path.hops.is_empty() { return };
181 let mut cumulative_msat = 0;
182 if let Some(tail) = &path.blinded_tail {
183 cumulative_msat += tail.final_value_msat;
186 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
187 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
188 // the router excludes the payer node. In the following lines, the payer's information is
189 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
190 // in our sliding window of two.
191 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
192 .map(|hop| hop.pubkey)
193 .chain(core::iter::once(payer_node_id));
195 // Taking the reversed vector from above, we zip it with just the reversed hops list to
196 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
197 // the total amount sent.
198 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
199 cumulative_msat += next_hop.fee_msat;
201 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
202 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
203 .or_insert(cumulative_msat);
207 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
209 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
211 .entry((channel_scid, source < target))
212 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
213 .or_insert(used_msat);
216 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
218 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
219 self.0.get(&(channel_scid, source < target)).map(|v| *v)
223 impl Writeable for InFlightHtlcs {
224 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
227 impl Readable for InFlightHtlcs {
228 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
229 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
230 Ok(Self(infight_map))
234 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
235 /// that leads to it.
236 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
237 pub struct RouteHop {
238 /// The node_id of the node at this hop.
239 pub pubkey: PublicKey,
240 /// The node_announcement features of the node at this hop. For the last hop, these may be
241 /// amended to match the features present in the invoice this node generated.
242 pub node_features: NodeFeatures,
243 /// The channel that should be used from the previous hop to reach this node.
244 pub short_channel_id: u64,
245 /// The channel_announcement features of the channel that should be used from the previous hop
246 /// to reach this node.
247 pub channel_features: ChannelFeatures,
248 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
249 /// If this is the last hop in [`Path::hops`]:
250 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
251 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
253 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
255 /// The CLTV delta added for this hop.
256 /// If this is the last hop in [`Path::hops`]:
257 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
258 /// * otherwise, this is the CLTV delta expected at the destination
260 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
261 pub cltv_expiry_delta: u32,
264 impl_writeable_tlv_based!(RouteHop, {
265 (0, pubkey, required),
266 (2, node_features, required),
267 (4, short_channel_id, required),
268 (6, channel_features, required),
269 (8, fee_msat, required),
270 (10, cltv_expiry_delta, required),
273 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
274 /// their BOLT12 [`Invoice`].
276 /// [`Invoice`]: crate::offers::invoice::Invoice
277 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
278 pub struct BlindedTail {
279 /// The hops of the [`BlindedPath`] provided by the recipient.
281 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
282 pub hops: Vec<BlindedHop>,
283 /// The blinding point of the [`BlindedPath`] provided by the recipient.
285 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
286 pub blinding_point: PublicKey,
287 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
288 /// inferring the destination. May be 0.
289 pub excess_final_cltv_expiry_delta: u32,
290 /// The total amount paid on this [`Path`], excluding the fees.
291 pub final_value_msat: u64,
294 impl_writeable_tlv_based!(BlindedTail, {
296 (2, blinding_point, required),
297 (4, excess_final_cltv_expiry_delta, required),
298 (6, final_value_msat, required),
301 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
302 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
303 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
305 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
306 pub hops: Vec<RouteHop>,
307 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
308 pub blinded_tail: Option<BlindedTail>,
312 /// Gets the fees for a given path, excluding any excess paid to the recipient.
313 pub fn fee_msat(&self) -> u64 {
314 match &self.blinded_tail {
315 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
317 // Do not count last hop of each path since that's the full value of the payment
318 self.hops.split_last().map_or(0,
319 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
324 /// Gets the total amount paid on this [`Path`], excluding the fees.
325 pub fn final_value_msat(&self) -> u64 {
326 match &self.blinded_tail {
327 Some(blinded_tail) => blinded_tail.final_value_msat,
328 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
332 /// Gets the final hop's CLTV expiry delta.
333 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
334 match &self.blinded_tail {
336 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
341 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
342 /// it can take multiple paths. Each path is composed of one or more hops through the network.
343 #[derive(Clone, Hash, PartialEq, Eq)]
345 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
346 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
348 pub paths: Vec<Path>,
349 /// The `payment_params` parameter passed to [`find_route`].
350 /// This is used by `ChannelManager` to track information which may be required for retries,
351 /// provided back to you via [`Event::PaymentPathFailed`].
353 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
354 pub payment_params: Option<PaymentParameters>,
358 /// Returns the total amount of fees paid on this [`Route`].
360 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
361 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
362 pub fn get_total_fees(&self) -> u64 {
363 self.paths.iter().map(|path| path.fee_msat()).sum()
366 /// Returns the total amount paid on this [`Route`], excluding the fees. Might be more than
367 /// requested if we had to reach htlc_minimum_msat.
368 pub fn get_total_amount(&self) -> u64 {
369 self.paths.iter().map(|path| path.final_value_msat()).sum()
373 const SERIALIZATION_VERSION: u8 = 1;
374 const MIN_SERIALIZATION_VERSION: u8 = 1;
376 impl Writeable for Route {
377 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
378 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
379 (self.paths.len() as u64).write(writer)?;
380 let mut blinded_tails = Vec::new();
381 for path in self.paths.iter() {
382 (path.hops.len() as u8).write(writer)?;
383 for (idx, hop) in path.hops.iter().enumerate() {
385 if let Some(blinded_tail) = &path.blinded_tail {
386 if blinded_tails.is_empty() {
387 blinded_tails = Vec::with_capacity(path.hops.len());
389 blinded_tails.push(None);
392 blinded_tails.push(Some(blinded_tail));
393 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
396 write_tlv_fields!(writer, {
397 (1, self.payment_params, option),
398 (2, blinded_tails, optional_vec),
404 impl Readable for Route {
405 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
406 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
407 let path_count: u64 = Readable::read(reader)?;
408 if path_count == 0 { return Err(DecodeError::InvalidValue); }
409 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
410 let mut min_final_cltv_expiry_delta = u32::max_value();
411 for _ in 0..path_count {
412 let hop_count: u8 = Readable::read(reader)?;
413 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
414 for _ in 0..hop_count {
415 hops.push(Readable::read(reader)?);
417 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
418 min_final_cltv_expiry_delta =
419 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
420 paths.push(Path { hops, blinded_tail: None });
422 _init_and_read_tlv_fields!(reader, {
423 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
424 (2, blinded_tails, optional_vec),
426 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
427 if blinded_tails.len() != 0 {
428 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
429 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
430 path.blinded_tail = blinded_tail_opt;
433 Ok(Route { paths, payment_params })
437 /// Parameters needed to find a [`Route`].
439 /// Passed to [`find_route`] and [`build_route_from_hops`], but also provided in
440 /// [`Event::PaymentPathFailed`].
442 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
443 #[derive(Clone, Debug, PartialEq, Eq)]
444 pub struct RouteParameters {
445 /// The parameters of the failed payment path.
446 pub payment_params: PaymentParameters,
448 /// The amount in msats sent on the failed payment path.
449 pub final_value_msat: u64,
452 impl Writeable for RouteParameters {
453 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
454 write_tlv_fields!(writer, {
455 (0, self.payment_params, required),
456 (2, self.final_value_msat, required),
457 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
458 // `RouteParameters` directly. For compatibility, we write it here.
459 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
465 impl Readable for RouteParameters {
466 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
467 _init_and_read_tlv_fields!(reader, {
468 (0, payment_params, (required: ReadableArgs, 0)),
469 (2, final_value_msat, required),
470 (4, final_cltv_delta, option),
472 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
473 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
474 if final_cltv_expiry_delta == &0 {
475 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
480 final_value_msat: final_value_msat.0.unwrap(),
485 /// Maximum total CTLV difference we allow for a full payment path.
486 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
488 /// Maximum number of paths we allow an (MPP) payment to have.
489 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
490 // limits, but for now more than 10 paths likely carries too much one-path failure.
491 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
493 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
495 // The median hop CLTV expiry delta currently seen in the network.
496 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
498 // During routing, we only consider paths shorter than our maximum length estimate.
499 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
500 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
501 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
503 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
504 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
505 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
506 // (payment_secret and total_msat) = 93 bytes for the final hop.
507 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
508 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
509 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
511 /// Information used to route a payment.
512 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
513 pub struct PaymentParameters {
514 /// Information about the payee, such as their features and route hints for their channels.
517 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
518 pub expiry_time: Option<u64>,
520 /// The maximum total CLTV delta we accept for the route.
521 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
522 pub max_total_cltv_expiry_delta: u32,
524 /// The maximum number of paths that may be used by (MPP) payments.
525 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
526 pub max_path_count: u8,
528 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
529 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
530 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
531 /// increasing failure probability for those paths.
533 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
534 /// restriction have been found. While paths which meet this criteria will be searched for, it
535 /// is ultimately up to the scorer to select them over other paths.
537 /// A value of 0 will allow payments up to and including a channel's total announced usable
538 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
541 pub max_channel_saturation_power_of_half: u8,
543 /// A list of SCIDs which this payment was previously attempted over and which caused the
544 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
546 pub previously_failed_channels: Vec<u64>,
549 impl Writeable for PaymentParameters {
550 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
551 let mut clear_hints = &vec![];
552 let mut blinded_hints = &vec![];
554 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
555 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
557 write_tlv_fields!(writer, {
558 (0, self.payee.node_id(), option),
559 (1, self.max_total_cltv_expiry_delta, required),
560 (2, self.payee.features(), option),
561 (3, self.max_path_count, required),
562 (4, *clear_hints, vec_type),
563 (5, self.max_channel_saturation_power_of_half, required),
564 (6, self.expiry_time, option),
565 (7, self.previously_failed_channels, vec_type),
566 (8, *blinded_hints, optional_vec),
567 (9, self.payee.final_cltv_expiry_delta(), option),
573 impl ReadableArgs<u32> for PaymentParameters {
574 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
575 _init_and_read_tlv_fields!(reader, {
576 (0, payee_pubkey, option),
577 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
578 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
579 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
580 (4, route_hints, vec_type),
581 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
582 (6, expiry_time, option),
583 (7, previously_failed_channels, vec_type),
584 (8, blinded_route_hints, optional_vec),
585 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
587 let clear_route_hints = route_hints.unwrap_or(vec![]);
588 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
589 let payee = if blinded_route_hints.len() != 0 {
590 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
592 route_hints: blinded_route_hints,
593 features: features.and_then(|f: Features| f.bolt12()),
597 route_hints: clear_route_hints,
598 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
599 features: features.and_then(|f| f.bolt11()),
600 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
604 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
605 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
607 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
609 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
615 impl PaymentParameters {
616 /// Creates a payee with the node id of the given `pubkey`.
618 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
620 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
622 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
624 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
625 max_path_count: DEFAULT_MAX_PATH_COUNT,
626 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
627 previously_failed_channels: Vec::new(),
631 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
633 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
636 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
637 /// whether your router will be allowed to find a multi-part route for this payment. If you
638 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
639 /// [`RecipientOnionFields::secret_only`].
641 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
642 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
643 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
644 .with_bolt11_features(InvoiceFeatures::for_keysend(allow_mpp))
645 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
648 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
649 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
650 /// [`PaymentParameters::expiry_time`].
651 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
652 Self::blinded(invoice.payment_paths().to_vec())
653 .with_bolt12_features(invoice.features().clone()).unwrap()
654 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
657 fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
659 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
661 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
662 max_path_count: DEFAULT_MAX_PATH_COUNT,
663 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
664 previously_failed_channels: Vec::new(),
668 /// Includes the payee's features. Errors if the parameters were not initialized with
669 /// [`PaymentParameters::from_bolt12_invoice`].
671 /// This is not exported to bindings users since bindings don't support move semantics
672 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
674 Payee::Clear { .. } => Err(()),
675 Payee::Blinded { route_hints, .. } =>
676 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
680 /// Includes the payee's features. Errors if the parameters were initialized with
681 /// [`PaymentParameters::from_bolt12_invoice`].
683 /// This is not exported to bindings users since bindings don't support move semantics
684 pub fn with_bolt11_features(self, features: InvoiceFeatures) -> Result<Self, ()> {
686 Payee::Blinded { .. } => Err(()),
687 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
689 payee: Payee::Clear {
690 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
696 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
697 /// [`PaymentParameters::from_bolt12_invoice`].
699 /// This is not exported to bindings users since bindings don't support move semantics
700 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
702 Payee::Blinded { .. } => Err(()),
703 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
705 payee: Payee::Clear {
706 route_hints, node_id, features, final_cltv_expiry_delta,
712 /// Includes a payment expiration in seconds relative to the UNIX epoch.
714 /// This is not exported to bindings users since bindings don't support move semantics
715 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
716 Self { expiry_time: Some(expiry_time), ..self }
719 /// Includes a limit for the total CLTV expiry delta which is considered during routing
721 /// This is not exported to bindings users since bindings don't support move semantics
722 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
723 Self { max_total_cltv_expiry_delta, ..self }
726 /// Includes a limit for the maximum number of payment paths that may be used.
728 /// This is not exported to bindings users since bindings don't support move semantics
729 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
730 Self { max_path_count, ..self }
733 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
734 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
736 /// This is not exported to bindings users since bindings don't support move semantics
737 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
738 Self { max_channel_saturation_power_of_half, ..self }
742 /// The recipient of a payment, differing based on whether they've hidden their identity with route
744 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
746 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
747 /// will be included in the final [`Route`].
749 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
751 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
752 /// Features supported by the payee.
754 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
756 features: Option<Bolt12InvoiceFeatures>,
758 /// The recipient included these route hints in their BOLT11 invoice.
760 /// The node id of the payee.
762 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
763 route_hints: Vec<RouteHint>,
764 /// Features supported by the payee.
766 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
767 /// does not contain any features.
769 /// [`for_keysend`]: PaymentParameters::for_keysend
770 features: Option<InvoiceFeatures>,
771 /// The minimum CLTV delta at the end of the route. This value must not be zero.
772 final_cltv_expiry_delta: u32,
777 fn node_id(&self) -> Option<PublicKey> {
779 Self::Clear { node_id, .. } => Some(*node_id),
783 fn node_features(&self) -> Option<NodeFeatures> {
785 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
786 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
789 fn supports_basic_mpp(&self) -> bool {
791 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
792 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
795 fn features(&self) -> Option<FeaturesRef> {
797 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
798 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
801 fn final_cltv_expiry_delta(&self) -> Option<u32> {
803 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
807 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
809 Self::Blinded { route_hints, .. } => &route_hints[..],
810 Self::Clear { .. } => &[]
814 fn unblinded_route_hints(&self) -> &[RouteHint] {
816 Self::Blinded { .. } => &[],
817 Self::Clear { route_hints, .. } => &route_hints[..]
822 enum FeaturesRef<'a> {
823 Bolt11(&'a InvoiceFeatures),
824 Bolt12(&'a Bolt12InvoiceFeatures),
827 Bolt11(InvoiceFeatures),
828 Bolt12(Bolt12InvoiceFeatures),
832 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
834 Self::Bolt12(f) => Some(f),
838 fn bolt11(self) -> Option<InvoiceFeatures> {
840 Self::Bolt11(f) => Some(f),
846 impl<'a> Writeable for FeaturesRef<'a> {
847 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
849 Self::Bolt11(f) => Ok(f.write(w)?),
850 Self::Bolt12(f) => Ok(f.write(w)?),
855 impl ReadableArgs<bool> for Features {
856 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
857 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
858 Ok(Self::Bolt12(Readable::read(reader)?))
862 /// A list of hops along a payment path terminating with a channel to the recipient.
863 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
864 pub struct RouteHint(pub Vec<RouteHintHop>);
866 impl Writeable for RouteHint {
867 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
868 (self.0.len() as u64).write(writer)?;
869 for hop in self.0.iter() {
876 impl Readable for RouteHint {
877 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
878 let hop_count: u64 = Readable::read(reader)?;
879 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
880 for _ in 0..hop_count {
881 hops.push(Readable::read(reader)?);
887 /// A channel descriptor for a hop along a payment path.
888 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
889 pub struct RouteHintHop {
890 /// The node_id of the non-target end of the route
891 pub src_node_id: PublicKey,
892 /// The short_channel_id of this channel
893 pub short_channel_id: u64,
894 /// The fees which must be paid to use this channel
895 pub fees: RoutingFees,
896 /// The difference in CLTV values between this node and the next node.
897 pub cltv_expiry_delta: u16,
898 /// The minimum value, in msat, which must be relayed to the next hop.
899 pub htlc_minimum_msat: Option<u64>,
900 /// The maximum value in msat available for routing with a single HTLC.
901 pub htlc_maximum_msat: Option<u64>,
904 impl_writeable_tlv_based!(RouteHintHop, {
905 (0, src_node_id, required),
906 (1, htlc_minimum_msat, option),
907 (2, short_channel_id, required),
908 (3, htlc_maximum_msat, option),
910 (6, cltv_expiry_delta, required),
913 #[derive(Eq, PartialEq)]
914 struct RouteGraphNode {
916 lowest_fee_to_node: u64,
917 total_cltv_delta: u32,
918 // The maximum value a yet-to-be-constructed payment path might flow through this node.
919 // This value is upper-bounded by us by:
920 // - how much is needed for a path being constructed
921 // - how much value can channels following this node (up to the destination) can contribute,
922 // considering their capacity and fees
923 value_contribution_msat: u64,
924 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
925 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
926 path_htlc_minimum_msat: u64,
927 /// All penalties incurred from this hop on the way to the destination, as calculated using
929 path_penalty_msat: u64,
930 /// The number of hops walked up to this node.
931 path_length_to_node: u8,
934 impl cmp::Ord for RouteGraphNode {
935 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
936 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
937 .saturating_add(other.path_penalty_msat);
938 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
939 .saturating_add(self.path_penalty_msat);
940 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
944 impl cmp::PartialOrd for RouteGraphNode {
945 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
946 Some(self.cmp(other))
950 /// A wrapper around the various hop representations.
952 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
953 #[derive(Clone, Debug)]
954 enum CandidateRouteHop<'a> {
955 /// A hop from the payer, where the outbound liquidity is known.
957 details: &'a ChannelDetails,
959 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
961 info: DirectedChannelInfo<'a>,
962 short_channel_id: u64,
964 /// A hop to the payee found in the BOLT 11 payment invoice, though not necessarily a direct
967 hint: &'a RouteHintHop,
969 /// The payee's identity is concealed behind blinded paths provided in a BOLT 12 invoice.
971 hint: &'a (BlindedPayInfo, BlindedPath),
974 /// Similar to [`Self::Blinded`], but the path here has 1 blinded hop. `BlindedPayInfo` provided
975 /// for 1-hop blinded paths is ignored because it is meant to apply to the hops *between* the
976 /// introduction node and the destination. Useful for tracking that we need to include a blinded
977 /// path at the end of our [`Route`].
979 hint: &'a (BlindedPayInfo, BlindedPath),
984 impl<'a> CandidateRouteHop<'a> {
985 fn short_channel_id(&self) -> Option<u64> {
987 CandidateRouteHop::FirstHop { details } => Some(details.get_outbound_payment_scid().unwrap()),
988 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
989 CandidateRouteHop::PrivateHop { hint } => Some(hint.short_channel_id),
990 CandidateRouteHop::Blinded { .. } => None,
991 CandidateRouteHop::OneHopBlinded { .. } => None,
995 // NOTE: This may alloc memory so avoid calling it in a hot code path.
996 fn features(&self) -> ChannelFeatures {
998 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
999 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
1000 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
1001 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
1002 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
1006 fn cltv_expiry_delta(&self) -> u32 {
1008 CandidateRouteHop::FirstHop { .. } => 0,
1009 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1010 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
1011 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1012 CandidateRouteHop::OneHopBlinded { .. } => 0,
1016 fn htlc_minimum_msat(&self) -> u64 {
1018 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_minimum_msat,
1019 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1020 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
1021 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1022 CandidateRouteHop::OneHopBlinded { .. } => 0,
1026 fn fees(&self) -> RoutingFees {
1028 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1029 base_msat: 0, proportional_millionths: 0,
1031 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1032 CandidateRouteHop::PrivateHop { hint } => hint.fees,
1033 CandidateRouteHop::Blinded { hint, .. } => {
1035 base_msat: hint.0.fee_base_msat,
1036 proportional_millionths: hint.0.fee_proportional_millionths
1039 CandidateRouteHop::OneHopBlinded { .. } =>
1040 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1044 fn effective_capacity(&self) -> EffectiveCapacity {
1046 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
1047 liquidity_msat: details.next_outbound_htlc_limit_msat,
1049 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1050 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }} =>
1051 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1052 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }} =>
1053 EffectiveCapacity::Infinite,
1054 CandidateRouteHop::Blinded { hint, .. } =>
1055 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1056 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1060 fn id(&self, channel_direction: bool /* src_node_id < target_node_id */) -> CandidateHopId {
1062 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1063 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1064 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), channel_direction)),
1067 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1069 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1077 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1078 enum CandidateHopId {
1079 /// Contains (scid, src_node_id < target_node_id)
1081 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1086 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1087 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1089 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1090 EffectiveCapacity::Infinite => u64::max_value(),
1091 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1092 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1093 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1094 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1095 // expected to have been generated from up-to-date capacity information.
1096 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1097 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1098 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1102 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1103 -> bool where I1::Item: PartialEq<I2::Item> {
1105 let a = iter_a.next();
1106 let b = iter_b.next();
1107 if a.is_none() && b.is_none() { return true; }
1108 if a.is_none() || b.is_none() { return false; }
1109 if a.unwrap().ne(&b.unwrap()) { return false; }
1113 /// It's useful to keep track of the hops associated with the fees required to use them,
1114 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1115 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1116 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1118 struct PathBuildingHop<'a> {
1119 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
1120 // is a larger refactor and will require careful performance analysis.
1122 candidate: CandidateRouteHop<'a>,
1125 /// All the fees paid *after* this channel on the way to the destination
1126 next_hops_fee_msat: u64,
1127 /// Fee paid for the use of the current channel (see candidate.fees()).
1128 /// The value will be actually deducted from the counterparty balance on the previous link.
1129 hop_use_fee_msat: u64,
1130 /// Used to compare channels when choosing the for routing.
1131 /// Includes paying for the use of a hop and the following hops, as well as
1132 /// an estimated cost of reaching this hop.
1133 /// Might get stale when fees are recomputed. Primarily for internal use.
1134 total_fee_msat: u64,
1135 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1136 /// walk and may be invalid thereafter.
1137 path_htlc_minimum_msat: u64,
1138 /// All penalties incurred from this channel on the way to the destination, as calculated using
1139 /// channel scoring.
1140 path_penalty_msat: u64,
1141 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1142 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1143 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1144 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1145 /// avoid processing them again.
1146 was_processed: bool,
1147 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1148 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1149 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1150 // value_contribution_msat, which requires tracking it here. See comments below where it is
1151 // used for more info.
1152 value_contribution_msat: u64,
1155 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1156 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1157 let mut debug_struct = f.debug_struct("PathBuildingHop");
1159 .field("node_id", &self.node_id)
1160 .field("short_channel_id", &self.candidate.short_channel_id())
1161 .field("total_fee_msat", &self.total_fee_msat)
1162 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1163 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1164 .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)))
1165 .field("path_penalty_msat", &self.path_penalty_msat)
1166 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1167 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1168 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1169 let debug_struct = debug_struct
1170 .field("value_contribution_msat", &self.value_contribution_msat);
1171 debug_struct.finish()
1175 // Instantiated with a list of hops with correct data in them collected during path finding,
1176 // an instance of this struct should be further modified only via given methods.
1178 struct PaymentPath<'a> {
1179 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1182 impl<'a> PaymentPath<'a> {
1183 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1184 fn get_value_msat(&self) -> u64 {
1185 self.hops.last().unwrap().0.fee_msat
1188 fn get_path_penalty_msat(&self) -> u64 {
1189 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1192 fn get_total_fee_paid_msat(&self) -> u64 {
1193 if self.hops.len() < 1 {
1197 // Can't use next_hops_fee_msat because it gets outdated.
1198 for (i, (hop, _)) in self.hops.iter().enumerate() {
1199 if i != self.hops.len() - 1 {
1200 result += hop.fee_msat;
1206 fn get_cost_msat(&self) -> u64 {
1207 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1210 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1211 // to change fees may result in an inconsistency.
1213 // Sometimes we call this function right after constructing a path which is inconsistent in
1214 // that it the value being transferred has decreased while we were doing path finding, leading
1215 // to the fees being paid not lining up with the actual limits.
1217 // Note that this function is not aware of the available_liquidity limit, and thus does not
1218 // support increasing the value being transferred beyond what was selected during the initial
1220 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
1221 let mut total_fee_paid_msat = 0 as u64;
1222 for i in (0..self.hops.len()).rev() {
1223 let last_hop = i == self.hops.len() - 1;
1225 // For non-last-hop, this value will represent the fees paid on the current hop. It
1226 // will consist of the fees for the use of the next hop, and extra fees to match
1227 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1228 let mut cur_hop_fees_msat = 0;
1230 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1233 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1234 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1235 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1236 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1237 // set it too high just to maliciously take more fees by exploiting this
1238 // match htlc_minimum_msat logic.
1239 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1240 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1241 // Note that there is a risk that *previous hops* (those closer to us, as we go
1242 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1244 // This might make us end up with a broken route, although this should be super-rare
1245 // in practice, both because of how healthy channels look like, and how we pick
1246 // channels in add_entry.
1247 // Also, this can't be exploited more heavily than *announce a free path and fail
1249 cur_hop_transferred_amount_msat += extra_fees_msat;
1250 total_fee_paid_msat += extra_fees_msat;
1251 cur_hop_fees_msat += extra_fees_msat;
1255 // Final hop is a special case: it usually has just value_msat (by design), but also
1256 // it still could overpay for the htlc_minimum_msat.
1257 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1259 // Propagate updated fees for the use of the channels to one hop back, where they
1260 // will be actually paid (fee_msat). The last hop is handled above separately.
1261 cur_hop.fee_msat = cur_hop_fees_msat;
1264 // Fee for the use of the current hop which will be deducted on the previous hop.
1265 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1266 // this channel is free for us.
1268 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1269 cur_hop.hop_use_fee_msat = new_fee;
1270 total_fee_paid_msat += new_fee;
1272 // It should not be possible because this function is called only to reduce the
1273 // value. In that case, compute_fee was already called with the same fees for
1274 // larger amount and there was no overflow.
1283 /// Calculate the fees required to route the given amount over a channel with the given fees.
1284 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1285 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1286 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1290 /// Calculate the fees required to route the given amount over a channel with the given fees,
1291 /// saturating to [`u64::max_value`].
1292 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1293 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1294 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1295 .saturating_add(channel_fees.base_msat as u64)
1298 /// The default `features` we assume for a node in a route, when no `features` are known about that
1301 /// Default features are:
1302 /// * variable_length_onion_optional
1303 fn default_node_features() -> NodeFeatures {
1304 let mut features = NodeFeatures::empty();
1305 features.set_variable_length_onion_optional();
1309 struct LoggedPayeePubkey(Option<PublicKey>);
1310 impl fmt::Display for LoggedPayeePubkey {
1311 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1314 "payee node id ".fmt(f)?;
1318 "blinded payee".fmt(f)
1324 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1325 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1326 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1328 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1329 "blinded route hint with introduction node id ".fmt(f)?;
1330 hint.1.introduction_node_id.fmt(f)?;
1331 " and blinding point ".fmt(f)?;
1332 hint.1.blinding_point.fmt(f)
1336 self.0.short_channel_id().unwrap().fmt(f)
1343 fn sort_first_hop_channels(
1344 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1345 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1347 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1348 // most like to use.
1350 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1351 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1354 // Second, because simply always sorting in descending order would always use our largest
1355 // available outbound capacity, needlessly fragmenting our available channel capacities,
1356 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1357 // which have enough, but not too much, capacity for the payment.
1359 // Available outbound balances factor in liquidity already reserved for previously found paths.
1360 channels.sort_unstable_by(|chan_a, chan_b| {
1361 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1362 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1363 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1364 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1365 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1366 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1367 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1368 // Sort in descending order
1369 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1371 // Sort in ascending order
1372 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1377 /// Finds a route from us (payer) to the given target node (payee).
1379 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
1380 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1382 /// Private routing paths between a public node and the target may be included in `params.payee`.
1384 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1385 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1386 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1388 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1389 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1390 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1394 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
1395 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
1400 /// Panics if first_hops contains channels without short_channel_ids;
1401 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1403 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1404 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1405 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1406 pub fn find_route<L: Deref, GL: Deref, S: Score>(
1407 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1408 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1409 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1410 ) -> Result<Route, LightningError>
1411 where L::Target: Logger, GL::Target: Logger {
1412 let graph_lock = network_graph.read_only();
1413 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
1414 route_params.final_value_msat, logger, scorer, score_params,
1415 random_seed_bytes)?;
1416 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1420 pub(crate) fn get_route<L: Deref, S: Score>(
1421 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
1422 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, logger: L, scorer: &S, score_params: &S::ScoreParams,
1423 _random_seed_bytes: &[u8; 32]
1424 ) -> Result<Route, LightningError>
1425 where L::Target: Logger {
1426 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1427 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1428 // so use a dummy id for this in the blinded case.
1429 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1430 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1431 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1432 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1433 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1435 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1436 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1439 if final_value_msat > MAX_VALUE_MSAT {
1440 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1443 if final_value_msat == 0 {
1444 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1447 match &payment_params.payee {
1448 Payee::Clear { route_hints, node_id, .. } => {
1449 for route in route_hints.iter() {
1450 for hop in &route.0 {
1451 if hop.src_node_id == *node_id {
1452 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1457 Payee::Blinded { route_hints, .. } => {
1458 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1459 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});
1461 for (_, blinded_path) in route_hints.iter() {
1462 if blinded_path.blinded_hops.len() == 0 {
1463 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1464 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1465 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1466 } else if blinded_path.blinded_hops.len() == 1 &&
1467 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1468 && p.introduction_node_id != blinded_path.introduction_node_id)
1470 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1475 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1476 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1477 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});
1480 // The general routing idea is the following:
1481 // 1. Fill first/last hops communicated by the caller.
1482 // 2. Attempt to construct a path from payer to payee for transferring
1483 // any ~sufficient (described later) value.
1484 // If succeed, remember which channels were used and how much liquidity they have available,
1485 // so that future paths don't rely on the same liquidity.
1486 // 3. Proceed to the next step if:
1487 // - we hit the recommended target value;
1488 // - OR if we could not construct a new path. Any next attempt will fail too.
1489 // Otherwise, repeat step 2.
1490 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1491 // (not recommended value).
1492 // 5. If yes, proceed. If not, fail routing.
1493 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1494 // transferred up to the transfer target value.
1495 // 7. Reduce the value of the last path until we are sending only the target value.
1496 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1497 // them so that we're not sending two HTLCs along the same path.
1499 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1500 // distance from the payee
1502 // We are not a faithful Dijkstra's implementation because we can change values which impact
1503 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1504 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1505 // the value we are currently attempting to send over a path, we simply reduce the value being
1506 // sent along the path for any hops after that channel. This may imply that later fees (which
1507 // we've already tabulated) are lower because a smaller value is passing through the channels
1508 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1509 // channels which were selected earlier (and which may still be used for other paths without a
1510 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1513 // One potentially problematic case for this algorithm would be if there are many
1514 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1515 // graph walking), we may never find a path which is not liquidity-limited and has lower
1516 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1517 // Because we only consider paths with at least 5% of the total value being sent, the damage
1518 // from such a case should be limited, however this could be further reduced in the future by
1519 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1520 // limits for the purposes of fee calculation.
1522 // Alternatively, we could store more detailed path information in the heap (targets, below)
1523 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1524 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1525 // and practically (as we would need to store dynamically-allocated path information in heap
1526 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1527 // results of such an algorithm would likely be biased towards lower-value paths.
1529 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1530 // outside of our current search value, running a path search more times to gather candidate
1531 // paths at different values. While this may be acceptable, further path searches may increase
1532 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1533 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1534 // the same time, remaining generic across different payment values.
1536 let network_channels = network_graph.channels();
1537 let network_nodes = network_graph.nodes();
1539 if payment_params.max_path_count == 0 {
1540 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1543 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1544 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1546 let allow_mpp = if payment_params.max_path_count == 1 {
1548 } else if payment_params.payee.supports_basic_mpp() {
1550 } else if let Some(payee) = payee_node_id_opt {
1551 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1552 |info| info.features.supports_basic_mpp()))
1555 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1556 LoggedPayeePubkey(payment_params.payee.node_id()), if allow_mpp { "with" } else { "without" },
1557 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1560 // Prepare the data we'll use for payee-to-payer search by
1561 // inserting first hops suggested by the caller as targets.
1562 // Our search will then attempt to reach them while traversing from the payee node.
1563 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1564 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1565 if let Some(hops) = first_hops {
1567 if chan.get_outbound_payment_scid().is_none() {
1568 panic!("first_hops should be filled in with usable channels, not pending ones");
1570 if chan.counterparty.node_id == *our_node_pubkey {
1571 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1574 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1575 .or_insert(Vec::new())
1578 if first_hop_targets.is_empty() {
1579 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1583 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1584 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1585 // adding duplicate entries when we find a better path to a given node.
1586 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1588 // Map from node_id to information about the best current path to that node, including feerate
1590 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1592 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1593 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1594 // htlc_minimum with extra fees while still finding a cheaper path.
1595 let mut hit_minimum_limit;
1597 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1598 // We start with a path_value of the exact amount we want, and if that generates a route we may
1599 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1600 // amount we want in total across paths, selecting the best subset at the end.
1601 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1602 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1603 let mut path_value_msat = final_value_msat;
1605 // Routing Fragmentation Mitigation heuristic:
1607 // Routing fragmentation across many payment paths increases the overall routing
1608 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1609 // Taking too many smaller paths also increases the chance of payment failure.
1610 // Thus to avoid this effect, we require from our collected links to provide
1611 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1612 // This requirement is currently set to be 1/max_path_count of the payment
1613 // value to ensure we only ever return routes that do not violate this limit.
1614 let minimal_value_contribution_msat: u64 = if allow_mpp {
1615 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1620 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1621 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1622 // drop the requirement by setting this to 0.
1623 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1625 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1626 // determine if the channel can be used by additional MPP paths or to inform path finding
1627 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1628 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1630 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1631 HashMap::with_capacity(network_nodes.len());
1633 // Keeping track of how much value we already collected across other paths. Helps to decide
1634 // when we want to stop looking for new paths.
1635 let mut already_collected_value_msat = 0;
1637 for (_, channels) in first_hop_targets.iter_mut() {
1638 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1642 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1643 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1645 macro_rules! add_entry {
1646 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1647 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1648 // since that value has to be transferred over this channel.
1649 // Returns whether this channel caused an update to `targets`.
1650 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1651 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1652 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1653 // We "return" whether we updated the path at the end, and how much we can route via
1654 // this channel, via this:
1655 let mut did_add_update_path_to_src_node = None;
1656 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1657 // practice these cases should be caught earlier:
1658 // - for regular channels at channel announcement (TODO)
1659 // - for first and last hops early in get_route
1660 if $src_node_id != $dest_node_id {
1661 let scid_opt = $candidate.short_channel_id();
1662 let effective_capacity = $candidate.effective_capacity();
1663 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1665 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1666 // It may be misleading because we might later choose to reduce the value transferred
1667 // over these channels, and the channel which was insufficient might become sufficient.
1668 // Worst case: we drop a good channel here because it can't cover the high following
1669 // fees caused by one expensive channel, but then this channel could have been used
1670 // if the amount being transferred over this path is lower.
1671 // We do this for now, but this is a subject for removal.
1672 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1673 let used_liquidity_msat = used_liquidities
1674 .get(&$candidate.id($src_node_id < $dest_node_id))
1675 .map_or(0, |used_liquidity_msat| {
1676 available_value_contribution_msat = available_value_contribution_msat
1677 .saturating_sub(*used_liquidity_msat);
1678 *used_liquidity_msat
1681 // Verify the liquidity offered by this channel complies to the minimal contribution.
1682 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1683 // Do not consider candidate hops that would exceed the maximum path length.
1684 let path_length_to_node = $next_hops_path_length + 1;
1685 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1687 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1688 // In order to already account for some of the privacy enhancing random CLTV
1689 // expiry delta offset we add on top later, we subtract a rough estimate
1690 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1691 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1692 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1693 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1694 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1695 .saturating_add($candidate.cltv_expiry_delta());
1696 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1698 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1699 // Includes paying fees for the use of the following channels.
1700 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1701 Some(result) => result,
1702 // Can't overflow due to how the values were computed right above.
1703 None => unreachable!(),
1705 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1706 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1707 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1709 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1710 let may_overpay_to_meet_path_minimum_msat =
1711 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1712 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1713 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1714 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1716 let payment_failed_on_this_channel = scid_opt.map_or(false,
1717 |scid| payment_params.previously_failed_channels.contains(&scid));
1719 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1720 // bother considering this channel. If retrying with recommended_value_msat may
1721 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1722 // around again with a higher amount.
1723 if !contributes_sufficient_value || exceeds_max_path_length ||
1724 exceeds_cltv_delta_limit || payment_failed_on_this_channel {
1725 // Path isn't useful, ignore it and move on.
1726 } else if may_overpay_to_meet_path_minimum_msat {
1727 hit_minimum_limit = true;
1728 } else if over_path_minimum_msat {
1729 // Note that low contribution here (limited by available_liquidity_msat)
1730 // might violate htlc_minimum_msat on the hops which are next along the
1731 // payment path (upstream to the payee). To avoid that, we recompute
1732 // path fees knowing the final path contribution after constructing it.
1733 let path_htlc_minimum_msat = cmp::max(
1734 compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1735 .saturating_add($next_hops_path_htlc_minimum_msat),
1736 $candidate.htlc_minimum_msat());
1737 let hm_entry = dist.entry($src_node_id);
1738 let old_entry = hm_entry.or_insert_with(|| {
1739 // If there was previously no known way to access the source node
1740 // (recall it goes payee-to-payer) of short_channel_id, first add a
1741 // semi-dummy record just to compute the fees to reach the source node.
1742 // This will affect our decision on selecting short_channel_id
1743 // as a way to reach the $dest_node_id.
1745 node_id: $dest_node_id.clone(),
1746 candidate: $candidate.clone(),
1748 next_hops_fee_msat: u64::max_value(),
1749 hop_use_fee_msat: u64::max_value(),
1750 total_fee_msat: u64::max_value(),
1751 path_htlc_minimum_msat,
1752 path_penalty_msat: u64::max_value(),
1753 was_processed: false,
1754 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1755 value_contribution_msat,
1759 #[allow(unused_mut)] // We only use the mut in cfg(test)
1760 let mut should_process = !old_entry.was_processed;
1761 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1763 // In test/fuzzing builds, we do extra checks to make sure the skipping
1764 // of already-seen nodes only happens in cases we expect (see below).
1765 if !should_process { should_process = true; }
1769 let mut hop_use_fee_msat = 0;
1770 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1772 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1773 // will have the same effective-fee
1774 if $src_node_id != our_node_id {
1775 // Note that `u64::max_value` means we'll always fail the
1776 // `old_entry.total_fee_msat > total_fee_msat` check below
1777 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1778 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1781 let channel_usage = ChannelUsage {
1782 amount_msat: amount_to_transfer_over_msat,
1783 inflight_htlc_msat: used_liquidity_msat,
1786 let channel_penalty_msat = scid_opt.map_or(0,
1787 |scid| scorer.channel_penalty_msat(scid, &$src_node_id, &$dest_node_id,
1788 channel_usage, score_params));
1789 let path_penalty_msat = $next_hops_path_penalty_msat
1790 .saturating_add(channel_penalty_msat);
1791 let new_graph_node = RouteGraphNode {
1792 node_id: $src_node_id,
1793 lowest_fee_to_node: total_fee_msat,
1794 total_cltv_delta: hop_total_cltv_delta,
1795 value_contribution_msat,
1796 path_htlc_minimum_msat,
1798 path_length_to_node,
1801 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1802 // if this way is cheaper than the already known
1803 // (considering the cost to "reach" this channel from the route destination,
1804 // the cost of using this channel,
1805 // and the cost of routing to the source node of this channel).
1806 // Also, consider that htlc_minimum_msat_difference, because we might end up
1807 // paying it. Consider the following exploit:
1808 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1809 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1810 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1811 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1813 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1814 // but it may require additional tracking - we don't want to double-count
1815 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1816 // can't use something that may decrease on future hops.
1817 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1818 .saturating_add(old_entry.path_penalty_msat);
1819 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1820 .saturating_add(path_penalty_msat);
1822 if !old_entry.was_processed && new_cost < old_cost {
1823 targets.push(new_graph_node);
1824 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1825 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1826 old_entry.total_fee_msat = total_fee_msat;
1827 old_entry.node_id = $dest_node_id.clone();
1828 old_entry.candidate = $candidate.clone();
1829 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1830 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1831 old_entry.path_penalty_msat = path_penalty_msat;
1832 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1834 old_entry.value_contribution_msat = value_contribution_msat;
1836 did_add_update_path_to_src_node = Some(value_contribution_msat);
1837 } else if old_entry.was_processed && new_cost < old_cost {
1838 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1840 // If we're skipping processing a node which was previously
1841 // processed even though we found another path to it with a
1842 // cheaper fee, check that it was because the second path we
1843 // found (which we are processing now) has a lower value
1844 // contribution due to an HTLC minimum limit.
1846 // e.g. take a graph with two paths from node 1 to node 2, one
1847 // through channel A, and one through channel B. Channel A and
1848 // B are both in the to-process heap, with their scores set by
1849 // a higher htlc_minimum than fee.
1850 // Channel A is processed first, and the channels onwards from
1851 // node 1 are added to the to-process heap. Thereafter, we pop
1852 // Channel B off of the heap, note that it has a much more
1853 // restrictive htlc_maximum_msat, and recalculate the fees for
1854 // all of node 1's channels using the new, reduced, amount.
1856 // This would be bogus - we'd be selecting a higher-fee path
1857 // with a lower htlc_maximum_msat instead of the one we'd
1858 // already decided to use.
1859 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1861 value_contribution_msat + path_penalty_msat <
1862 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1870 did_add_update_path_to_src_node
1874 let default_node_features = default_node_features();
1876 // Find ways (channels with destination) to reach a given node and store them
1877 // in the corresponding data structures (routing graph etc).
1878 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1879 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1880 // This data can later be helpful to optimize routing (pay lower fees).
1881 macro_rules! add_entries_to_cheapest_to_target_node {
1882 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1883 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1884 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1885 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1886 let was_processed = elem.was_processed;
1887 elem.was_processed = true;
1890 // Entries are added to dist in add_entry!() when there is a channel from a node.
1891 // Because there are no channels from payee, it will not have a dist entry at this point.
1892 // If we're processing any other node, it is always be the result of a channel from it.
1893 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
1898 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1899 for details in first_channels {
1900 let candidate = CandidateRouteHop::FirstHop { details };
1901 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1902 $next_hops_value_contribution,
1903 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1904 $next_hops_cltv_delta, $next_hops_path_length);
1908 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1911 &default_node_features
1914 if !features.requires_unknown_bits() {
1915 for chan_id in $node.channels.iter() {
1916 let chan = network_channels.get(chan_id).unwrap();
1917 if !chan.features.requires_unknown_bits() {
1918 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1919 if first_hops.is_none() || *source != our_node_id {
1920 if directed_channel.direction().enabled {
1921 let candidate = CandidateRouteHop::PublicHop {
1922 info: directed_channel,
1923 short_channel_id: *chan_id,
1925 add_entry!(candidate, *source, $node_id,
1926 $fee_to_target_msat,
1927 $next_hops_value_contribution,
1928 $next_hops_path_htlc_minimum_msat,
1929 $next_hops_path_penalty_msat,
1930 $next_hops_cltv_delta, $next_hops_path_length);
1941 let mut payment_paths = Vec::<PaymentPath>::new();
1943 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1944 'paths_collection: loop {
1945 // For every new path, start from scratch, except for used_liquidities, which
1946 // helps to avoid reusing previously selected paths in future iterations.
1949 hit_minimum_limit = false;
1951 // If first hop is a private channel and the only way to reach the payee, this is the only
1952 // place where it could be added.
1953 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
1954 for details in first_channels {
1955 let candidate = CandidateRouteHop::FirstHop { details };
1956 let added = add_entry!(candidate, our_node_id, payee, 0, path_value_msat,
1957 0, 0u64, 0, 0).is_some();
1958 log_trace!(logger, "{} direct route to payee via {}",
1959 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
1963 // Add the payee as a target, so that the payee-to-payer
1964 // search algorithm knows what to start with.
1965 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
1966 // The payee is not in our network graph, so nothing to add here.
1967 // There is still a chance of reaching them via last_hops though,
1968 // so don't yet fail the payment here.
1969 // If not, targets.pop() will not even let us enter the loop in step 2.
1972 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
1977 // If a caller provided us with last hops, add them to routing targets. Since this happens
1978 // earlier than general path finding, they will be somewhat prioritized, although currently
1979 // it matters only if the fees are exactly the same.
1980 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
1981 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
1982 let have_intro_node_in_graph =
1983 // Only add the hops in this route to our candidate set if either
1984 // we have a direct channel to the first hop or the first hop is
1985 // in the regular network graph.
1986 first_hop_targets.get(&intro_node_id).is_some() ||
1987 network_nodes.get(&intro_node_id).is_some();
1988 if !have_intro_node_in_graph { continue }
1989 let candidate = if hint.1.blinded_hops.len() == 1 {
1990 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
1991 } else { CandidateRouteHop::Blinded { hint, hint_idx } };
1992 let mut path_contribution_msat = path_value_msat;
1993 if let Some(hop_used_msat) = add_entry!(candidate, intro_node_id, maybe_dummy_payee_node_id,
1994 0, path_contribution_msat, 0, 0_u64, 0, 0)
1996 path_contribution_msat = hop_used_msat;
1998 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
1999 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2001 for details in first_channels {
2002 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2003 add_entry!(first_hop_candidate, our_node_id, intro_node_id, 0, path_contribution_msat, 0,
2008 for route in payment_params.payee.unblinded_route_hints().iter()
2009 .filter(|route| !route.0.is_empty())
2011 let first_hop_in_route = &(route.0)[0];
2012 let have_hop_src_in_graph =
2013 // Only add the hops in this route to our candidate set if either
2014 // we have a direct channel to the first hop or the first hop is
2015 // in the regular network graph.
2016 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
2017 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
2018 if have_hop_src_in_graph {
2019 // We start building the path from reverse, i.e., from payee
2020 // to the first RouteHintHop in the path.
2021 let hop_iter = route.0.iter().rev();
2022 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2023 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2024 let mut hop_used = true;
2025 let mut aggregate_next_hops_fee_msat: u64 = 0;
2026 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2027 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2028 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2029 let mut aggregate_next_hops_path_length: u8 = 0;
2030 let mut aggregate_path_contribution_msat = path_value_msat;
2032 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2033 let source = NodeId::from_pubkey(&hop.src_node_id);
2034 let target = NodeId::from_pubkey(&prev_hop_id);
2035 let candidate = network_channels
2036 .get(&hop.short_channel_id)
2037 .and_then(|channel| channel.as_directed_to(&target))
2038 .map(|(info, _)| CandidateRouteHop::PublicHop {
2040 short_channel_id: hop.short_channel_id,
2042 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
2044 if let Some(hop_used_msat) = add_entry!(candidate, source, target,
2045 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2046 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2047 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2049 aggregate_path_contribution_msat = hop_used_msat;
2051 // If this hop was not used then there is no use checking the preceding
2052 // hops in the RouteHint. We can break by just searching for a direct
2053 // channel between last checked hop and first_hop_targets.
2057 let used_liquidity_msat = used_liquidities
2058 .get(&candidate.id(source < target)).copied()
2060 let channel_usage = ChannelUsage {
2061 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2062 inflight_htlc_msat: used_liquidity_msat,
2063 effective_capacity: candidate.effective_capacity(),
2065 let channel_penalty_msat = scorer.channel_penalty_msat(
2066 hop.short_channel_id, &source, &target, channel_usage, score_params
2068 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2069 .saturating_add(channel_penalty_msat);
2071 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2072 .saturating_add(hop.cltv_expiry_delta as u32);
2074 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2077 // Searching for a direct channel between last checked hop and first_hop_targets
2078 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&prev_hop_id)) {
2079 sort_first_hop_channels(first_channels, &used_liquidities,
2080 recommended_value_msat, our_node_pubkey);
2081 for details in first_channels {
2082 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2083 add_entry!(first_hop_candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
2084 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2085 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2086 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2094 // In the next values of the iterator, the aggregate fees already reflects
2095 // the sum of value sent from payer (final_value_msat) and routing fees
2096 // for the last node in the RouteHint. We need to just add the fees to
2097 // route through the current node so that the preceding node (next iteration)
2099 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2100 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2101 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2103 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
2104 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
2105 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
2106 .checked_add(hop_htlc_minimum_msat_inc);
2107 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
2109 if idx == route.0.len() - 1 {
2110 // The last hop in this iterator is the first hop in
2111 // overall RouteHint.
2112 // If this hop connects to a node with which we have a direct channel,
2113 // ignore the network graph and, if the last hop was added, add our
2114 // direct channel to the candidate set.
2116 // Note that we *must* check if the last hop was added as `add_entry`
2117 // always assumes that the third argument is a node to which we have a
2119 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2120 sort_first_hop_channels(first_channels, &used_liquidities,
2121 recommended_value_msat, our_node_pubkey);
2122 for details in first_channels {
2123 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2124 add_entry!(first_hop_candidate, our_node_id,
2125 NodeId::from_pubkey(&hop.src_node_id),
2126 aggregate_next_hops_fee_msat,
2127 aggregate_path_contribution_msat,
2128 aggregate_next_hops_path_htlc_minimum_msat,
2129 aggregate_next_hops_path_penalty_msat,
2130 aggregate_next_hops_cltv_delta,
2131 aggregate_next_hops_path_length);
2139 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2141 // At this point, targets are filled with the data from first and
2142 // last hops communicated by the caller, and the payment receiver.
2143 let mut found_new_path = false;
2146 // If this loop terminates due the exhaustion of targets, two situations are possible:
2147 // - not enough outgoing liquidity:
2148 // 0 < already_collected_value_msat < final_value_msat
2149 // - enough outgoing liquidity:
2150 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2151 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2152 // paths_collection will be stopped because found_new_path==false.
2153 // This is not necessarily a routing failure.
2154 '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() {
2156 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2157 // traversing the graph and arrange the path out of what we found.
2158 if node_id == our_node_id {
2159 let mut new_entry = dist.remove(&our_node_id).unwrap();
2160 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2163 let mut features_set = false;
2164 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
2165 for details in first_channels {
2166 if let Some(scid) = ordered_hops.last().unwrap().0.candidate.short_channel_id() {
2167 if details.get_outbound_payment_scid().unwrap() == scid {
2168 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2169 features_set = true;
2176 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
2177 if let Some(node_info) = node.announcement_info.as_ref() {
2178 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2180 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2183 // We can fill in features for everything except hops which were
2184 // provided via the invoice we're paying. We could guess based on the
2185 // recipient's features but for now we simply avoid guessing at all.
2189 // Means we succesfully traversed from the payer to the payee, now
2190 // save this path for the payment route. Also, update the liquidity
2191 // remaining on the used hops, so that we take them into account
2192 // while looking for more paths.
2193 if ordered_hops.last().unwrap().0.node_id == maybe_dummy_payee_node_id {
2197 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
2198 Some(payment_hop) => payment_hop,
2199 // We can't arrive at None because, if we ever add an entry to targets,
2200 // we also fill in the entry in dist (see add_entry!).
2201 None => unreachable!(),
2203 // We "propagate" the fees one hop backward (topologically) here,
2204 // so that fees paid for a HTLC forwarding on the current channel are
2205 // associated with the previous channel (where they will be subtracted).
2206 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2207 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2209 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2210 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2212 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2213 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2215 let mut payment_path = PaymentPath {hops: ordered_hops};
2217 // We could have possibly constructed a slightly inconsistent path: since we reduce
2218 // value being transferred along the way, we could have violated htlc_minimum_msat
2219 // on some channels we already passed (assuming dest->source direction). Here, we
2220 // recompute the fees again, so that if that's the case, we match the currently
2221 // underpaid htlc_minimum_msat with fees.
2222 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2223 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
2224 payment_path.update_value_and_recompute_fees(value_contribution_msat);
2226 // Since a path allows to transfer as much value as
2227 // the smallest channel it has ("bottleneck"), we should recompute
2228 // the fees so sender HTLC don't overpay fees when traversing
2229 // larger channels than the bottleneck. This may happen because
2230 // when we were selecting those channels we were not aware how much value
2231 // this path will transfer, and the relative fee for them
2232 // might have been computed considering a larger value.
2233 // Remember that we used these channels so that we don't rely
2234 // on the same liquidity in future paths.
2235 let mut prevented_redundant_path_selection = false;
2236 let prev_hop_iter = core::iter::once(&our_node_id)
2237 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
2238 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
2239 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2240 let used_liquidity_msat = used_liquidities
2241 .entry(hop.candidate.id(*prev_hop < hop.node_id))
2242 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2243 .or_insert(spent_on_hop_msat);
2244 let hop_capacity = hop.candidate.effective_capacity();
2245 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2246 if *used_liquidity_msat == hop_max_msat {
2247 // If this path used all of this channel's available liquidity, we know
2248 // this path will not be selected again in the next loop iteration.
2249 prevented_redundant_path_selection = true;
2251 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2253 if !prevented_redundant_path_selection {
2254 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2255 // we'll probably end up picking the same path again on the next iteration.
2256 // Decrease the available liquidity of a hop in the middle of the path.
2257 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2258 let exhausted = u64::max_value();
2259 log_trace!(logger, "Disabling route candidate {} for future path building iterations to
2260 avoid duplicates.", LoggedCandidateHop(victim_candidate));
2261 *used_liquidities.entry(victim_candidate.id(false)).or_default() = exhausted;
2262 *used_liquidities.entry(victim_candidate.id(true)).or_default() = exhausted;
2265 // Track the total amount all our collected paths allow to send so that we know
2266 // when to stop looking for more paths
2267 already_collected_value_msat += value_contribution_msat;
2269 payment_paths.push(payment_path);
2270 found_new_path = true;
2271 break 'path_construction;
2274 // If we found a path back to the payee, we shouldn't try to process it again. This is
2275 // the equivalent of the `elem.was_processed` check in
2276 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2277 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2279 // Otherwise, since the current target node is not us,
2280 // keep "unrolling" the payment graph from payee to payer by
2281 // finding a way to reach the current target from the payer side.
2282 match network_nodes.get(&node_id) {
2285 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2286 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2287 total_cltv_delta, path_length_to_node);
2293 if !found_new_path && channel_saturation_pow_half != 0 {
2294 channel_saturation_pow_half = 0;
2295 continue 'paths_collection;
2297 // If we don't support MPP, no use trying to gather more value ever.
2298 break 'paths_collection;
2302 // Stop either when the recommended value is reached or if no new path was found in this
2304 // In the latter case, making another path finding attempt won't help,
2305 // because we deterministically terminated the search due to low liquidity.
2306 if !found_new_path && channel_saturation_pow_half != 0 {
2307 channel_saturation_pow_half = 0;
2308 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2309 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2310 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2311 break 'paths_collection;
2312 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2313 // Further, if this was our first walk of the graph, and we weren't limited by an
2314 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2315 // limited by an htlc_minimum_msat value, find another path with a higher value,
2316 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2317 // still keeping a lower total fee than this path.
2318 if !hit_minimum_limit {
2319 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2320 break 'paths_collection;
2322 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
2323 path_value_msat = recommended_value_msat;
2328 if payment_paths.len() == 0 {
2329 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2332 if already_collected_value_msat < final_value_msat {
2333 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2337 let mut selected_route = payment_paths;
2339 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2340 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2342 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2343 // the value they contribute towards the payment amount.
2344 // We sort in descending order as we will remove from the front in `retain`, next.
2345 selected_route.sort_unstable_by(|a, b|
2346 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2347 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2350 // We should make sure that at least 1 path left.
2351 let mut paths_left = selected_route.len();
2352 selected_route.retain(|path| {
2353 if paths_left == 1 {
2356 let path_value_msat = path.get_value_msat();
2357 if path_value_msat <= overpaid_value_msat {
2358 overpaid_value_msat -= path_value_msat;
2364 debug_assert!(selected_route.len() > 0);
2366 if overpaid_value_msat != 0 {
2368 // Now, subtract the remaining overpaid value from the most-expensive path.
2369 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2370 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2371 selected_route.sort_unstable_by(|a, b| {
2372 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2373 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2374 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2376 let expensive_payment_path = selected_route.first_mut().unwrap();
2378 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2379 // can't go negative.
2380 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2381 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2385 // Sort by the path itself and combine redundant paths.
2386 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2387 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2389 selected_route.sort_unstable_by_key(|path| {
2390 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2391 debug_assert!(path.hops.len() <= key.len());
2392 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id(true)).zip(key.iter_mut()) {
2397 for idx in 0..(selected_route.len() - 1) {
2398 if idx + 1 >= selected_route.len() { break; }
2399 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id)),
2400 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id))) {
2401 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2402 selected_route[idx].update_value_and_recompute_fees(new_value);
2403 selected_route.remove(idx + 1);
2407 let mut paths = Vec::new();
2408 for payment_path in selected_route {
2409 let mut hops = Vec::with_capacity(payment_path.hops.len());
2410 for (hop, node_features) in payment_path.hops.iter()
2411 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2413 hops.push(RouteHop {
2414 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)})?,
2415 node_features: node_features.clone(),
2416 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2417 channel_features: hop.candidate.features(),
2418 fee_msat: hop.fee_msat,
2419 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2422 let mut final_cltv_delta = final_cltv_expiry_delta;
2423 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2424 if let Some(blinded_path) = h.candidate.blinded_path() {
2425 final_cltv_delta = h.candidate.cltv_expiry_delta();
2427 hops: blinded_path.blinded_hops.clone(),
2428 blinding_point: blinded_path.blinding_point,
2429 excess_final_cltv_expiry_delta: 0,
2430 final_value_msat: h.fee_msat,
2434 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2435 // applicable for the previous hop.
2436 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2437 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2440 paths.push(Path { hops, blinded_tail });
2442 // Make sure we would never create a route with more paths than we allow.
2443 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2445 if let Some(node_features) = payment_params.payee.node_features() {
2446 for path in paths.iter_mut() {
2447 path.hops.last_mut().unwrap().node_features = node_features.clone();
2451 let route = Route { paths, payment_params: Some(payment_params.clone()) };
2452 log_info!(logger, "Got route: {}", log_route!(route));
2456 // When an adversarial intermediary node observes a payment, it may be able to infer its
2457 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2458 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2459 // payment path by adding a randomized 'shadow route' offset to the final hop.
2460 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2461 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2463 let network_channels = network_graph.channels();
2464 let network_nodes = network_graph.nodes();
2466 for path in route.paths.iter_mut() {
2467 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2469 // Remember the last three nodes of the random walk and avoid looping back on them.
2470 // Init with the last three nodes from the actual path, if possible.
2471 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2472 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2473 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2475 // Choose the last publicly known node as the starting point for the random walk.
2476 let mut cur_hop: Option<NodeId> = None;
2477 let mut path_nonce = [0u8; 12];
2478 if let Some(starting_hop) = path.hops.iter().rev()
2479 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2480 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2481 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2484 // Init PRNG with the path-dependant nonce, which is static for private paths.
2485 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2486 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2488 // Pick a random path length in [1 .. 3]
2489 prng.process_in_place(&mut random_path_bytes);
2490 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2492 for random_hop in 0..random_walk_length {
2493 // If we don't find a suitable offset in the public network graph, we default to
2494 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2495 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2497 if let Some(cur_node_id) = cur_hop {
2498 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2499 // Randomly choose the next unvisited hop.
2500 prng.process_in_place(&mut random_path_bytes);
2501 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2502 .checked_rem(cur_node.channels.len())
2503 .and_then(|index| cur_node.channels.get(index))
2504 .and_then(|id| network_channels.get(id)) {
2505 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2506 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2507 nodes_to_avoid[random_hop] = *next_id;
2508 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2509 cur_hop = Some(*next_id);
2516 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2517 .checked_add(random_hop_offset)
2518 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2521 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2522 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2523 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2525 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2526 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2527 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2528 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2529 max_path_offset = cmp::max(
2530 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2531 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2532 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2534 // Add 'shadow' CLTV offset to the final hop
2535 if let Some(tail) = path.blinded_tail.as_mut() {
2536 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2537 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2539 if let Some(last_hop) = path.hops.last_mut() {
2540 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2541 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2546 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2547 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2549 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2550 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2551 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2552 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2553 ) -> Result<Route, LightningError>
2554 where L::Target: Logger, GL::Target: Logger {
2555 let graph_lock = network_graph.read_only();
2556 let mut route = build_route_from_hops_internal(
2557 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
2558 route_params.final_value_msat, logger, random_seed_bytes)?;
2559 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2563 fn build_route_from_hops_internal<L: Deref>(
2564 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
2565 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, logger: L,
2566 random_seed_bytes: &[u8; 32]
2567 ) -> Result<Route, LightningError> where L::Target: Logger {
2570 our_node_id: NodeId,
2571 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2574 impl Score for HopScorer {
2575 type ScoreParams = ();
2576 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2577 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2579 let mut cur_id = self.our_node_id;
2580 for i in 0..self.hop_ids.len() {
2581 if let Some(next_id) = self.hop_ids[i] {
2582 if cur_id == *source && next_id == *target {
2593 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
2595 fn payment_path_successful(&mut self, _path: &Path) {}
2597 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
2599 fn probe_successful(&mut self, _path: &Path) {}
2602 impl<'a> Writeable for HopScorer {
2604 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2609 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2610 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2613 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2614 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2615 for i in 0..hops.len() {
2616 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2619 let scorer = HopScorer { our_node_id, hop_ids };
2621 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
2622 logger, &scorer, &(), random_seed_bytes)
2627 use crate::blinded_path::{BlindedHop, BlindedPath};
2628 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2629 use crate::routing::utxo::UtxoResult;
2630 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2631 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2632 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
2633 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, Score, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2634 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2635 use crate::chain::transaction::OutPoint;
2636 use crate::sign::EntropySource;
2637 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2638 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2639 use crate::ln::channelmanager;
2640 use crate::offers::invoice::BlindedPayInfo;
2641 use crate::util::config::UserConfig;
2642 use crate::util::test_utils as ln_test_utils;
2643 use crate::util::chacha20::ChaCha20;
2644 use crate::util::ser::{Readable, Writeable};
2646 use crate::util::ser::Writer;
2648 use bitcoin::hashes::Hash;
2649 use bitcoin::network::constants::Network;
2650 use bitcoin::blockdata::constants::genesis_block;
2651 use bitcoin::blockdata::script::Builder;
2652 use bitcoin::blockdata::opcodes;
2653 use bitcoin::blockdata::transaction::TxOut;
2657 use bitcoin::secp256k1::{PublicKey,SecretKey};
2658 use bitcoin::secp256k1::Secp256k1;
2660 use crate::io::Cursor;
2661 use crate::prelude::*;
2662 use crate::sync::Arc;
2664 use core::convert::TryInto;
2666 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2667 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2668 channelmanager::ChannelDetails {
2669 channel_id: [0; 32],
2670 counterparty: channelmanager::ChannelCounterparty {
2673 unspendable_punishment_reserve: 0,
2674 forwarding_info: None,
2675 outbound_htlc_minimum_msat: None,
2676 outbound_htlc_maximum_msat: None,
2678 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2681 outbound_scid_alias: None,
2682 inbound_scid_alias: None,
2683 channel_value_satoshis: 0,
2686 outbound_capacity_msat,
2687 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2688 next_outbound_htlc_minimum_msat: 0,
2689 inbound_capacity_msat: 42,
2690 unspendable_punishment_reserve: None,
2691 confirmations_required: None,
2692 confirmations: None,
2693 force_close_spend_delay: None,
2694 is_outbound: true, is_channel_ready: true,
2695 is_usable: true, is_public: true,
2696 inbound_htlc_minimum_msat: None,
2697 inbound_htlc_maximum_msat: None,
2699 feerate_sat_per_1000_weight: None,
2700 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
2705 fn simple_route_test() {
2706 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2707 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2708 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2709 let scorer = ln_test_utils::TestScorer::new();
2710 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2711 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2713 // Simple route to 2 via 1
2715 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) {
2716 assert_eq!(err, "Cannot send a payment of 0 msat");
2717 } else { panic!(); }
2719 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2720 assert_eq!(route.paths[0].hops.len(), 2);
2722 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2723 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2724 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2725 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2726 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2727 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2729 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2730 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2731 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2732 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2733 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2734 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2738 fn invalid_first_hop_test() {
2739 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2740 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2741 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2742 let scorer = ln_test_utils::TestScorer::new();
2743 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2744 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2746 // Simple route to 2 via 1
2748 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2750 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2751 get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2752 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2753 } else { panic!(); }
2755 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2756 assert_eq!(route.paths[0].hops.len(), 2);
2760 fn htlc_minimum_test() {
2761 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2762 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2763 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2764 let scorer = ln_test_utils::TestScorer::new();
2765 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2766 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2768 // Simple route to 2 via 1
2770 // Disable other paths
2771 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2772 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2773 short_channel_id: 12,
2775 flags: 2, // to disable
2776 cltv_expiry_delta: 0,
2777 htlc_minimum_msat: 0,
2778 htlc_maximum_msat: MAX_VALUE_MSAT,
2780 fee_proportional_millionths: 0,
2781 excess_data: Vec::new()
2783 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2784 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2785 short_channel_id: 3,
2787 flags: 2, // to disable
2788 cltv_expiry_delta: 0,
2789 htlc_minimum_msat: 0,
2790 htlc_maximum_msat: MAX_VALUE_MSAT,
2792 fee_proportional_millionths: 0,
2793 excess_data: Vec::new()
2795 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2796 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2797 short_channel_id: 13,
2799 flags: 2, // to disable
2800 cltv_expiry_delta: 0,
2801 htlc_minimum_msat: 0,
2802 htlc_maximum_msat: MAX_VALUE_MSAT,
2804 fee_proportional_millionths: 0,
2805 excess_data: Vec::new()
2807 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2808 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2809 short_channel_id: 6,
2811 flags: 2, // to disable
2812 cltv_expiry_delta: 0,
2813 htlc_minimum_msat: 0,
2814 htlc_maximum_msat: MAX_VALUE_MSAT,
2816 fee_proportional_millionths: 0,
2817 excess_data: Vec::new()
2819 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2820 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2821 short_channel_id: 7,
2823 flags: 2, // to disable
2824 cltv_expiry_delta: 0,
2825 htlc_minimum_msat: 0,
2826 htlc_maximum_msat: MAX_VALUE_MSAT,
2828 fee_proportional_millionths: 0,
2829 excess_data: Vec::new()
2832 // Check against amount_to_transfer_over_msat.
2833 // Set minimal HTLC of 200_000_000 msat.
2834 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2835 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2836 short_channel_id: 2,
2839 cltv_expiry_delta: 0,
2840 htlc_minimum_msat: 200_000_000,
2841 htlc_maximum_msat: MAX_VALUE_MSAT,
2843 fee_proportional_millionths: 0,
2844 excess_data: Vec::new()
2847 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2849 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2850 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2851 short_channel_id: 4,
2854 cltv_expiry_delta: 0,
2855 htlc_minimum_msat: 0,
2856 htlc_maximum_msat: 199_999_999,
2858 fee_proportional_millionths: 0,
2859 excess_data: Vec::new()
2862 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2863 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) {
2864 assert_eq!(err, "Failed to find a path to the given destination");
2865 } else { panic!(); }
2867 // Lift the restriction on the first hop.
2868 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2869 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2870 short_channel_id: 2,
2873 cltv_expiry_delta: 0,
2874 htlc_minimum_msat: 0,
2875 htlc_maximum_msat: MAX_VALUE_MSAT,
2877 fee_proportional_millionths: 0,
2878 excess_data: Vec::new()
2881 // A payment above the minimum should pass
2882 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 199_999_999, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2883 assert_eq!(route.paths[0].hops.len(), 2);
2887 fn htlc_minimum_overpay_test() {
2888 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2889 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2890 let config = UserConfig::default();
2891 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
2892 let scorer = ln_test_utils::TestScorer::new();
2893 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2894 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2896 // A route to node#2 via two paths.
2897 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2898 // Thus, they can't send 60 without overpaying.
2899 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2900 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2901 short_channel_id: 2,
2904 cltv_expiry_delta: 0,
2905 htlc_minimum_msat: 35_000,
2906 htlc_maximum_msat: 40_000,
2908 fee_proportional_millionths: 0,
2909 excess_data: Vec::new()
2911 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2912 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2913 short_channel_id: 12,
2916 cltv_expiry_delta: 0,
2917 htlc_minimum_msat: 35_000,
2918 htlc_maximum_msat: 40_000,
2920 fee_proportional_millionths: 0,
2921 excess_data: Vec::new()
2925 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2926 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2927 short_channel_id: 13,
2930 cltv_expiry_delta: 0,
2931 htlc_minimum_msat: 0,
2932 htlc_maximum_msat: MAX_VALUE_MSAT,
2934 fee_proportional_millionths: 0,
2935 excess_data: Vec::new()
2937 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2938 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2939 short_channel_id: 4,
2942 cltv_expiry_delta: 0,
2943 htlc_minimum_msat: 0,
2944 htlc_maximum_msat: MAX_VALUE_MSAT,
2946 fee_proportional_millionths: 0,
2947 excess_data: Vec::new()
2950 // Disable other paths
2951 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2952 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2953 short_channel_id: 1,
2955 flags: 2, // to disable
2956 cltv_expiry_delta: 0,
2957 htlc_minimum_msat: 0,
2958 htlc_maximum_msat: MAX_VALUE_MSAT,
2960 fee_proportional_millionths: 0,
2961 excess_data: Vec::new()
2964 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2965 // Overpay fees to hit htlc_minimum_msat.
2966 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
2967 // TODO: this could be better balanced to overpay 10k and not 15k.
2968 assert_eq!(overpaid_fees, 15_000);
2970 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2971 // while taking even more fee to match htlc_minimum_msat.
2972 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2973 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2974 short_channel_id: 12,
2977 cltv_expiry_delta: 0,
2978 htlc_minimum_msat: 65_000,
2979 htlc_maximum_msat: 80_000,
2981 fee_proportional_millionths: 0,
2982 excess_data: Vec::new()
2984 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2985 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2986 short_channel_id: 2,
2989 cltv_expiry_delta: 0,
2990 htlc_minimum_msat: 0,
2991 htlc_maximum_msat: MAX_VALUE_MSAT,
2993 fee_proportional_millionths: 0,
2994 excess_data: Vec::new()
2996 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2997 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2998 short_channel_id: 4,
3001 cltv_expiry_delta: 0,
3002 htlc_minimum_msat: 0,
3003 htlc_maximum_msat: MAX_VALUE_MSAT,
3005 fee_proportional_millionths: 100_000,
3006 excess_data: Vec::new()
3009 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3010 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3011 assert_eq!(route.paths.len(), 1);
3012 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3013 let fees = route.paths[0].hops[0].fee_msat;
3014 assert_eq!(fees, 5_000);
3016 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3017 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3018 // the other channel.
3019 assert_eq!(route.paths.len(), 1);
3020 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3021 let fees = route.paths[0].hops[0].fee_msat;
3022 assert_eq!(fees, 5_000);
3026 fn disable_channels_test() {
3027 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3028 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3029 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3030 let scorer = ln_test_utils::TestScorer::new();
3031 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3032 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3034 // // Disable channels 4 and 12 by flags=2
3035 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3036 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3037 short_channel_id: 4,
3039 flags: 2, // to disable
3040 cltv_expiry_delta: 0,
3041 htlc_minimum_msat: 0,
3042 htlc_maximum_msat: MAX_VALUE_MSAT,
3044 fee_proportional_millionths: 0,
3045 excess_data: Vec::new()
3047 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3048 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3049 short_channel_id: 12,
3051 flags: 2, // to disable
3052 cltv_expiry_delta: 0,
3053 htlc_minimum_msat: 0,
3054 htlc_maximum_msat: MAX_VALUE_MSAT,
3056 fee_proportional_millionths: 0,
3057 excess_data: Vec::new()
3060 // If all the channels require some features we don't understand, route should fail
3061 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) {
3062 assert_eq!(err, "Failed to find a path to the given destination");
3063 } else { panic!(); }
3065 // If we specify a channel to node7, that overrides our local channel view and that gets used
3066 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3067 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();
3068 assert_eq!(route.paths[0].hops.len(), 2);
3070 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3071 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3072 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3073 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3074 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3075 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3077 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3078 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3079 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3080 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3081 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3082 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3086 fn disable_node_test() {
3087 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3088 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3089 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3090 let scorer = ln_test_utils::TestScorer::new();
3091 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3092 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3094 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3095 let mut unknown_features = NodeFeatures::empty();
3096 unknown_features.set_unknown_feature_required();
3097 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3098 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3099 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3101 // If all nodes require some features we don't understand, route should fail
3102 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) {
3103 assert_eq!(err, "Failed to find a path to the given destination");
3104 } else { panic!(); }
3106 // If we specify a channel to node7, that overrides our local channel view and that gets used
3107 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3108 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();
3109 assert_eq!(route.paths[0].hops.len(), 2);
3111 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3112 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3113 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3114 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3115 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3116 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3118 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3119 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3120 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3121 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3122 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3123 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3125 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3126 // naively) assume that the user checked the feature bits on the invoice, which override
3127 // the node_announcement.
3131 fn our_chans_test() {
3132 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3133 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3134 let scorer = ln_test_utils::TestScorer::new();
3135 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3136 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3138 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3139 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3140 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3141 assert_eq!(route.paths[0].hops.len(), 3);
3143 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3144 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3145 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3146 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3147 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3148 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3150 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3151 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3152 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3153 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3154 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3155 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3157 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3158 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3159 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3160 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3161 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3162 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3164 // If we specify a channel to node7, that overrides our local channel view and that gets used
3165 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3166 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3167 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();
3168 assert_eq!(route.paths[0].hops.len(), 2);
3170 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3171 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3172 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3173 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3174 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3175 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3177 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3178 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3179 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3180 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3181 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3182 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3185 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3186 let zero_fees = RoutingFees {
3188 proportional_millionths: 0,
3190 vec![RouteHint(vec![RouteHintHop {
3191 src_node_id: nodes[3],
3192 short_channel_id: 8,
3194 cltv_expiry_delta: (8 << 4) | 1,
3195 htlc_minimum_msat: None,
3196 htlc_maximum_msat: None,
3198 ]), RouteHint(vec![RouteHintHop {
3199 src_node_id: nodes[4],
3200 short_channel_id: 9,
3203 proportional_millionths: 0,
3205 cltv_expiry_delta: (9 << 4) | 1,
3206 htlc_minimum_msat: None,
3207 htlc_maximum_msat: None,
3208 }]), RouteHint(vec![RouteHintHop {
3209 src_node_id: nodes[5],
3210 short_channel_id: 10,
3212 cltv_expiry_delta: (10 << 4) | 1,
3213 htlc_minimum_msat: None,
3214 htlc_maximum_msat: None,
3218 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3219 let zero_fees = RoutingFees {
3221 proportional_millionths: 0,
3223 vec![RouteHint(vec![RouteHintHop {
3224 src_node_id: nodes[2],
3225 short_channel_id: 5,
3228 proportional_millionths: 0,
3230 cltv_expiry_delta: (5 << 4) | 1,
3231 htlc_minimum_msat: None,
3232 htlc_maximum_msat: None,
3234 src_node_id: nodes[3],
3235 short_channel_id: 8,
3237 cltv_expiry_delta: (8 << 4) | 1,
3238 htlc_minimum_msat: None,
3239 htlc_maximum_msat: None,
3241 ]), RouteHint(vec![RouteHintHop {
3242 src_node_id: nodes[4],
3243 short_channel_id: 9,
3246 proportional_millionths: 0,
3248 cltv_expiry_delta: (9 << 4) | 1,
3249 htlc_minimum_msat: None,
3250 htlc_maximum_msat: None,
3251 }]), RouteHint(vec![RouteHintHop {
3252 src_node_id: nodes[5],
3253 short_channel_id: 10,
3255 cltv_expiry_delta: (10 << 4) | 1,
3256 htlc_minimum_msat: None,
3257 htlc_maximum_msat: None,
3262 fn partial_route_hint_test() {
3263 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3264 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3265 let scorer = ln_test_utils::TestScorer::new();
3266 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3267 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3269 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3270 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3271 // RouteHint may be partially used by the algo to build the best path.
3273 // First check that last hop can't have its source as the payee.
3274 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3275 src_node_id: nodes[6],
3276 short_channel_id: 8,
3279 proportional_millionths: 0,
3281 cltv_expiry_delta: (8 << 4) | 1,
3282 htlc_minimum_msat: None,
3283 htlc_maximum_msat: None,
3286 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3287 invalid_last_hops.push(invalid_last_hop);
3289 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(invalid_last_hops).unwrap();
3290 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) {
3291 assert_eq!(err, "Route hint cannot have the payee as the source.");
3292 } else { panic!(); }
3295 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3296 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3297 assert_eq!(route.paths[0].hops.len(), 5);
3299 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3300 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3301 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3302 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3303 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3304 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3306 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3307 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3308 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3309 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3310 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3311 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3313 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3314 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3315 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3316 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3317 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3318 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3320 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3321 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3322 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3323 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3324 // If we have a peer in the node map, we'll use their features here since we don't have
3325 // a way of figuring out their features from the invoice:
3326 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3327 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3329 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3330 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3331 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3332 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3333 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3334 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3337 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3338 let zero_fees = RoutingFees {
3340 proportional_millionths: 0,
3342 vec![RouteHint(vec![RouteHintHop {
3343 src_node_id: nodes[3],
3344 short_channel_id: 8,
3346 cltv_expiry_delta: (8 << 4) | 1,
3347 htlc_minimum_msat: None,
3348 htlc_maximum_msat: None,
3349 }]), RouteHint(vec![
3351 ]), RouteHint(vec![RouteHintHop {
3352 src_node_id: nodes[5],
3353 short_channel_id: 10,
3355 cltv_expiry_delta: (10 << 4) | 1,
3356 htlc_minimum_msat: None,
3357 htlc_maximum_msat: None,
3362 fn ignores_empty_last_hops_test() {
3363 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3364 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3365 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3366 let scorer = ln_test_utils::TestScorer::new();
3367 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3368 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3370 // Test handling of an empty RouteHint passed in Invoice.
3372 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3373 assert_eq!(route.paths[0].hops.len(), 5);
3375 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3376 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3377 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3378 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3379 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3380 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3382 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3383 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3384 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3385 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3386 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3387 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3389 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3390 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3391 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3392 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3393 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3394 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3396 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3397 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3398 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3399 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3400 // If we have a peer in the node map, we'll use their features here since we don't have
3401 // a way of figuring out their features from the invoice:
3402 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3403 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3405 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3406 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3407 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3408 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3409 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3410 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3413 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3415 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3416 let zero_fees = RoutingFees {
3418 proportional_millionths: 0,
3420 vec![RouteHint(vec![RouteHintHop {
3421 src_node_id: hint_hops[0],
3422 short_channel_id: 0xff00,
3425 proportional_millionths: 0,
3427 cltv_expiry_delta: (5 << 4) | 1,
3428 htlc_minimum_msat: None,
3429 htlc_maximum_msat: None,
3431 src_node_id: hint_hops[1],
3432 short_channel_id: 0xff01,
3434 cltv_expiry_delta: (8 << 4) | 1,
3435 htlc_minimum_msat: None,
3436 htlc_maximum_msat: None,
3441 fn multi_hint_last_hops_test() {
3442 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3443 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3444 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3445 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3446 let scorer = ln_test_utils::TestScorer::new();
3447 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3448 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3449 // Test through channels 2, 3, 0xff00, 0xff01.
3450 // Test shows that multiple hop hints are considered.
3452 // Disabling channels 6 & 7 by flags=2
3453 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3454 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3455 short_channel_id: 6,
3457 flags: 2, // to disable
3458 cltv_expiry_delta: 0,
3459 htlc_minimum_msat: 0,
3460 htlc_maximum_msat: MAX_VALUE_MSAT,
3462 fee_proportional_millionths: 0,
3463 excess_data: Vec::new()
3465 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3466 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3467 short_channel_id: 7,
3469 flags: 2, // to disable
3470 cltv_expiry_delta: 0,
3471 htlc_minimum_msat: 0,
3472 htlc_maximum_msat: MAX_VALUE_MSAT,
3474 fee_proportional_millionths: 0,
3475 excess_data: Vec::new()
3478 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3479 assert_eq!(route.paths[0].hops.len(), 4);
3481 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3482 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3483 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3484 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3485 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3486 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3488 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3489 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3490 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3491 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3492 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3493 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3495 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3496 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3497 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3498 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3499 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3500 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3502 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3503 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3504 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3505 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3506 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3507 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3511 fn private_multi_hint_last_hops_test() {
3512 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3513 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3515 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3516 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3518 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3519 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3520 let scorer = ln_test_utils::TestScorer::new();
3521 // Test through channels 2, 3, 0xff00, 0xff01.
3522 // Test shows that multiple hop hints are considered.
3524 // Disabling channels 6 & 7 by flags=2
3525 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3526 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3527 short_channel_id: 6,
3529 flags: 2, // to disable
3530 cltv_expiry_delta: 0,
3531 htlc_minimum_msat: 0,
3532 htlc_maximum_msat: MAX_VALUE_MSAT,
3534 fee_proportional_millionths: 0,
3535 excess_data: Vec::new()
3537 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3538 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3539 short_channel_id: 7,
3541 flags: 2, // to disable
3542 cltv_expiry_delta: 0,
3543 htlc_minimum_msat: 0,
3544 htlc_maximum_msat: MAX_VALUE_MSAT,
3546 fee_proportional_millionths: 0,
3547 excess_data: Vec::new()
3550 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &[42u8; 32]).unwrap();
3551 assert_eq!(route.paths[0].hops.len(), 4);
3553 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3554 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3555 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3556 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3557 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3558 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3560 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3561 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3562 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3563 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3564 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3565 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3567 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3568 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3569 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3570 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3571 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3572 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3574 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3575 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3576 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3577 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3578 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3579 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3582 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3583 let zero_fees = RoutingFees {
3585 proportional_millionths: 0,
3587 vec![RouteHint(vec![RouteHintHop {
3588 src_node_id: nodes[4],
3589 short_channel_id: 11,
3591 cltv_expiry_delta: (11 << 4) | 1,
3592 htlc_minimum_msat: None,
3593 htlc_maximum_msat: None,
3595 src_node_id: nodes[3],
3596 short_channel_id: 8,
3598 cltv_expiry_delta: (8 << 4) | 1,
3599 htlc_minimum_msat: None,
3600 htlc_maximum_msat: None,
3601 }]), RouteHint(vec![RouteHintHop {
3602 src_node_id: nodes[4],
3603 short_channel_id: 9,
3606 proportional_millionths: 0,
3608 cltv_expiry_delta: (9 << 4) | 1,
3609 htlc_minimum_msat: None,
3610 htlc_maximum_msat: None,
3611 }]), RouteHint(vec![RouteHintHop {
3612 src_node_id: nodes[5],
3613 short_channel_id: 10,
3615 cltv_expiry_delta: (10 << 4) | 1,
3616 htlc_minimum_msat: None,
3617 htlc_maximum_msat: None,
3622 fn last_hops_with_public_channel_test() {
3623 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3624 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3625 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
3626 let scorer = ln_test_utils::TestScorer::new();
3627 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3628 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3629 // This test shows that public routes can be present in the invoice
3630 // which would be handled in the same manner.
3632 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3633 assert_eq!(route.paths[0].hops.len(), 5);
3635 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3636 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3637 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3638 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3639 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3640 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3642 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3643 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3644 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3645 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3646 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3647 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3649 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3650 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3651 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3652 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3653 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3654 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3656 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3657 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3658 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3659 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3660 // If we have a peer in the node map, we'll use their features here since we don't have
3661 // a way of figuring out their features from the invoice:
3662 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3663 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3665 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3666 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3667 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3668 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3669 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3670 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3674 fn our_chans_last_hop_connect_test() {
3675 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3676 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3677 let scorer = ln_test_utils::TestScorer::new();
3678 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3679 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3681 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3682 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3683 let mut last_hops = last_hops(&nodes);
3684 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3685 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();
3686 assert_eq!(route.paths[0].hops.len(), 2);
3688 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3689 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3690 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3691 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3692 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3693 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3695 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3696 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3697 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3698 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3699 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3700 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3702 last_hops[0].0[0].fees.base_msat = 1000;
3704 // Revert to via 6 as the fee on 8 goes up
3705 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops).unwrap();
3706 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3707 assert_eq!(route.paths[0].hops.len(), 4);
3709 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3710 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3711 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
3712 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3713 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3714 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3716 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3717 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3718 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3719 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
3720 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3721 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3723 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
3724 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3725 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3726 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3727 // If we have a peer in the node map, we'll use their features here since we don't have
3728 // a way of figuring out their features from the invoice:
3729 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3730 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3732 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3733 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3734 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3735 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3736 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3737 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3739 // ...but still use 8 for larger payments as 6 has a variable feerate
3740 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3741 assert_eq!(route.paths[0].hops.len(), 5);
3743 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3744 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3745 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3746 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3747 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3748 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3750 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3751 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3752 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3753 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3754 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3755 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3757 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3758 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3759 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3760 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3761 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3762 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3764 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3765 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3766 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
3767 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3768 // If we have a peer in the node map, we'll use their features here since we don't have
3769 // a way of figuring out their features from the invoice:
3770 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3771 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3773 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3774 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3775 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
3776 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3777 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3778 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3781 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> {
3782 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3783 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3784 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3786 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3787 let last_hops = RouteHint(vec![RouteHintHop {
3788 src_node_id: middle_node_id,
3789 short_channel_id: 8,
3792 proportional_millionths: last_hop_fee_prop,
3794 cltv_expiry_delta: (8 << 4) | 1,
3795 htlc_minimum_msat: None,
3796 htlc_maximum_msat: last_hop_htlc_max,
3798 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
3799 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3800 let scorer = ln_test_utils::TestScorer::new();
3801 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3802 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3803 let logger = ln_test_utils::TestLogger::new();
3804 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3805 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3806 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, &logger, &scorer, &(), &random_seed_bytes);
3811 fn unannounced_path_test() {
3812 // We should be able to send a payment to a destination without any help of a routing graph
3813 // if we have a channel with a common counterparty that appears in the first and last hop
3815 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3817 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3818 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3819 assert_eq!(route.paths[0].hops.len(), 2);
3821 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
3822 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3823 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
3824 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3825 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
3826 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3828 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
3829 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3830 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
3831 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3832 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3833 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3837 fn overflow_unannounced_path_test_liquidity_underflow() {
3838 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3839 // the last-hop had a fee which overflowed a u64, we'd panic.
3840 // This was due to us adding the first-hop from us unconditionally, causing us to think
3841 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3842 // In this test, we previously hit a subtraction underflow due to having less available
3843 // liquidity at the last hop than 0.
3844 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());
3848 fn overflow_unannounced_path_test_feerate_overflow() {
3849 // This tests for the same case as above, except instead of hitting a subtraction
3850 // underflow, we hit a case where the fee charged at a hop overflowed.
3851 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());
3855 fn available_amount_while_routing_test() {
3856 // Tests whether we choose the correct available channel amount while routing.
3858 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3859 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3860 let scorer = ln_test_utils::TestScorer::new();
3861 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3862 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3863 let config = UserConfig::default();
3864 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3866 // We will use a simple single-path route from
3867 // our node to node2 via node0: channels {1, 3}.
3869 // First disable all other paths.
3870 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3871 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3872 short_channel_id: 2,
3875 cltv_expiry_delta: 0,
3876 htlc_minimum_msat: 0,
3877 htlc_maximum_msat: 100_000,
3879 fee_proportional_millionths: 0,
3880 excess_data: Vec::new()
3882 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3883 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3884 short_channel_id: 12,
3887 cltv_expiry_delta: 0,
3888 htlc_minimum_msat: 0,
3889 htlc_maximum_msat: 100_000,
3891 fee_proportional_millionths: 0,
3892 excess_data: Vec::new()
3895 // Make the first channel (#1) very permissive,
3896 // and we will be testing all limits on the second channel.
3897 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3898 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3899 short_channel_id: 1,
3902 cltv_expiry_delta: 0,
3903 htlc_minimum_msat: 0,
3904 htlc_maximum_msat: 1_000_000_000,
3906 fee_proportional_millionths: 0,
3907 excess_data: Vec::new()
3910 // First, let's see if routing works if we have absolutely no idea about the available amount.
3911 // In this case, it should be set to 250_000 sats.
3912 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3913 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3914 short_channel_id: 3,
3917 cltv_expiry_delta: 0,
3918 htlc_minimum_msat: 0,
3919 htlc_maximum_msat: 250_000_000,
3921 fee_proportional_millionths: 0,
3922 excess_data: Vec::new()
3926 // Attempt to route more than available results in a failure.
3927 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3928 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3929 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3930 } else { panic!(); }
3934 // Now, attempt to route an exact amount we have should be fine.
3935 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000_000, Arc::clone(&logger), &scorer, &(),&random_seed_bytes).unwrap();
3936 assert_eq!(route.paths.len(), 1);
3937 let path = route.paths.last().unwrap();
3938 assert_eq!(path.hops.len(), 2);
3939 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3940 assert_eq!(path.final_value_msat(), 250_000_000);
3943 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3944 // Disable channel #1 and use another first hop.
3945 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3946 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3947 short_channel_id: 1,
3950 cltv_expiry_delta: 0,
3951 htlc_minimum_msat: 0,
3952 htlc_maximum_msat: 1_000_000_000,
3954 fee_proportional_millionths: 0,
3955 excess_data: Vec::new()
3958 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3959 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3962 // Attempt to route more than available results in a failure.
3963 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3964 &our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3965 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3966 } else { panic!(); }
3970 // Now, attempt to route an exact amount we have should be fine.
3971 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();
3972 assert_eq!(route.paths.len(), 1);
3973 let path = route.paths.last().unwrap();
3974 assert_eq!(path.hops.len(), 2);
3975 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3976 assert_eq!(path.final_value_msat(), 200_000_000);
3979 // Enable channel #1 back.
3980 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3981 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3982 short_channel_id: 1,
3985 cltv_expiry_delta: 0,
3986 htlc_minimum_msat: 0,
3987 htlc_maximum_msat: 1_000_000_000,
3989 fee_proportional_millionths: 0,
3990 excess_data: Vec::new()
3994 // Now let's see if routing works if we know only htlc_maximum_msat.
3995 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3996 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3997 short_channel_id: 3,
4000 cltv_expiry_delta: 0,
4001 htlc_minimum_msat: 0,
4002 htlc_maximum_msat: 15_000,
4004 fee_proportional_millionths: 0,
4005 excess_data: Vec::new()
4009 // Attempt to route more than available results in a failure.
4010 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4011 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4012 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4013 } else { panic!(); }
4017 // Now, attempt to route an exact amount we have should be fine.
4018 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4019 assert_eq!(route.paths.len(), 1);
4020 let path = route.paths.last().unwrap();
4021 assert_eq!(path.hops.len(), 2);
4022 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4023 assert_eq!(path.final_value_msat(), 15_000);
4026 // Now let's see if routing works if we know only capacity from the UTXO.
4028 // We can't change UTXO capacity on the fly, so we'll disable
4029 // the existing channel and add another one with the capacity we need.
4030 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4031 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4032 short_channel_id: 3,
4035 cltv_expiry_delta: 0,
4036 htlc_minimum_msat: 0,
4037 htlc_maximum_msat: MAX_VALUE_MSAT,
4039 fee_proportional_millionths: 0,
4040 excess_data: Vec::new()
4043 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4044 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4045 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4046 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4047 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4049 *chain_monitor.utxo_ret.lock().unwrap() =
4050 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4051 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4053 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4054 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4055 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4056 short_channel_id: 333,
4059 cltv_expiry_delta: (3 << 4) | 1,
4060 htlc_minimum_msat: 0,
4061 htlc_maximum_msat: 15_000,
4063 fee_proportional_millionths: 0,
4064 excess_data: Vec::new()
4066 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4067 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4068 short_channel_id: 333,
4071 cltv_expiry_delta: (3 << 4) | 2,
4072 htlc_minimum_msat: 0,
4073 htlc_maximum_msat: 15_000,
4075 fee_proportional_millionths: 0,
4076 excess_data: Vec::new()
4080 // Attempt to route more than available results in a failure.
4081 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4082 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4083 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4084 } else { panic!(); }
4088 // Now, attempt to route an exact amount we have should be fine.
4089 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4090 assert_eq!(route.paths.len(), 1);
4091 let path = route.paths.last().unwrap();
4092 assert_eq!(path.hops.len(), 2);
4093 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4094 assert_eq!(path.final_value_msat(), 15_000);
4097 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4098 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4099 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4100 short_channel_id: 333,
4103 cltv_expiry_delta: 0,
4104 htlc_minimum_msat: 0,
4105 htlc_maximum_msat: 10_000,
4107 fee_proportional_millionths: 0,
4108 excess_data: Vec::new()
4112 // Attempt to route more than available results in a failure.
4113 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4114 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4115 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4116 } else { panic!(); }
4120 // Now, attempt to route an exact amount we have should be fine.
4121 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4122 assert_eq!(route.paths.len(), 1);
4123 let path = route.paths.last().unwrap();
4124 assert_eq!(path.hops.len(), 2);
4125 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4126 assert_eq!(path.final_value_msat(), 10_000);
4131 fn available_liquidity_last_hop_test() {
4132 // Check that available liquidity properly limits the path even when only
4133 // one of the latter hops is limited.
4134 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4135 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4136 let scorer = ln_test_utils::TestScorer::new();
4137 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4138 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4139 let config = UserConfig::default();
4140 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4142 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4143 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4144 // Total capacity: 50 sats.
4146 // Disable other potential paths.
4147 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4148 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4149 short_channel_id: 2,
4152 cltv_expiry_delta: 0,
4153 htlc_minimum_msat: 0,
4154 htlc_maximum_msat: 100_000,
4156 fee_proportional_millionths: 0,
4157 excess_data: Vec::new()
4159 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4160 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4161 short_channel_id: 7,
4164 cltv_expiry_delta: 0,
4165 htlc_minimum_msat: 0,
4166 htlc_maximum_msat: 100_000,
4168 fee_proportional_millionths: 0,
4169 excess_data: Vec::new()
4174 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4175 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4176 short_channel_id: 12,
4179 cltv_expiry_delta: 0,
4180 htlc_minimum_msat: 0,
4181 htlc_maximum_msat: 100_000,
4183 fee_proportional_millionths: 0,
4184 excess_data: Vec::new()
4186 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4187 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4188 short_channel_id: 13,
4191 cltv_expiry_delta: 0,
4192 htlc_minimum_msat: 0,
4193 htlc_maximum_msat: 100_000,
4195 fee_proportional_millionths: 0,
4196 excess_data: Vec::new()
4199 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4200 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4201 short_channel_id: 6,
4204 cltv_expiry_delta: 0,
4205 htlc_minimum_msat: 0,
4206 htlc_maximum_msat: 50_000,
4208 fee_proportional_millionths: 0,
4209 excess_data: Vec::new()
4211 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4212 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4213 short_channel_id: 11,
4216 cltv_expiry_delta: 0,
4217 htlc_minimum_msat: 0,
4218 htlc_maximum_msat: 100_000,
4220 fee_proportional_millionths: 0,
4221 excess_data: Vec::new()
4224 // Attempt to route more than available results in a failure.
4225 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4226 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4227 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4228 } else { panic!(); }
4232 // Now, attempt to route 49 sats (just a bit below the capacity).
4233 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4234 assert_eq!(route.paths.len(), 1);
4235 let mut total_amount_paid_msat = 0;
4236 for path in &route.paths {
4237 assert_eq!(path.hops.len(), 4);
4238 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4239 total_amount_paid_msat += path.final_value_msat();
4241 assert_eq!(total_amount_paid_msat, 49_000);
4245 // Attempt to route an exact amount is also fine
4246 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4247 assert_eq!(route.paths.len(), 1);
4248 let mut total_amount_paid_msat = 0;
4249 for path in &route.paths {
4250 assert_eq!(path.hops.len(), 4);
4251 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4252 total_amount_paid_msat += path.final_value_msat();
4254 assert_eq!(total_amount_paid_msat, 50_000);
4259 fn ignore_fee_first_hop_test() {
4260 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4261 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4262 let scorer = ln_test_utils::TestScorer::new();
4263 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4264 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4265 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4267 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4268 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4269 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4270 short_channel_id: 1,
4273 cltv_expiry_delta: 0,
4274 htlc_minimum_msat: 0,
4275 htlc_maximum_msat: 100_000,
4276 fee_base_msat: 1_000_000,
4277 fee_proportional_millionths: 0,
4278 excess_data: Vec::new()
4280 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4281 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4282 short_channel_id: 3,
4285 cltv_expiry_delta: 0,
4286 htlc_minimum_msat: 0,
4287 htlc_maximum_msat: 50_000,
4289 fee_proportional_millionths: 0,
4290 excess_data: Vec::new()
4294 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4295 assert_eq!(route.paths.len(), 1);
4296 let mut total_amount_paid_msat = 0;
4297 for path in &route.paths {
4298 assert_eq!(path.hops.len(), 2);
4299 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4300 total_amount_paid_msat += path.final_value_msat();
4302 assert_eq!(total_amount_paid_msat, 50_000);
4307 fn simple_mpp_route_test() {
4308 let (secp_ctx, _, _, _, _) = build_graph();
4309 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4310 let config = UserConfig::default();
4311 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4312 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4313 do_simple_mpp_route_test(clear_payment_params);
4315 // MPP to a 1-hop blinded path for nodes[2]
4316 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
4317 let blinded_path = BlindedPath {
4318 introduction_node_id: nodes[2],
4319 blinding_point: ln_test_utils::pubkey(42),
4320 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4322 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4324 fee_proportional_millionths: 0,
4325 htlc_minimum_msat: 0,
4326 htlc_maximum_msat: 0,
4327 cltv_expiry_delta: 0,
4328 features: BlindedHopFeatures::empty(),
4330 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4331 .with_bolt12_features(bolt12_features.clone()).unwrap();
4332 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4334 // MPP to 3 2-hop blinded paths
4335 let mut blinded_path_node_0 = blinded_path.clone();
4336 blinded_path_node_0.introduction_node_id = nodes[0];
4337 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4338 let mut node_0_payinfo = blinded_payinfo.clone();
4339 node_0_payinfo.htlc_maximum_msat = 50_000;
4341 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4342 blinded_path_node_7.introduction_node_id = nodes[7];
4343 let mut node_7_payinfo = blinded_payinfo.clone();
4344 node_7_payinfo.htlc_maximum_msat = 60_000;
4346 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4347 blinded_path_node_1.introduction_node_id = nodes[1];
4348 let mut node_1_payinfo = blinded_payinfo.clone();
4349 node_1_payinfo.htlc_maximum_msat = 180_000;
4351 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4353 (node_0_payinfo, blinded_path_node_0),
4354 (node_7_payinfo, blinded_path_node_7),
4355 (node_1_payinfo, blinded_path_node_1)
4357 .with_bolt12_features(bolt12_features).unwrap();
4358 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4362 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4363 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4364 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4365 let scorer = ln_test_utils::TestScorer::new();
4366 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4367 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4369 // We need a route consisting of 3 paths:
4370 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4371 // To achieve this, the amount being transferred should be around
4372 // the total capacity of these 3 paths.
4374 // First, we set limits on these (previously unlimited) channels.
4375 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4377 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4378 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4379 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4380 short_channel_id: 1,
4383 cltv_expiry_delta: 0,
4384 htlc_minimum_msat: 0,
4385 htlc_maximum_msat: 100_000,
4387 fee_proportional_millionths: 0,
4388 excess_data: Vec::new()
4390 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4391 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4392 short_channel_id: 3,
4395 cltv_expiry_delta: 0,
4396 htlc_minimum_msat: 0,
4397 htlc_maximum_msat: 50_000,
4399 fee_proportional_millionths: 0,
4400 excess_data: Vec::new()
4403 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4404 // (total limit 60).
4405 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4406 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4407 short_channel_id: 12,
4410 cltv_expiry_delta: 0,
4411 htlc_minimum_msat: 0,
4412 htlc_maximum_msat: 60_000,
4414 fee_proportional_millionths: 0,
4415 excess_data: Vec::new()
4417 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4418 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4419 short_channel_id: 13,
4422 cltv_expiry_delta: 0,
4423 htlc_minimum_msat: 0,
4424 htlc_maximum_msat: 60_000,
4426 fee_proportional_millionths: 0,
4427 excess_data: Vec::new()
4430 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4431 // (total capacity 180 sats).
4432 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4433 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4434 short_channel_id: 2,
4437 cltv_expiry_delta: 0,
4438 htlc_minimum_msat: 0,
4439 htlc_maximum_msat: 200_000,
4441 fee_proportional_millionths: 0,
4442 excess_data: Vec::new()
4444 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4445 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4446 short_channel_id: 4,
4449 cltv_expiry_delta: 0,
4450 htlc_minimum_msat: 0,
4451 htlc_maximum_msat: 180_000,
4453 fee_proportional_millionths: 0,
4454 excess_data: Vec::new()
4458 // Attempt to route more than available results in a failure.
4459 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4460 &our_id, &payment_params, &network_graph.read_only(), None, 300_000,
4461 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4462 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4463 } else { panic!(); }
4467 // Attempt to route while setting max_path_count to 0 results in a failure.
4468 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4469 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4470 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100,
4471 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4472 assert_eq!(err, "Can't find a route with no paths allowed.");
4473 } else { panic!(); }
4477 // Attempt to route while setting max_path_count to 3 results in a failure.
4478 // This is the case because the minimal_value_contribution_msat would require each path
4479 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4480 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4481 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4482 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000,
4483 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4484 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4485 } else { panic!(); }
4489 // Now, attempt to route 250 sats (just a bit below the capacity).
4490 // Our algorithm should provide us with these 3 paths.
4491 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4492 250_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4493 assert_eq!(route.paths.len(), 3);
4494 let mut total_amount_paid_msat = 0;
4495 for path in &route.paths {
4496 if let Some(bt) = &path.blinded_tail {
4497 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4499 assert_eq!(path.hops.len(), 2);
4500 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4502 total_amount_paid_msat += path.final_value_msat();
4504 assert_eq!(total_amount_paid_msat, 250_000);
4508 // Attempt to route an exact amount is also fine
4509 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4510 290_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4511 assert_eq!(route.paths.len(), 3);
4512 let mut total_amount_paid_msat = 0;
4513 for path in &route.paths {
4514 if payment_params.payee.blinded_route_hints().len() != 0 {
4515 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
4516 if let Some(bt) = &path.blinded_tail {
4517 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4518 if bt.hops.len() > 1 {
4519 assert_eq!(path.hops.last().unwrap().pubkey,
4520 payment_params.payee.blinded_route_hints().iter()
4521 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
4522 .map(|(_, p)| p.introduction_node_id).unwrap());
4524 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4527 assert_eq!(path.hops.len(), 2);
4528 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4530 total_amount_paid_msat += path.final_value_msat();
4532 assert_eq!(total_amount_paid_msat, 290_000);
4537 fn long_mpp_route_test() {
4538 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4539 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4540 let scorer = ln_test_utils::TestScorer::new();
4541 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4542 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4543 let config = UserConfig::default();
4544 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4546 // We need a route consisting of 3 paths:
4547 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4548 // Note that these paths overlap (channels 5, 12, 13).
4549 // We will route 300 sats.
4550 // Each path will have 100 sats capacity, those channels which
4551 // are used twice will have 200 sats capacity.
4553 // Disable other potential paths.
4554 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4555 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4556 short_channel_id: 2,
4559 cltv_expiry_delta: 0,
4560 htlc_minimum_msat: 0,
4561 htlc_maximum_msat: 100_000,
4563 fee_proportional_millionths: 0,
4564 excess_data: Vec::new()
4566 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4567 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4568 short_channel_id: 7,
4571 cltv_expiry_delta: 0,
4572 htlc_minimum_msat: 0,
4573 htlc_maximum_msat: 100_000,
4575 fee_proportional_millionths: 0,
4576 excess_data: Vec::new()
4579 // Path via {node0, node2} is channels {1, 3, 5}.
4580 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4581 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4582 short_channel_id: 1,
4585 cltv_expiry_delta: 0,
4586 htlc_minimum_msat: 0,
4587 htlc_maximum_msat: 100_000,
4589 fee_proportional_millionths: 0,
4590 excess_data: Vec::new()
4592 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4593 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4594 short_channel_id: 3,
4597 cltv_expiry_delta: 0,
4598 htlc_minimum_msat: 0,
4599 htlc_maximum_msat: 100_000,
4601 fee_proportional_millionths: 0,
4602 excess_data: Vec::new()
4605 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4606 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4607 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4608 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4609 short_channel_id: 5,
4612 cltv_expiry_delta: 0,
4613 htlc_minimum_msat: 0,
4614 htlc_maximum_msat: 200_000,
4616 fee_proportional_millionths: 0,
4617 excess_data: Vec::new()
4620 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4621 // Add 100 sats to the capacities of {12, 13}, because these channels
4622 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4623 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4624 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4625 short_channel_id: 12,
4628 cltv_expiry_delta: 0,
4629 htlc_minimum_msat: 0,
4630 htlc_maximum_msat: 200_000,
4632 fee_proportional_millionths: 0,
4633 excess_data: Vec::new()
4635 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4636 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4637 short_channel_id: 13,
4640 cltv_expiry_delta: 0,
4641 htlc_minimum_msat: 0,
4642 htlc_maximum_msat: 200_000,
4644 fee_proportional_millionths: 0,
4645 excess_data: Vec::new()
4648 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4649 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4650 short_channel_id: 6,
4653 cltv_expiry_delta: 0,
4654 htlc_minimum_msat: 0,
4655 htlc_maximum_msat: 100_000,
4657 fee_proportional_millionths: 0,
4658 excess_data: Vec::new()
4660 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4661 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4662 short_channel_id: 11,
4665 cltv_expiry_delta: 0,
4666 htlc_minimum_msat: 0,
4667 htlc_maximum_msat: 100_000,
4669 fee_proportional_millionths: 0,
4670 excess_data: Vec::new()
4673 // Path via {node7, node2} is channels {12, 13, 5}.
4674 // We already limited them to 200 sats (they are used twice for 100 sats).
4675 // Nothing to do here.
4678 // Attempt to route more than available results in a failure.
4679 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4680 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4681 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4682 } else { panic!(); }
4686 // Now, attempt to route 300 sats (exact amount we can route).
4687 // Our algorithm should provide us with these 3 paths, 100 sats each.
4688 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4689 assert_eq!(route.paths.len(), 3);
4691 let mut total_amount_paid_msat = 0;
4692 for path in &route.paths {
4693 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4694 total_amount_paid_msat += path.final_value_msat();
4696 assert_eq!(total_amount_paid_msat, 300_000);
4702 fn mpp_cheaper_route_test() {
4703 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4704 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4705 let scorer = ln_test_utils::TestScorer::new();
4706 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4707 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4708 let config = UserConfig::default();
4709 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4711 // This test checks that if we have two cheaper paths and one more expensive path,
4712 // so that liquidity-wise any 2 of 3 combination is sufficient,
4713 // two cheaper paths will be taken.
4714 // These paths have equal available liquidity.
4716 // We need a combination of 3 paths:
4717 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4718 // Note that these paths overlap (channels 5, 12, 13).
4719 // Each path will have 100 sats capacity, those channels which
4720 // are used twice will have 200 sats capacity.
4722 // Disable other potential paths.
4723 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4724 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4725 short_channel_id: 2,
4728 cltv_expiry_delta: 0,
4729 htlc_minimum_msat: 0,
4730 htlc_maximum_msat: 100_000,
4732 fee_proportional_millionths: 0,
4733 excess_data: Vec::new()
4735 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4736 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4737 short_channel_id: 7,
4740 cltv_expiry_delta: 0,
4741 htlc_minimum_msat: 0,
4742 htlc_maximum_msat: 100_000,
4744 fee_proportional_millionths: 0,
4745 excess_data: Vec::new()
4748 // Path via {node0, node2} is channels {1, 3, 5}.
4749 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4750 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4751 short_channel_id: 1,
4754 cltv_expiry_delta: 0,
4755 htlc_minimum_msat: 0,
4756 htlc_maximum_msat: 100_000,
4758 fee_proportional_millionths: 0,
4759 excess_data: Vec::new()
4761 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4762 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4763 short_channel_id: 3,
4766 cltv_expiry_delta: 0,
4767 htlc_minimum_msat: 0,
4768 htlc_maximum_msat: 100_000,
4770 fee_proportional_millionths: 0,
4771 excess_data: Vec::new()
4774 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4775 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4776 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4777 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4778 short_channel_id: 5,
4781 cltv_expiry_delta: 0,
4782 htlc_minimum_msat: 0,
4783 htlc_maximum_msat: 200_000,
4785 fee_proportional_millionths: 0,
4786 excess_data: Vec::new()
4789 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4790 // Add 100 sats to the capacities of {12, 13}, because these channels
4791 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4792 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4793 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4794 short_channel_id: 12,
4797 cltv_expiry_delta: 0,
4798 htlc_minimum_msat: 0,
4799 htlc_maximum_msat: 200_000,
4801 fee_proportional_millionths: 0,
4802 excess_data: Vec::new()
4804 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4805 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4806 short_channel_id: 13,
4809 cltv_expiry_delta: 0,
4810 htlc_minimum_msat: 0,
4811 htlc_maximum_msat: 200_000,
4813 fee_proportional_millionths: 0,
4814 excess_data: Vec::new()
4817 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4818 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4819 short_channel_id: 6,
4822 cltv_expiry_delta: 0,
4823 htlc_minimum_msat: 0,
4824 htlc_maximum_msat: 100_000,
4825 fee_base_msat: 1_000,
4826 fee_proportional_millionths: 0,
4827 excess_data: Vec::new()
4829 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4830 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4831 short_channel_id: 11,
4834 cltv_expiry_delta: 0,
4835 htlc_minimum_msat: 0,
4836 htlc_maximum_msat: 100_000,
4838 fee_proportional_millionths: 0,
4839 excess_data: Vec::new()
4842 // Path via {node7, node2} is channels {12, 13, 5}.
4843 // We already limited them to 200 sats (they are used twice for 100 sats).
4844 // Nothing to do here.
4847 // Now, attempt to route 180 sats.
4848 // Our algorithm should provide us with these 2 paths.
4849 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4850 assert_eq!(route.paths.len(), 2);
4852 let mut total_value_transferred_msat = 0;
4853 let mut total_paid_msat = 0;
4854 for path in &route.paths {
4855 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4856 total_value_transferred_msat += path.final_value_msat();
4857 for hop in &path.hops {
4858 total_paid_msat += hop.fee_msat;
4861 // If we paid fee, this would be higher.
4862 assert_eq!(total_value_transferred_msat, 180_000);
4863 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4864 assert_eq!(total_fees_paid, 0);
4869 fn fees_on_mpp_route_test() {
4870 // This test makes sure that MPP algorithm properly takes into account
4871 // fees charged on the channels, by making the fees impactful:
4872 // if the fee is not properly accounted for, the behavior is different.
4873 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4874 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4875 let scorer = ln_test_utils::TestScorer::new();
4876 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4877 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4878 let config = UserConfig::default();
4879 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4881 // We need a route consisting of 2 paths:
4882 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4883 // We will route 200 sats, Each path will have 100 sats capacity.
4885 // This test is not particularly stable: e.g.,
4886 // there's a way to route via {node0, node2, node4}.
4887 // It works while pathfinding is deterministic, but can be broken otherwise.
4888 // It's fine to ignore this concern for now.
4890 // Disable other potential paths.
4891 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4892 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4893 short_channel_id: 2,
4896 cltv_expiry_delta: 0,
4897 htlc_minimum_msat: 0,
4898 htlc_maximum_msat: 100_000,
4900 fee_proportional_millionths: 0,
4901 excess_data: Vec::new()
4904 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4905 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4906 short_channel_id: 7,
4909 cltv_expiry_delta: 0,
4910 htlc_minimum_msat: 0,
4911 htlc_maximum_msat: 100_000,
4913 fee_proportional_millionths: 0,
4914 excess_data: Vec::new()
4917 // Path via {node0, node2} is channels {1, 3, 5}.
4918 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4919 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4920 short_channel_id: 1,
4923 cltv_expiry_delta: 0,
4924 htlc_minimum_msat: 0,
4925 htlc_maximum_msat: 100_000,
4927 fee_proportional_millionths: 0,
4928 excess_data: Vec::new()
4930 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4931 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4932 short_channel_id: 3,
4935 cltv_expiry_delta: 0,
4936 htlc_minimum_msat: 0,
4937 htlc_maximum_msat: 100_000,
4939 fee_proportional_millionths: 0,
4940 excess_data: Vec::new()
4943 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4944 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4945 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4946 short_channel_id: 5,
4949 cltv_expiry_delta: 0,
4950 htlc_minimum_msat: 0,
4951 htlc_maximum_msat: 100_000,
4953 fee_proportional_millionths: 0,
4954 excess_data: Vec::new()
4957 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4958 // All channels should be 100 sats capacity. But for the fee experiment,
4959 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4960 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4961 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4962 // so no matter how large are other channels,
4963 // the whole path will be limited by 100 sats with just these 2 conditions:
4964 // - channel 12 capacity is 250 sats
4965 // - fee for channel 6 is 150 sats
4966 // Let's test this by enforcing these 2 conditions and removing other limits.
4967 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4968 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4969 short_channel_id: 12,
4972 cltv_expiry_delta: 0,
4973 htlc_minimum_msat: 0,
4974 htlc_maximum_msat: 250_000,
4976 fee_proportional_millionths: 0,
4977 excess_data: Vec::new()
4979 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4980 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4981 short_channel_id: 13,
4984 cltv_expiry_delta: 0,
4985 htlc_minimum_msat: 0,
4986 htlc_maximum_msat: MAX_VALUE_MSAT,
4988 fee_proportional_millionths: 0,
4989 excess_data: Vec::new()
4992 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4993 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4994 short_channel_id: 6,
4997 cltv_expiry_delta: 0,
4998 htlc_minimum_msat: 0,
4999 htlc_maximum_msat: MAX_VALUE_MSAT,
5000 fee_base_msat: 150_000,
5001 fee_proportional_millionths: 0,
5002 excess_data: Vec::new()
5004 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5005 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5006 short_channel_id: 11,
5009 cltv_expiry_delta: 0,
5010 htlc_minimum_msat: 0,
5011 htlc_maximum_msat: MAX_VALUE_MSAT,
5013 fee_proportional_millionths: 0,
5014 excess_data: Vec::new()
5018 // Attempt to route more than available results in a failure.
5019 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5020 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5021 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5022 } else { panic!(); }
5026 // Now, attempt to route 200 sats (exact amount we can route).
5027 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5028 assert_eq!(route.paths.len(), 2);
5030 let mut total_amount_paid_msat = 0;
5031 for path in &route.paths {
5032 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5033 total_amount_paid_msat += path.final_value_msat();
5035 assert_eq!(total_amount_paid_msat, 200_000);
5036 assert_eq!(route.get_total_fees(), 150_000);
5041 fn mpp_with_last_hops() {
5042 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5043 // via a single last-hop route hint, we'd fail to route if we first collected routes
5044 // totaling close but not quite enough to fund the full payment.
5046 // This was because we considered last-hop hints to have exactly the sought payment amount
5047 // instead of the amount we were trying to collect, needlessly limiting our path searching
5048 // at the very first hop.
5050 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5051 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5052 // to only have the remaining to-collect amount in available liquidity.
5054 // This bug appeared in production in some specific channel configurations.
5055 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5056 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5057 let scorer = ln_test_utils::TestScorer::new();
5058 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5059 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5060 let config = UserConfig::default();
5061 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5062 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5063 src_node_id: nodes[2],
5064 short_channel_id: 42,
5065 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5066 cltv_expiry_delta: 42,
5067 htlc_minimum_msat: None,
5068 htlc_maximum_msat: None,
5069 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5071 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5072 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5073 // would first use the no-fee route and then fail to find a path along the second route as
5074 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5075 // under 5% of our payment amount.
5076 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5077 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5078 short_channel_id: 1,
5081 cltv_expiry_delta: (5 << 4) | 5,
5082 htlc_minimum_msat: 0,
5083 htlc_maximum_msat: 99_000,
5084 fee_base_msat: u32::max_value(),
5085 fee_proportional_millionths: u32::max_value(),
5086 excess_data: Vec::new()
5088 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5089 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5090 short_channel_id: 2,
5093 cltv_expiry_delta: (5 << 4) | 3,
5094 htlc_minimum_msat: 0,
5095 htlc_maximum_msat: 99_000,
5096 fee_base_msat: u32::max_value(),
5097 fee_proportional_millionths: u32::max_value(),
5098 excess_data: Vec::new()
5100 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5101 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5102 short_channel_id: 4,
5105 cltv_expiry_delta: (4 << 4) | 1,
5106 htlc_minimum_msat: 0,
5107 htlc_maximum_msat: MAX_VALUE_MSAT,
5109 fee_proportional_millionths: 0,
5110 excess_data: Vec::new()
5112 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5113 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5114 short_channel_id: 13,
5116 flags: 0|2, // Channel disabled
5117 cltv_expiry_delta: (13 << 4) | 1,
5118 htlc_minimum_msat: 0,
5119 htlc_maximum_msat: MAX_VALUE_MSAT,
5121 fee_proportional_millionths: 2000000,
5122 excess_data: Vec::new()
5125 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5127 let mut route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5128 assert_eq!(route.paths.len(), 2);
5129 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5130 // Paths are manually ordered ordered by SCID, so:
5131 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5132 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5133 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5134 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5135 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5136 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5137 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5138 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5139 assert_eq!(route.get_total_fees(), 1);
5140 assert_eq!(route.get_total_amount(), 100_000);
5144 fn drop_lowest_channel_mpp_route_test() {
5145 // This test checks that low-capacity channel is dropped when after
5146 // path finding we realize that we found more capacity than we need.
5147 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5148 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5149 let scorer = ln_test_utils::TestScorer::new();
5150 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5151 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5152 let config = UserConfig::default();
5153 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5154 .with_max_channel_saturation_power_of_half(0);
5156 // We need a route consisting of 3 paths:
5157 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5159 // The first and the second paths should be sufficient, but the third should be
5160 // cheaper, so that we select it but drop later.
5162 // First, we set limits on these (previously unlimited) channels.
5163 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5165 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5166 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5167 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5168 short_channel_id: 1,
5171 cltv_expiry_delta: 0,
5172 htlc_minimum_msat: 0,
5173 htlc_maximum_msat: 100_000,
5175 fee_proportional_millionths: 0,
5176 excess_data: Vec::new()
5178 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5179 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5180 short_channel_id: 3,
5183 cltv_expiry_delta: 0,
5184 htlc_minimum_msat: 0,
5185 htlc_maximum_msat: 50_000,
5187 fee_proportional_millionths: 0,
5188 excess_data: Vec::new()
5191 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5192 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5193 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5194 short_channel_id: 12,
5197 cltv_expiry_delta: 0,
5198 htlc_minimum_msat: 0,
5199 htlc_maximum_msat: 60_000,
5201 fee_proportional_millionths: 0,
5202 excess_data: Vec::new()
5204 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5205 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5206 short_channel_id: 13,
5209 cltv_expiry_delta: 0,
5210 htlc_minimum_msat: 0,
5211 htlc_maximum_msat: 60_000,
5213 fee_proportional_millionths: 0,
5214 excess_data: Vec::new()
5217 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5218 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5219 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5220 short_channel_id: 2,
5223 cltv_expiry_delta: 0,
5224 htlc_minimum_msat: 0,
5225 htlc_maximum_msat: 20_000,
5227 fee_proportional_millionths: 0,
5228 excess_data: Vec::new()
5230 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5231 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5232 short_channel_id: 4,
5235 cltv_expiry_delta: 0,
5236 htlc_minimum_msat: 0,
5237 htlc_maximum_msat: 20_000,
5239 fee_proportional_millionths: 0,
5240 excess_data: Vec::new()
5244 // Attempt to route more than available results in a failure.
5245 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5246 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5247 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5248 } else { panic!(); }
5252 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5253 // Our algorithm should provide us with these 3 paths.
5254 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5255 assert_eq!(route.paths.len(), 3);
5256 let mut total_amount_paid_msat = 0;
5257 for path in &route.paths {
5258 assert_eq!(path.hops.len(), 2);
5259 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5260 total_amount_paid_msat += path.final_value_msat();
5262 assert_eq!(total_amount_paid_msat, 125_000);
5266 // Attempt to route without the last small cheap channel
5267 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5268 assert_eq!(route.paths.len(), 2);
5269 let mut total_amount_paid_msat = 0;
5270 for path in &route.paths {
5271 assert_eq!(path.hops.len(), 2);
5272 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5273 total_amount_paid_msat += path.final_value_msat();
5275 assert_eq!(total_amount_paid_msat, 90_000);
5280 fn min_criteria_consistency() {
5281 // Test that we don't use an inconsistent metric between updating and walking nodes during
5282 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5283 // was updated with a different criterion from the heap sorting, resulting in loops in
5284 // calculated paths. We test for that specific case here.
5286 // We construct a network that looks like this:
5288 // node2 -1(3)2- node3
5292 // node1 -1(5)2- node4 -1(1)2- node6
5298 // We create a loop on the side of our real path - our destination is node 6, with a
5299 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5300 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5301 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5302 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5303 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5304 // "previous hop" being set to node 3, creating a loop in the path.
5305 let secp_ctx = Secp256k1::new();
5306 let logger = Arc::new(ln_test_utils::TestLogger::new());
5307 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5308 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5309 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5310 let scorer = ln_test_utils::TestScorer::new();
5311 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5312 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5313 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5315 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5316 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5317 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5318 short_channel_id: 6,
5321 cltv_expiry_delta: (6 << 4) | 0,
5322 htlc_minimum_msat: 0,
5323 htlc_maximum_msat: MAX_VALUE_MSAT,
5325 fee_proportional_millionths: 0,
5326 excess_data: Vec::new()
5328 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5330 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5331 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5332 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5333 short_channel_id: 5,
5336 cltv_expiry_delta: (5 << 4) | 0,
5337 htlc_minimum_msat: 0,
5338 htlc_maximum_msat: MAX_VALUE_MSAT,
5340 fee_proportional_millionths: 0,
5341 excess_data: Vec::new()
5343 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5345 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5346 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5347 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5348 short_channel_id: 4,
5351 cltv_expiry_delta: (4 << 4) | 0,
5352 htlc_minimum_msat: 0,
5353 htlc_maximum_msat: MAX_VALUE_MSAT,
5355 fee_proportional_millionths: 0,
5356 excess_data: Vec::new()
5358 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5360 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5361 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5362 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5363 short_channel_id: 3,
5366 cltv_expiry_delta: (3 << 4) | 0,
5367 htlc_minimum_msat: 0,
5368 htlc_maximum_msat: MAX_VALUE_MSAT,
5370 fee_proportional_millionths: 0,
5371 excess_data: Vec::new()
5373 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5375 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5376 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5377 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5378 short_channel_id: 2,
5381 cltv_expiry_delta: (2 << 4) | 0,
5382 htlc_minimum_msat: 0,
5383 htlc_maximum_msat: MAX_VALUE_MSAT,
5385 fee_proportional_millionths: 0,
5386 excess_data: Vec::new()
5389 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5390 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5391 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5392 short_channel_id: 1,
5395 cltv_expiry_delta: (1 << 4) | 0,
5396 htlc_minimum_msat: 100,
5397 htlc_maximum_msat: MAX_VALUE_MSAT,
5399 fee_proportional_millionths: 0,
5400 excess_data: Vec::new()
5402 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5405 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5406 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5407 assert_eq!(route.paths.len(), 1);
5408 assert_eq!(route.paths[0].hops.len(), 3);
5410 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5411 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5412 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5413 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5414 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5415 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5417 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5418 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5419 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5420 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5421 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5422 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5424 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5425 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5426 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5427 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5428 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5429 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5435 fn exact_fee_liquidity_limit() {
5436 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5437 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5438 // we calculated fees on a higher value, resulting in us ignoring such paths.
5439 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5440 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5441 let scorer = ln_test_utils::TestScorer::new();
5442 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5443 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5444 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5446 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5448 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5449 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5450 short_channel_id: 2,
5453 cltv_expiry_delta: 0,
5454 htlc_minimum_msat: 0,
5455 htlc_maximum_msat: 85_000,
5457 fee_proportional_millionths: 0,
5458 excess_data: Vec::new()
5461 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5462 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5463 short_channel_id: 12,
5466 cltv_expiry_delta: (4 << 4) | 1,
5467 htlc_minimum_msat: 0,
5468 htlc_maximum_msat: 270_000,
5470 fee_proportional_millionths: 1000000,
5471 excess_data: Vec::new()
5475 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5476 // 200% fee charged channel 13 in the 1-to-2 direction.
5477 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5478 assert_eq!(route.paths.len(), 1);
5479 assert_eq!(route.paths[0].hops.len(), 2);
5481 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5482 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5483 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5484 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5485 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5486 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5488 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5489 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5490 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5491 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5492 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5493 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5498 fn htlc_max_reduction_below_min() {
5499 // Test that if, while walking the graph, we reduce the value being sent to meet an
5500 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5501 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5502 // resulting in us thinking there is no possible path, even if other paths exist.
5503 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5504 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5505 let scorer = ln_test_utils::TestScorer::new();
5506 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5507 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5508 let config = UserConfig::default();
5509 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5511 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5512 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5513 // then try to send 90_000.
5514 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5515 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5516 short_channel_id: 2,
5519 cltv_expiry_delta: 0,
5520 htlc_minimum_msat: 0,
5521 htlc_maximum_msat: 80_000,
5523 fee_proportional_millionths: 0,
5524 excess_data: Vec::new()
5526 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5527 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5528 short_channel_id: 4,
5531 cltv_expiry_delta: (4 << 4) | 1,
5532 htlc_minimum_msat: 90_000,
5533 htlc_maximum_msat: MAX_VALUE_MSAT,
5535 fee_proportional_millionths: 0,
5536 excess_data: Vec::new()
5540 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5541 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5542 // expensive) channels 12-13 path.
5543 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5544 assert_eq!(route.paths.len(), 1);
5545 assert_eq!(route.paths[0].hops.len(), 2);
5547 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5548 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5549 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5550 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5551 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5552 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5554 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5555 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5556 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5557 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5558 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5559 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5564 fn multiple_direct_first_hops() {
5565 // Previously we'd only ever considered one first hop path per counterparty.
5566 // However, as we don't restrict users to one channel per peer, we really need to support
5567 // looking at all first hop paths.
5568 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5569 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5570 // route over multiple channels with the same first hop.
5571 let secp_ctx = Secp256k1::new();
5572 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5573 let logger = Arc::new(ln_test_utils::TestLogger::new());
5574 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5575 let scorer = ln_test_utils::TestScorer::new();
5576 let config = UserConfig::default();
5577 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5578 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5579 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5582 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5583 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5584 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5585 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5586 assert_eq!(route.paths.len(), 1);
5587 assert_eq!(route.paths[0].hops.len(), 1);
5589 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5590 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5591 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5594 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5595 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5596 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5597 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5598 assert_eq!(route.paths.len(), 2);
5599 assert_eq!(route.paths[0].hops.len(), 1);
5600 assert_eq!(route.paths[1].hops.len(), 1);
5602 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5603 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5605 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5606 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5608 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5609 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5613 // If we have a bunch of outbound channels to the same node, where most are not
5614 // sufficient to pay the full payment, but one is, we should default to just using the
5615 // one single channel that has sufficient balance, avoiding MPP.
5617 // If we have several options above the 3xpayment value threshold, we should pick the
5618 // smallest of them, avoiding further fragmenting our available outbound balance to
5620 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5621 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5622 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5623 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5624 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5625 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5626 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5627 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5628 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5629 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5630 assert_eq!(route.paths.len(), 1);
5631 assert_eq!(route.paths[0].hops.len(), 1);
5633 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5634 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5635 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5640 fn prefers_shorter_route_with_higher_fees() {
5641 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5642 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5643 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5645 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5646 let scorer = ln_test_utils::TestScorer::new();
5647 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5648 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5649 let route = get_route(
5650 &our_id, &payment_params, &network_graph.read_only(), None, 100,
5651 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5653 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5655 assert_eq!(route.get_total_fees(), 100);
5656 assert_eq!(route.get_total_amount(), 100);
5657 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5659 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5660 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5661 let scorer = FixedPenaltyScorer::with_penalty(100);
5662 let route = get_route(
5663 &our_id, &payment_params, &network_graph.read_only(), None, 100,
5664 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5666 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5668 assert_eq!(route.get_total_fees(), 300);
5669 assert_eq!(route.get_total_amount(), 100);
5670 assert_eq!(path, vec![2, 4, 7, 10]);
5673 struct BadChannelScorer {
5674 short_channel_id: u64,
5678 impl Writeable for BadChannelScorer {
5679 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5681 impl Score for BadChannelScorer {
5682 type ScoreParams = ();
5683 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5684 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5687 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5688 fn payment_path_successful(&mut self, _path: &Path) {}
5689 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5690 fn probe_successful(&mut self, _path: &Path) {}
5693 struct BadNodeScorer {
5698 impl Writeable for BadNodeScorer {
5699 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5702 impl Score for BadNodeScorer {
5703 type ScoreParams = ();
5704 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5705 if *target == self.node_id { u64::max_value() } else { 0 }
5708 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5709 fn payment_path_successful(&mut self, _path: &Path) {}
5710 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5711 fn probe_successful(&mut self, _path: &Path) {}
5715 fn avoids_routing_through_bad_channels_and_nodes() {
5716 let (secp_ctx, network, _, _, logger) = build_graph();
5717 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5718 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5719 let network_graph = network.read_only();
5721 // A path to nodes[6] exists when no penalties are applied to any channel.
5722 let scorer = ln_test_utils::TestScorer::new();
5723 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5724 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5725 let route = get_route(
5726 &our_id, &payment_params, &network_graph, None, 100,
5727 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5729 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5731 assert_eq!(route.get_total_fees(), 100);
5732 assert_eq!(route.get_total_amount(), 100);
5733 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5735 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5736 let scorer = BadChannelScorer { short_channel_id: 6 };
5737 let route = get_route(
5738 &our_id, &payment_params, &network_graph, None, 100,
5739 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5741 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5743 assert_eq!(route.get_total_fees(), 300);
5744 assert_eq!(route.get_total_amount(), 100);
5745 assert_eq!(path, vec![2, 4, 7, 10]);
5747 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5748 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5750 &our_id, &payment_params, &network_graph, None, 100,
5751 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5753 Err(LightningError { err, .. } ) => {
5754 assert_eq!(err, "Failed to find a path to the given destination");
5756 Ok(_) => panic!("Expected error"),
5761 fn total_fees_single_path() {
5763 paths: vec![Path { hops: vec![
5765 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5766 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5767 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5770 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5771 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5772 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5775 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5776 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5777 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5779 ], blinded_tail: None }],
5780 payment_params: None,
5783 assert_eq!(route.get_total_fees(), 250);
5784 assert_eq!(route.get_total_amount(), 225);
5788 fn total_fees_multi_path() {
5790 paths: vec![Path { hops: vec![
5792 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5793 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5794 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5797 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5798 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5799 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5801 ], blinded_tail: None }, Path { hops: vec![
5803 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5804 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5805 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5808 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5809 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5810 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5812 ], blinded_tail: None }],
5813 payment_params: None,
5816 assert_eq!(route.get_total_fees(), 200);
5817 assert_eq!(route.get_total_amount(), 300);
5821 fn total_empty_route_no_panic() {
5822 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5823 // would both panic if the route was completely empty. We test to ensure they return 0
5824 // here, even though its somewhat nonsensical as a route.
5825 let route = Route { paths: Vec::new(), payment_params: None };
5827 assert_eq!(route.get_total_fees(), 0);
5828 assert_eq!(route.get_total_amount(), 0);
5832 fn limits_total_cltv_delta() {
5833 let (secp_ctx, network, _, _, logger) = build_graph();
5834 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5835 let network_graph = network.read_only();
5837 let scorer = ln_test_utils::TestScorer::new();
5839 // Make sure that generally there is at least one route available
5840 let feasible_max_total_cltv_delta = 1008;
5841 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5842 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5843 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5844 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5845 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5846 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5847 assert_ne!(path.len(), 0);
5849 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5850 let fail_max_total_cltv_delta = 23;
5851 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5852 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5853 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5855 Err(LightningError { err, .. } ) => {
5856 assert_eq!(err, "Failed to find a path to the given destination");
5858 Ok(_) => panic!("Expected error"),
5863 fn avoids_recently_failed_paths() {
5864 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5865 // randomly inserting channels into it until we can't find a route anymore.
5866 let (secp_ctx, network, _, _, logger) = build_graph();
5867 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5868 let network_graph = network.read_only();
5870 let scorer = ln_test_utils::TestScorer::new();
5871 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5872 .with_max_path_count(1);
5873 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5874 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5876 // We should be able to find a route initially, and then after we fail a few random
5877 // channels eventually we won't be able to any longer.
5878 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).is_ok());
5880 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5881 for chan in route.paths[0].hops.iter() {
5882 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5884 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5885 % route.paths[0].hops.len();
5886 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
5892 fn limits_path_length() {
5893 let (secp_ctx, network, _, _, logger) = build_line_graph();
5894 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5895 let network_graph = network.read_only();
5897 let scorer = ln_test_utils::TestScorer::new();
5898 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5899 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5901 // First check we can actually create a long route on this graph.
5902 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
5903 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100,
5904 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5905 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5906 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5908 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5909 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
5910 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100,
5911 Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5913 Err(LightningError { err, .. } ) => {
5914 assert_eq!(err, "Failed to find a path to the given destination");
5916 Ok(_) => panic!("Expected error"),
5921 fn adds_and_limits_cltv_offset() {
5922 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5923 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5925 let scorer = ln_test_utils::TestScorer::new();
5927 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5928 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5929 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5930 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5931 assert_eq!(route.paths.len(), 1);
5933 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5935 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5936 let mut route_default = route.clone();
5937 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5938 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5939 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5940 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5941 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5943 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5944 let mut route_limited = route.clone();
5945 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5946 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5947 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5948 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5949 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5953 fn adds_plausible_cltv_offset() {
5954 let (secp_ctx, network, _, _, logger) = build_graph();
5955 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5956 let network_graph = network.read_only();
5957 let network_nodes = network_graph.nodes();
5958 let network_channels = network_graph.channels();
5959 let scorer = ln_test_utils::TestScorer::new();
5960 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5961 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5962 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5964 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100,
5965 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5966 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5968 let mut path_plausibility = vec![];
5970 for p in route.paths {
5971 // 1. Select random observation point
5972 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5973 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5975 prng.process_in_place(&mut random_bytes);
5976 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
5977 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
5979 // 2. Calculate what CLTV expiry delta we would observe there
5980 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5982 // 3. Starting from the observation point, find candidate paths
5983 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5984 candidates.push_back((observation_point, vec![]));
5986 let mut found_plausible_candidate = false;
5988 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5989 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5990 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5991 found_plausible_candidate = true;
5992 break 'candidate_loop;
5996 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5997 for channel_id in &cur_node.channels {
5998 if let Some(channel_info) = network_channels.get(&channel_id) {
5999 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6000 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6001 if cur_path_cltv_deltas.iter().sum::<u32>()
6002 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6003 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6004 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6005 candidates.push_back((*next_id, new_path_cltv_deltas));
6013 path_plausibility.push(found_plausible_candidate);
6015 assert!(path_plausibility.iter().all(|x| *x));
6019 fn builds_correct_path_from_hops() {
6020 let (secp_ctx, network, _, _, logger) = build_graph();
6021 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6022 let network_graph = network.read_only();
6024 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6025 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6027 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6028 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6029 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
6030 &network_graph, 100, Arc::clone(&logger), &random_seed_bytes).unwrap();
6031 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6032 assert_eq!(hops.len(), route.paths[0].hops.len());
6033 for (idx, hop_pubkey) in hops.iter().enumerate() {
6034 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6039 fn avoids_saturating_channels() {
6040 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6041 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6042 let decay_params = ProbabilisticScoringDecayParameters::default();
6043 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6045 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6046 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6047 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6048 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6049 short_channel_id: 4,
6052 cltv_expiry_delta: (4 << 4) | 1,
6053 htlc_minimum_msat: 0,
6054 htlc_maximum_msat: 250_000_000,
6056 fee_proportional_millionths: 0,
6057 excess_data: Vec::new()
6059 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6060 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6061 short_channel_id: 13,
6064 cltv_expiry_delta: (13 << 4) | 1,
6065 htlc_minimum_msat: 0,
6066 htlc_maximum_msat: 250_000_000,
6068 fee_proportional_millionths: 0,
6069 excess_data: Vec::new()
6072 let config = UserConfig::default();
6073 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6074 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6075 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6076 // 100,000 sats is less than the available liquidity on each channel, set above.
6077 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();
6078 assert_eq!(route.paths.len(), 2);
6079 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6080 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6083 #[cfg(not(feature = "no-std"))]
6084 pub(super) fn random_init_seed() -> u64 {
6085 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6086 use core::hash::{BuildHasher, Hasher};
6087 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6088 println!("Using seed of {}", seed);
6093 #[cfg(not(feature = "no-std"))]
6094 fn generate_routes() {
6095 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6097 let logger = ln_test_utils::TestLogger::new();
6098 let graph = match super::bench_utils::read_network_graph(&logger) {
6106 let params = ProbabilisticScoringFeeParameters::default();
6107 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6108 let features = super::InvoiceFeatures::empty();
6110 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6114 #[cfg(not(feature = "no-std"))]
6115 fn generate_routes_mpp() {
6116 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6118 let logger = ln_test_utils::TestLogger::new();
6119 let graph = match super::bench_utils::read_network_graph(&logger) {
6127 let params = ProbabilisticScoringFeeParameters::default();
6128 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6129 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6131 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6135 #[cfg(not(feature = "no-std"))]
6136 fn generate_large_mpp_routes() {
6137 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6139 let logger = ln_test_utils::TestLogger::new();
6140 let graph = match super::bench_utils::read_network_graph(&logger) {
6148 let params = ProbabilisticScoringFeeParameters::default();
6149 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6150 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6152 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6156 fn honors_manual_penalties() {
6157 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6158 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6160 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6161 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6163 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6164 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6166 // First check set manual penalties are returned by the scorer.
6167 let usage = ChannelUsage {
6169 inflight_htlc_msat: 0,
6170 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6172 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6173 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6174 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
6176 // Then check we can get a normal route
6177 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
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());
6181 // Then check that we can't get a route if we ban an intermediate node.
6182 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6183 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6184 assert!(route.is_err());
6186 // Finally make sure we can route again, when we remove the ban.
6187 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6188 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6189 assert!(route.is_ok());
6193 fn abide_by_route_hint_max_htlc() {
6194 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6195 // params in the final route.
6196 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6197 let netgraph = network_graph.read_only();
6198 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6199 let scorer = ln_test_utils::TestScorer::new();
6200 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6201 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6202 let config = UserConfig::default();
6204 let max_htlc_msat = 50_000;
6205 let route_hint_1 = RouteHint(vec![RouteHintHop {
6206 src_node_id: nodes[2],
6207 short_channel_id: 42,
6210 proportional_millionths: 0,
6212 cltv_expiry_delta: 10,
6213 htlc_minimum_msat: None,
6214 htlc_maximum_msat: Some(max_htlc_msat),
6216 let dest_node_id = ln_test_utils::pubkey(42);
6217 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6218 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6219 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6221 // Make sure we'll error if our route hints don't have enough liquidity according to their
6222 // htlc_maximum_msat.
6223 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6224 &payment_params, &netgraph, None, max_htlc_msat + 1, Arc::clone(&logger), &scorer, &(),
6227 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6228 } else { panic!(); }
6230 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6231 let mut route_hint_2 = route_hint_1.clone();
6232 route_hint_2.0[0].short_channel_id = 43;
6233 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6234 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6235 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6236 let route = get_route(&our_id, &payment_params, &netgraph, None, max_htlc_msat + 1,
6237 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6238 assert_eq!(route.paths.len(), 2);
6239 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6240 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6244 fn direct_channel_to_hints_with_max_htlc() {
6245 // Check that if we have a first hop channel peer that's connected to multiple provided route
6246 // hints, that we properly split the payment between the route hints if needed.
6247 let logger = Arc::new(ln_test_utils::TestLogger::new());
6248 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6249 let scorer = ln_test_utils::TestScorer::new();
6250 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6251 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6252 let config = UserConfig::default();
6254 let our_node_id = ln_test_utils::pubkey(42);
6255 let intermed_node_id = ln_test_utils::pubkey(43);
6256 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6258 let amt_msat = 900_000;
6259 let max_htlc_msat = 500_000;
6260 let route_hint_1 = RouteHint(vec![RouteHintHop {
6261 src_node_id: intermed_node_id,
6262 short_channel_id: 44,
6265 proportional_millionths: 0,
6267 cltv_expiry_delta: 10,
6268 htlc_minimum_msat: None,
6269 htlc_maximum_msat: Some(max_htlc_msat),
6271 src_node_id: intermed_node_id,
6272 short_channel_id: 45,
6275 proportional_millionths: 0,
6277 cltv_expiry_delta: 10,
6278 htlc_minimum_msat: None,
6279 // Check that later route hint max htlcs don't override earlier ones
6280 htlc_maximum_msat: Some(max_htlc_msat - 50),
6282 let mut route_hint_2 = route_hint_1.clone();
6283 route_hint_2.0[0].short_channel_id = 46;
6284 route_hint_2.0[1].short_channel_id = 47;
6285 let dest_node_id = ln_test_utils::pubkey(44);
6286 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6287 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6288 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6290 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6291 Some(&first_hop.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6292 &random_seed_bytes).unwrap();
6293 assert_eq!(route.paths.len(), 2);
6294 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6295 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6296 assert_eq!(route.get_total_amount(), amt_msat);
6298 // Re-run but with two first hop channels connected to the same route hint peers that must be
6300 let first_hops = vec![
6301 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6302 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6304 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6305 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6306 &random_seed_bytes).unwrap();
6307 assert_eq!(route.paths.len(), 2);
6308 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6309 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6310 assert_eq!(route.get_total_amount(), amt_msat);
6312 // Make sure this works for blinded route hints.
6313 let blinded_path = BlindedPath {
6314 introduction_node_id: intermed_node_id,
6315 blinding_point: ln_test_utils::pubkey(42),
6317 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6318 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6321 let blinded_payinfo = BlindedPayInfo {
6323 fee_proportional_millionths: 0,
6324 htlc_minimum_msat: 1,
6325 htlc_maximum_msat: max_htlc_msat,
6326 cltv_expiry_delta: 10,
6327 features: BlindedHopFeatures::empty(),
6329 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6330 let payment_params = PaymentParameters::blinded(vec![
6331 (blinded_payinfo.clone(), blinded_path.clone()),
6332 (blinded_payinfo.clone(), blinded_path.clone())])
6333 .with_bolt12_features(bolt12_features).unwrap();
6334 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6335 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6336 &random_seed_bytes).unwrap();
6337 assert_eq!(route.paths.len(), 2);
6338 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6339 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6340 assert_eq!(route.get_total_amount(), amt_msat);
6344 fn blinded_route_ser() {
6345 let blinded_path_1 = BlindedPath {
6346 introduction_node_id: ln_test_utils::pubkey(42),
6347 blinding_point: ln_test_utils::pubkey(43),
6349 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6350 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6353 let blinded_path_2 = BlindedPath {
6354 introduction_node_id: ln_test_utils::pubkey(46),
6355 blinding_point: ln_test_utils::pubkey(47),
6357 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6358 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6361 // (De)serialize a Route with 1 blinded path out of two total paths.
6362 let mut route = Route { paths: vec![Path {
6363 hops: vec![RouteHop {
6364 pubkey: ln_test_utils::pubkey(50),
6365 node_features: NodeFeatures::empty(),
6366 short_channel_id: 42,
6367 channel_features: ChannelFeatures::empty(),
6369 cltv_expiry_delta: 0,
6371 blinded_tail: Some(BlindedTail {
6372 hops: blinded_path_1.blinded_hops,
6373 blinding_point: blinded_path_1.blinding_point,
6374 excess_final_cltv_expiry_delta: 40,
6375 final_value_msat: 100,
6377 hops: vec![RouteHop {
6378 pubkey: ln_test_utils::pubkey(51),
6379 node_features: NodeFeatures::empty(),
6380 short_channel_id: 43,
6381 channel_features: ChannelFeatures::empty(),
6383 cltv_expiry_delta: 0,
6384 }], blinded_tail: None }],
6385 payment_params: None,
6387 let encoded_route = route.encode();
6388 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6389 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6390 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6392 // (De)serialize a Route with two paths, each containing a blinded tail.
6393 route.paths[1].blinded_tail = Some(BlindedTail {
6394 hops: blinded_path_2.blinded_hops,
6395 blinding_point: blinded_path_2.blinding_point,
6396 excess_final_cltv_expiry_delta: 41,
6397 final_value_msat: 101,
6399 let encoded_route = route.encode();
6400 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6401 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6402 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6406 fn blinded_path_inflight_processing() {
6407 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6408 // account for the blinded tail's final amount_msat.
6409 let mut inflight_htlcs = InFlightHtlcs::new();
6410 let blinded_path = BlindedPath {
6411 introduction_node_id: ln_test_utils::pubkey(43),
6412 blinding_point: ln_test_utils::pubkey(48),
6413 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
6416 hops: vec![RouteHop {
6417 pubkey: ln_test_utils::pubkey(42),
6418 node_features: NodeFeatures::empty(),
6419 short_channel_id: 42,
6420 channel_features: ChannelFeatures::empty(),
6422 cltv_expiry_delta: 0,
6425 pubkey: blinded_path.introduction_node_id,
6426 node_features: NodeFeatures::empty(),
6427 short_channel_id: 43,
6428 channel_features: ChannelFeatures::empty(),
6430 cltv_expiry_delta: 0,
6432 blinded_tail: Some(BlindedTail {
6433 hops: blinded_path.blinded_hops,
6434 blinding_point: blinded_path.blinding_point,
6435 excess_final_cltv_expiry_delta: 0,
6436 final_value_msat: 200,
6439 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
6440 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
6441 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
6445 fn blinded_path_cltv_shadow_offset() {
6446 // Make sure we add a shadow offset when sending to blinded paths.
6447 let blinded_path = BlindedPath {
6448 introduction_node_id: ln_test_utils::pubkey(43),
6449 blinding_point: ln_test_utils::pubkey(44),
6451 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
6452 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
6455 let mut route = Route { paths: vec![Path {
6456 hops: vec![RouteHop {
6457 pubkey: ln_test_utils::pubkey(42),
6458 node_features: NodeFeatures::empty(),
6459 short_channel_id: 42,
6460 channel_features: ChannelFeatures::empty(),
6462 cltv_expiry_delta: 0,
6465 pubkey: blinded_path.introduction_node_id,
6466 node_features: NodeFeatures::empty(),
6467 short_channel_id: 43,
6468 channel_features: ChannelFeatures::empty(),
6470 cltv_expiry_delta: 0,
6473 blinded_tail: Some(BlindedTail {
6474 hops: blinded_path.blinded_hops,
6475 blinding_point: blinded_path.blinding_point,
6476 excess_final_cltv_expiry_delta: 0,
6477 final_value_msat: 200,
6479 }], payment_params: None};
6481 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
6482 let (_, network_graph, _, _, _) = build_line_graph();
6483 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
6484 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
6485 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
6489 fn simple_blinded_route_hints() {
6490 do_simple_blinded_route_hints(1);
6491 do_simple_blinded_route_hints(2);
6492 do_simple_blinded_route_hints(3);
6495 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
6496 // Check that we can generate a route to a blinded path with the expected hops.
6497 let (secp_ctx, network, _, _, logger) = build_graph();
6498 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6499 let network_graph = network.read_only();
6501 let scorer = ln_test_utils::TestScorer::new();
6502 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6503 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6505 let mut blinded_path = BlindedPath {
6506 introduction_node_id: nodes[2],
6507 blinding_point: ln_test_utils::pubkey(42),
6508 blinded_hops: Vec::with_capacity(num_blinded_hops),
6510 for i in 0..num_blinded_hops {
6511 blinded_path.blinded_hops.push(
6512 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
6515 let blinded_payinfo = BlindedPayInfo {
6517 fee_proportional_millionths: 500,
6518 htlc_minimum_msat: 1000,
6519 htlc_maximum_msat: 100_000_000,
6520 cltv_expiry_delta: 15,
6521 features: BlindedHopFeatures::empty(),
6524 let final_amt_msat = 1001;
6525 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
6526 let route = get_route(&our_id, &payment_params, &network_graph, None, final_amt_msat , Arc::clone(&logger),
6527 &scorer, &(), &random_seed_bytes).unwrap();
6528 assert_eq!(route.paths.len(), 1);
6529 assert_eq!(route.paths[0].hops.len(), 2);
6531 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
6532 assert_eq!(tail.hops, blinded_path.blinded_hops);
6533 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
6534 assert_eq!(tail.final_value_msat, 1001);
6536 let final_hop = route.paths[0].hops.last().unwrap();
6537 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
6538 if tail.hops.len() > 1 {
6539 assert_eq!(final_hop.fee_msat,
6540 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
6541 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
6543 assert_eq!(final_hop.fee_msat, 0);
6544 assert_eq!(final_hop.cltv_expiry_delta, 0);
6549 fn blinded_path_routing_errors() {
6550 // Check that we can generate a route to a blinded path with the expected hops.
6551 let (secp_ctx, network, _, _, logger) = build_graph();
6552 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6553 let network_graph = network.read_only();
6555 let scorer = ln_test_utils::TestScorer::new();
6556 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6557 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6559 let mut invalid_blinded_path = BlindedPath {
6560 introduction_node_id: nodes[2],
6561 blinding_point: ln_test_utils::pubkey(42),
6563 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
6566 let blinded_payinfo = BlindedPayInfo {
6568 fee_proportional_millionths: 500,
6569 htlc_minimum_msat: 1000,
6570 htlc_maximum_msat: 100_000_000,
6571 cltv_expiry_delta: 15,
6572 features: BlindedHopFeatures::empty(),
6575 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
6576 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
6577 let payment_params = PaymentParameters::blinded(vec![
6578 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
6579 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
6580 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6581 &scorer, &(), &random_seed_bytes)
6583 Err(LightningError { err, .. }) => {
6584 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
6586 _ => panic!("Expected error")
6589 invalid_blinded_path.introduction_node_id = our_id;
6590 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
6591 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6592 &scorer, &(), &random_seed_bytes)
6594 Err(LightningError { err, .. }) => {
6595 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
6597 _ => panic!("Expected error")
6600 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
6601 invalid_blinded_path.blinded_hops.clear();
6602 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
6603 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6604 &scorer, &(), &random_seed_bytes)
6606 Err(LightningError { err, .. }) => {
6607 assert_eq!(err, "0-hop blinded path provided");
6609 _ => panic!("Expected error")
6614 fn matching_intro_node_paths_provided() {
6615 // Check that if multiple blinded paths with the same intro node are provided in payment
6616 // parameters, we'll return the correct paths in the resulting MPP route.
6617 let (secp_ctx, network, _, _, logger) = build_graph();
6618 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6619 let network_graph = network.read_only();
6621 let scorer = ln_test_utils::TestScorer::new();
6622 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6623 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6624 let config = UserConfig::default();
6626 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6627 let blinded_path_1 = BlindedPath {
6628 introduction_node_id: nodes[2],
6629 blinding_point: ln_test_utils::pubkey(42),
6631 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6632 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6635 let blinded_payinfo_1 = BlindedPayInfo {
6637 fee_proportional_millionths: 0,
6638 htlc_minimum_msat: 0,
6639 htlc_maximum_msat: 30_000,
6640 cltv_expiry_delta: 0,
6641 features: BlindedHopFeatures::empty(),
6644 let mut blinded_path_2 = blinded_path_1.clone();
6645 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
6646 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
6647 blinded_payinfo_2.htlc_maximum_msat = 70_000;
6649 let blinded_hints = vec![
6650 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
6651 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
6653 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
6654 .with_bolt12_features(bolt12_features.clone()).unwrap();
6656 let route = get_route(&our_id, &payment_params, &network_graph, None,
6657 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6658 assert_eq!(route.paths.len(), 2);
6659 let mut total_amount_paid_msat = 0;
6660 for path in route.paths.into_iter() {
6661 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6662 if let Some(bt) = &path.blinded_tail {
6663 assert_eq!(bt.blinding_point,
6664 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
6665 .map(|(_, bp)| bp.blinding_point).unwrap());
6666 } else { panic!(); }
6667 total_amount_paid_msat += path.final_value_msat();
6669 assert_eq!(total_amount_paid_msat, 100_000);
6673 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
6674 pub(crate) mod bench_utils {
6678 use bitcoin::hashes::Hash;
6679 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
6681 use crate::chain::transaction::OutPoint;
6682 use crate::sign::{EntropySource, KeysManager};
6683 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
6684 use crate::ln::features::InvoiceFeatures;
6685 use crate::routing::gossip::NetworkGraph;
6686 use crate::util::config::UserConfig;
6687 use crate::util::ser::ReadableArgs;
6688 use crate::util::test_utils::TestLogger;
6690 /// Tries to open a network graph file, or panics with a URL to fetch it.
6691 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
6692 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
6693 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
6694 .or_else(|_| { // Fall back to guessing based on the binary location
6695 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
6696 let mut path = std::env::current_exe().unwrap();
6697 path.pop(); // lightning-...
6699 path.pop(); // debug
6700 path.pop(); // target
6701 path.push("lightning");
6702 path.push("net_graph-2023-01-18.bin");
6705 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
6706 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
6707 let mut path = std::env::current_exe().unwrap();
6708 path.pop(); // bench...
6710 path.pop(); // debug
6711 path.pop(); // target
6712 path.pop(); // bench
6713 path.push("lightning");
6714 path.push("net_graph-2023-01-18.bin");
6717 .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");
6718 #[cfg(require_route_graph_test)]
6719 return Ok(res.unwrap());
6720 #[cfg(not(require_route_graph_test))]
6724 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
6725 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
6728 pub(crate) fn payer_pubkey() -> PublicKey {
6729 let secp_ctx = Secp256k1::new();
6730 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
6734 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
6736 channel_id: [0; 32],
6737 counterparty: ChannelCounterparty {
6738 features: channelmanager::provided_init_features(&UserConfig::default()),
6740 unspendable_punishment_reserve: 0,
6741 forwarding_info: None,
6742 outbound_htlc_minimum_msat: None,
6743 outbound_htlc_maximum_msat: None,
6745 funding_txo: Some(OutPoint {
6746 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
6749 short_channel_id: Some(1),
6750 inbound_scid_alias: None,
6751 outbound_scid_alias: None,
6752 channel_value_satoshis: 10_000_000_000,
6754 balance_msat: 10_000_000_000,
6755 outbound_capacity_msat: 10_000_000_000,
6756 next_outbound_htlc_minimum_msat: 0,
6757 next_outbound_htlc_limit_msat: 10_000_000_000,
6758 inbound_capacity_msat: 0,
6759 unspendable_punishment_reserve: None,
6760 confirmations_required: None,
6761 confirmations: None,
6762 force_close_spend_delay: None,
6764 is_channel_ready: true,
6767 inbound_htlc_minimum_msat: None,
6768 inbound_htlc_maximum_msat: None,
6770 feerate_sat_per_1000_weight: None,
6771 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
6775 pub(crate) fn generate_test_routes<S: Score>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
6776 score_params: &S::ScoreParams, features: InvoiceFeatures, mut seed: u64,
6777 starting_amount: u64, route_count: usize,
6778 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
6779 let payer = payer_pubkey();
6780 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
6781 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6783 let nodes = graph.read_only().nodes().clone();
6784 let mut route_endpoints = Vec::new();
6785 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
6786 // with some routes we picked being un-routable.
6787 for _ in 0..route_count * 3 / 2 {
6789 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6790 let src = PublicKey::from_slice(nodes.unordered_keys()
6791 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6792 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6793 let dst = PublicKey::from_slice(nodes.unordered_keys()
6794 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6795 let params = PaymentParameters::from_node_id(dst, 42)
6796 .with_bolt11_features(features.clone()).unwrap();
6797 let first_hop = first_hop(src);
6798 let amt = starting_amount + seed % 1_000_000;
6800 get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]),
6801 amt, &TestLogger::new(), &scorer, score_params, &random_seed_bytes).is_ok();
6803 // ...and seed the scorer with success and failure data...
6804 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6805 let mut score_amt = seed % 1_000_000_000;
6807 // Generate fail/success paths for a wider range of potential amounts with
6808 // MPP enabled to give us a chance to apply penalties for more potential
6810 let mpp_features = channelmanager::provided_invoice_features(&UserConfig::default());
6811 let params = PaymentParameters::from_node_id(dst, 42)
6812 .with_bolt11_features(mpp_features).unwrap();
6814 let route_res = get_route(&payer, ¶ms, &graph.read_only(),
6815 Some(&[&first_hop]), score_amt, &TestLogger::new(), &scorer,
6816 score_params, &random_seed_bytes);
6817 if let Ok(route) = route_res {
6818 for path in route.paths {
6819 if seed & 0x80 == 0 {
6820 scorer.payment_path_successful(&path);
6822 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
6823 scorer.payment_path_failed(&path, short_channel_id);
6825 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6829 // If we couldn't find a path with a higer amount, reduce and try again.
6833 route_endpoints.push((first_hop, params, amt));
6839 // Because we've changed channel scores, it's possible we'll take different routes to the
6840 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
6841 // requires a too-high CLTV delta.
6842 route_endpoints.retain(|(first_hop, params, amt)| {
6843 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
6844 &TestLogger::new(), &scorer, score_params, &random_seed_bytes).is_ok()
6846 route_endpoints.truncate(route_count);
6847 assert_eq!(route_endpoints.len(), route_count);
6855 use crate::sign::{EntropySource, KeysManager};
6856 use crate::ln::channelmanager;
6857 use crate::ln::features::InvoiceFeatures;
6858 use crate::routing::gossip::NetworkGraph;
6859 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
6860 use crate::util::config::UserConfig;
6861 use crate::util::logger::{Logger, Record};
6862 use crate::util::test_utils::TestLogger;
6864 use criterion::Criterion;
6866 struct DummyLogger {}
6867 impl Logger for DummyLogger {
6868 fn log(&self, _record: &Record) {}
6871 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
6872 let logger = TestLogger::new();
6873 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6874 let scorer = FixedPenaltyScorer::with_penalty(0);
6875 generate_routes(bench, &network_graph, scorer, &(), InvoiceFeatures::empty(), 0,
6876 "generate_routes_with_zero_penalty_scorer");
6879 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
6880 let logger = TestLogger::new();
6881 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6882 let scorer = FixedPenaltyScorer::with_penalty(0);
6883 generate_routes(bench, &network_graph, scorer, &(),
6884 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
6885 "generate_mpp_routes_with_zero_penalty_scorer");
6888 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6889 let logger = TestLogger::new();
6890 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6891 let params = ProbabilisticScoringFeeParameters::default();
6892 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6893 generate_routes(bench, &network_graph, scorer, ¶ms, InvoiceFeatures::empty(), 0,
6894 "generate_routes_with_probabilistic_scorer");
6897 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6898 let logger = TestLogger::new();
6899 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6900 let params = ProbabilisticScoringFeeParameters::default();
6901 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6902 generate_routes(bench, &network_graph, scorer, ¶ms,
6903 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
6904 "generate_mpp_routes_with_probabilistic_scorer");
6907 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6908 let logger = TestLogger::new();
6909 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6910 let params = ProbabilisticScoringFeeParameters::default();
6911 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6912 generate_routes(bench, &network_graph, scorer, ¶ms,
6913 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
6914 "generate_large_mpp_routes_with_probabilistic_scorer");
6917 fn generate_routes<S: Score>(
6918 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
6919 score_params: &S::ScoreParams, features: InvoiceFeatures, starting_amount: u64,
6920 bench_name: &'static str,
6922 let payer = bench_utils::payer_pubkey();
6923 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
6924 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6926 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
6927 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
6929 // ...then benchmark finding paths between the nodes we learned.
6931 bench.bench_function(bench_name, |b| b.iter(|| {
6932 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
6933 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
6934 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());