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, {
295 (0, hops, required_vec),
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, required_vec),
563 (5, self.max_channel_saturation_power_of_half, required),
564 (6, self.expiry_time, option),
565 (7, self.previously_failed_channels, required_vec),
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, clear_route_hints, required_vec),
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, optional_vec),
584 (8, blinded_route_hints, optional_vec),
585 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
587 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
588 let payee = if blinded_route_hints.len() != 0 {
589 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
591 route_hints: blinded_route_hints,
592 features: features.and_then(|f: Features| f.bolt12()),
596 route_hints: clear_route_hints,
597 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
598 features: features.and_then(|f| f.bolt11()),
599 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
603 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
604 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
606 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
608 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
614 impl PaymentParameters {
615 /// Creates a payee with the node id of the given `pubkey`.
617 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
619 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
621 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
623 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
624 max_path_count: DEFAULT_MAX_PATH_COUNT,
625 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
626 previously_failed_channels: Vec::new(),
630 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
632 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
635 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
636 /// whether your router will be allowed to find a multi-part route for this payment. If you
637 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
638 /// [`RecipientOnionFields::secret_only`].
640 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
641 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
642 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
643 .with_bolt11_features(InvoiceFeatures::for_keysend(allow_mpp))
644 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
647 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
648 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
649 /// [`PaymentParameters::expiry_time`].
650 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
651 Self::blinded(invoice.payment_paths().to_vec())
652 .with_bolt12_features(invoice.features().clone()).unwrap()
653 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
656 fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
658 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
660 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
661 max_path_count: DEFAULT_MAX_PATH_COUNT,
662 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
663 previously_failed_channels: Vec::new(),
667 /// Includes the payee's features. Errors if the parameters were not initialized with
668 /// [`PaymentParameters::from_bolt12_invoice`].
670 /// This is not exported to bindings users since bindings don't support move semantics
671 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
673 Payee::Clear { .. } => Err(()),
674 Payee::Blinded { route_hints, .. } =>
675 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
679 /// Includes the payee's features. Errors if the parameters were initialized with
680 /// [`PaymentParameters::from_bolt12_invoice`].
682 /// This is not exported to bindings users since bindings don't support move semantics
683 pub fn with_bolt11_features(self, features: InvoiceFeatures) -> Result<Self, ()> {
685 Payee::Blinded { .. } => Err(()),
686 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
688 payee: Payee::Clear {
689 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
695 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
696 /// [`PaymentParameters::from_bolt12_invoice`].
698 /// This is not exported to bindings users since bindings don't support move semantics
699 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
701 Payee::Blinded { .. } => Err(()),
702 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
704 payee: Payee::Clear {
705 route_hints, node_id, features, final_cltv_expiry_delta,
711 /// Includes a payment expiration in seconds relative to the UNIX epoch.
713 /// This is not exported to bindings users since bindings don't support move semantics
714 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
715 Self { expiry_time: Some(expiry_time), ..self }
718 /// Includes a limit for the total CLTV expiry delta which is considered during routing
720 /// This is not exported to bindings users since bindings don't support move semantics
721 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
722 Self { max_total_cltv_expiry_delta, ..self }
725 /// Includes a limit for the maximum number of payment paths that may be used.
727 /// This is not exported to bindings users since bindings don't support move semantics
728 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
729 Self { max_path_count, ..self }
732 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
733 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
735 /// This is not exported to bindings users since bindings don't support move semantics
736 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
737 Self { max_channel_saturation_power_of_half, ..self }
741 /// The recipient of a payment, differing based on whether they've hidden their identity with route
743 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
745 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
746 /// will be included in the final [`Route`].
748 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
750 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
751 /// Features supported by the payee.
753 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
755 features: Option<Bolt12InvoiceFeatures>,
757 /// The recipient included these route hints in their BOLT11 invoice.
759 /// The node id of the payee.
761 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
762 route_hints: Vec<RouteHint>,
763 /// Features supported by the payee.
765 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
766 /// does not contain any features.
768 /// [`for_keysend`]: PaymentParameters::for_keysend
769 features: Option<InvoiceFeatures>,
770 /// The minimum CLTV delta at the end of the route. This value must not be zero.
771 final_cltv_expiry_delta: u32,
776 fn node_id(&self) -> Option<PublicKey> {
778 Self::Clear { node_id, .. } => Some(*node_id),
782 fn node_features(&self) -> Option<NodeFeatures> {
784 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
785 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
788 fn supports_basic_mpp(&self) -> bool {
790 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
791 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
794 fn features(&self) -> Option<FeaturesRef> {
796 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
797 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
800 fn final_cltv_expiry_delta(&self) -> Option<u32> {
802 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
806 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
808 Self::Blinded { route_hints, .. } => &route_hints[..],
809 Self::Clear { .. } => &[]
813 fn unblinded_route_hints(&self) -> &[RouteHint] {
815 Self::Blinded { .. } => &[],
816 Self::Clear { route_hints, .. } => &route_hints[..]
821 enum FeaturesRef<'a> {
822 Bolt11(&'a InvoiceFeatures),
823 Bolt12(&'a Bolt12InvoiceFeatures),
826 Bolt11(InvoiceFeatures),
827 Bolt12(Bolt12InvoiceFeatures),
831 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
833 Self::Bolt12(f) => Some(f),
837 fn bolt11(self) -> Option<InvoiceFeatures> {
839 Self::Bolt11(f) => Some(f),
845 impl<'a> Writeable for FeaturesRef<'a> {
846 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
848 Self::Bolt11(f) => Ok(f.write(w)?),
849 Self::Bolt12(f) => Ok(f.write(w)?),
854 impl ReadableArgs<bool> for Features {
855 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
856 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
857 Ok(Self::Bolt12(Readable::read(reader)?))
861 /// A list of hops along a payment path terminating with a channel to the recipient.
862 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
863 pub struct RouteHint(pub Vec<RouteHintHop>);
865 impl Writeable for RouteHint {
866 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
867 (self.0.len() as u64).write(writer)?;
868 for hop in self.0.iter() {
875 impl Readable for RouteHint {
876 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
877 let hop_count: u64 = Readable::read(reader)?;
878 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
879 for _ in 0..hop_count {
880 hops.push(Readable::read(reader)?);
886 /// A channel descriptor for a hop along a payment path.
887 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
888 pub struct RouteHintHop {
889 /// The node_id of the non-target end of the route
890 pub src_node_id: PublicKey,
891 /// The short_channel_id of this channel
892 pub short_channel_id: u64,
893 /// The fees which must be paid to use this channel
894 pub fees: RoutingFees,
895 /// The difference in CLTV values between this node and the next node.
896 pub cltv_expiry_delta: u16,
897 /// The minimum value, in msat, which must be relayed to the next hop.
898 pub htlc_minimum_msat: Option<u64>,
899 /// The maximum value in msat available for routing with a single HTLC.
900 pub htlc_maximum_msat: Option<u64>,
903 impl_writeable_tlv_based!(RouteHintHop, {
904 (0, src_node_id, required),
905 (1, htlc_minimum_msat, option),
906 (2, short_channel_id, required),
907 (3, htlc_maximum_msat, option),
909 (6, cltv_expiry_delta, required),
912 #[derive(Eq, PartialEq)]
913 struct RouteGraphNode {
915 lowest_fee_to_node: u64,
916 total_cltv_delta: u32,
917 // The maximum value a yet-to-be-constructed payment path might flow through this node.
918 // This value is upper-bounded by us by:
919 // - how much is needed for a path being constructed
920 // - how much value can channels following this node (up to the destination) can contribute,
921 // considering their capacity and fees
922 value_contribution_msat: u64,
923 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
924 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
925 path_htlc_minimum_msat: u64,
926 /// All penalties incurred from this hop on the way to the destination, as calculated using
928 path_penalty_msat: u64,
929 /// The number of hops walked up to this node.
930 path_length_to_node: u8,
933 impl cmp::Ord for RouteGraphNode {
934 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
935 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
936 .saturating_add(other.path_penalty_msat);
937 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
938 .saturating_add(self.path_penalty_msat);
939 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
943 impl cmp::PartialOrd for RouteGraphNode {
944 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
945 Some(self.cmp(other))
949 /// A wrapper around the various hop representations.
951 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
952 #[derive(Clone, Debug)]
953 enum CandidateRouteHop<'a> {
954 /// A hop from the payer, where the outbound liquidity is known.
956 details: &'a ChannelDetails,
958 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
960 info: DirectedChannelInfo<'a>,
961 short_channel_id: u64,
963 /// A hop to the payee found in the BOLT 11 payment invoice, though not necessarily a direct
966 hint: &'a RouteHintHop,
968 /// The payee's identity is concealed behind blinded paths provided in a BOLT 12 invoice.
970 hint: &'a (BlindedPayInfo, BlindedPath),
973 /// Similar to [`Self::Blinded`], but the path here has 1 blinded hop. `BlindedPayInfo` provided
974 /// for 1-hop blinded paths is ignored because it is meant to apply to the hops *between* the
975 /// introduction node and the destination. Useful for tracking that we need to include a blinded
976 /// path at the end of our [`Route`].
978 hint: &'a (BlindedPayInfo, BlindedPath),
983 impl<'a> CandidateRouteHop<'a> {
984 fn short_channel_id(&self) -> Option<u64> {
986 CandidateRouteHop::FirstHop { details } => Some(details.get_outbound_payment_scid().unwrap()),
987 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
988 CandidateRouteHop::PrivateHop { hint } => Some(hint.short_channel_id),
989 CandidateRouteHop::Blinded { .. } => None,
990 CandidateRouteHop::OneHopBlinded { .. } => None,
994 // NOTE: This may alloc memory so avoid calling it in a hot code path.
995 fn features(&self) -> ChannelFeatures {
997 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
998 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
999 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
1000 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
1001 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
1005 fn cltv_expiry_delta(&self) -> u32 {
1007 CandidateRouteHop::FirstHop { .. } => 0,
1008 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1009 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
1010 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1011 CandidateRouteHop::OneHopBlinded { .. } => 0,
1015 fn htlc_minimum_msat(&self) -> u64 {
1017 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_minimum_msat,
1018 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1019 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
1020 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1021 CandidateRouteHop::OneHopBlinded { .. } => 0,
1025 fn fees(&self) -> RoutingFees {
1027 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1028 base_msat: 0, proportional_millionths: 0,
1030 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1031 CandidateRouteHop::PrivateHop { hint } => hint.fees,
1032 CandidateRouteHop::Blinded { hint, .. } => {
1034 base_msat: hint.0.fee_base_msat,
1035 proportional_millionths: hint.0.fee_proportional_millionths
1038 CandidateRouteHop::OneHopBlinded { .. } =>
1039 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1043 fn effective_capacity(&self) -> EffectiveCapacity {
1045 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
1046 liquidity_msat: details.next_outbound_htlc_limit_msat,
1048 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1049 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }} =>
1050 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1051 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }} =>
1052 EffectiveCapacity::Infinite,
1053 CandidateRouteHop::Blinded { hint, .. } =>
1054 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1055 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1059 fn id(&self, channel_direction: bool /* src_node_id < target_node_id */) -> CandidateHopId {
1061 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1062 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1063 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), channel_direction)),
1066 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1068 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1076 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1077 enum CandidateHopId {
1078 /// Contains (scid, src_node_id < target_node_id)
1080 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1085 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1086 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1088 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1089 EffectiveCapacity::Infinite => u64::max_value(),
1090 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1091 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1092 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1093 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1094 // expected to have been generated from up-to-date capacity information.
1095 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1096 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1097 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1101 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1102 -> bool where I1::Item: PartialEq<I2::Item> {
1104 let a = iter_a.next();
1105 let b = iter_b.next();
1106 if a.is_none() && b.is_none() { return true; }
1107 if a.is_none() || b.is_none() { return false; }
1108 if a.unwrap().ne(&b.unwrap()) { return false; }
1112 /// It's useful to keep track of the hops associated with the fees required to use them,
1113 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1114 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1115 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1117 struct PathBuildingHop<'a> {
1118 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
1119 // is a larger refactor and will require careful performance analysis.
1121 candidate: CandidateRouteHop<'a>,
1124 /// All the fees paid *after* this channel on the way to the destination
1125 next_hops_fee_msat: u64,
1126 /// Fee paid for the use of the current channel (see candidate.fees()).
1127 /// The value will be actually deducted from the counterparty balance on the previous link.
1128 hop_use_fee_msat: u64,
1129 /// Used to compare channels when choosing the for routing.
1130 /// Includes paying for the use of a hop and the following hops, as well as
1131 /// an estimated cost of reaching this hop.
1132 /// Might get stale when fees are recomputed. Primarily for internal use.
1133 total_fee_msat: u64,
1134 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1135 /// walk and may be invalid thereafter.
1136 path_htlc_minimum_msat: u64,
1137 /// All penalties incurred from this channel on the way to the destination, as calculated using
1138 /// channel scoring.
1139 path_penalty_msat: u64,
1140 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1141 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1142 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1143 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1144 /// avoid processing them again.
1145 was_processed: bool,
1146 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1147 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1148 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1149 // value_contribution_msat, which requires tracking it here. See comments below where it is
1150 // used for more info.
1151 value_contribution_msat: u64,
1154 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1155 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1156 let mut debug_struct = f.debug_struct("PathBuildingHop");
1158 .field("node_id", &self.node_id)
1159 .field("short_channel_id", &self.candidate.short_channel_id())
1160 .field("total_fee_msat", &self.total_fee_msat)
1161 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1162 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1163 .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)))
1164 .field("path_penalty_msat", &self.path_penalty_msat)
1165 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1166 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1167 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1168 let debug_struct = debug_struct
1169 .field("value_contribution_msat", &self.value_contribution_msat);
1170 debug_struct.finish()
1174 // Instantiated with a list of hops with correct data in them collected during path finding,
1175 // an instance of this struct should be further modified only via given methods.
1177 struct PaymentPath<'a> {
1178 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1181 impl<'a> PaymentPath<'a> {
1182 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1183 fn get_value_msat(&self) -> u64 {
1184 self.hops.last().unwrap().0.fee_msat
1187 fn get_path_penalty_msat(&self) -> u64 {
1188 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1191 fn get_total_fee_paid_msat(&self) -> u64 {
1192 if self.hops.len() < 1 {
1196 // Can't use next_hops_fee_msat because it gets outdated.
1197 for (i, (hop, _)) in self.hops.iter().enumerate() {
1198 if i != self.hops.len() - 1 {
1199 result += hop.fee_msat;
1205 fn get_cost_msat(&self) -> u64 {
1206 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1209 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1210 // to change fees may result in an inconsistency.
1212 // Sometimes we call this function right after constructing a path which is inconsistent in
1213 // that it the value being transferred has decreased while we were doing path finding, leading
1214 // to the fees being paid not lining up with the actual limits.
1216 // Note that this function is not aware of the available_liquidity limit, and thus does not
1217 // support increasing the value being transferred beyond what was selected during the initial
1219 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
1220 let mut total_fee_paid_msat = 0 as u64;
1221 for i in (0..self.hops.len()).rev() {
1222 let last_hop = i == self.hops.len() - 1;
1224 // For non-last-hop, this value will represent the fees paid on the current hop. It
1225 // will consist of the fees for the use of the next hop, and extra fees to match
1226 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1227 let mut cur_hop_fees_msat = 0;
1229 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1232 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1233 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1234 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1235 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1236 // set it too high just to maliciously take more fees by exploiting this
1237 // match htlc_minimum_msat logic.
1238 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1239 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1240 // Note that there is a risk that *previous hops* (those closer to us, as we go
1241 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1243 // This might make us end up with a broken route, although this should be super-rare
1244 // in practice, both because of how healthy channels look like, and how we pick
1245 // channels in add_entry.
1246 // Also, this can't be exploited more heavily than *announce a free path and fail
1248 cur_hop_transferred_amount_msat += extra_fees_msat;
1249 total_fee_paid_msat += extra_fees_msat;
1250 cur_hop_fees_msat += extra_fees_msat;
1254 // Final hop is a special case: it usually has just value_msat (by design), but also
1255 // it still could overpay for the htlc_minimum_msat.
1256 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1258 // Propagate updated fees for the use of the channels to one hop back, where they
1259 // will be actually paid (fee_msat). The last hop is handled above separately.
1260 cur_hop.fee_msat = cur_hop_fees_msat;
1263 // Fee for the use of the current hop which will be deducted on the previous hop.
1264 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1265 // this channel is free for us.
1267 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1268 cur_hop.hop_use_fee_msat = new_fee;
1269 total_fee_paid_msat += new_fee;
1271 // It should not be possible because this function is called only to reduce the
1272 // value. In that case, compute_fee was already called with the same fees for
1273 // larger amount and there was no overflow.
1282 /// Calculate the fees required to route the given amount over a channel with the given fees.
1283 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1284 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1285 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1289 /// Calculate the fees required to route the given amount over a channel with the given fees,
1290 /// saturating to [`u64::max_value`].
1291 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1292 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1293 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1294 .saturating_add(channel_fees.base_msat as u64)
1297 /// The default `features` we assume for a node in a route, when no `features` are known about that
1300 /// Default features are:
1301 /// * variable_length_onion_optional
1302 fn default_node_features() -> NodeFeatures {
1303 let mut features = NodeFeatures::empty();
1304 features.set_variable_length_onion_optional();
1308 struct LoggedPayeePubkey(Option<PublicKey>);
1309 impl fmt::Display for LoggedPayeePubkey {
1310 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1313 "payee node id ".fmt(f)?;
1317 "blinded payee".fmt(f)
1323 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1324 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1325 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1327 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1328 "blinded route hint with introduction node id ".fmt(f)?;
1329 hint.1.introduction_node_id.fmt(f)?;
1330 " and blinding point ".fmt(f)?;
1331 hint.1.blinding_point.fmt(f)
1335 self.0.short_channel_id().unwrap().fmt(f)
1342 fn sort_first_hop_channels(
1343 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1344 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1346 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1347 // most like to use.
1349 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1350 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1353 // Second, because simply always sorting in descending order would always use our largest
1354 // available outbound capacity, needlessly fragmenting our available channel capacities,
1355 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1356 // which have enough, but not too much, capacity for the payment.
1358 // Available outbound balances factor in liquidity already reserved for previously found paths.
1359 channels.sort_unstable_by(|chan_a, chan_b| {
1360 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1361 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1362 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1363 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1364 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1365 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1366 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1367 // Sort in descending order
1368 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1370 // Sort in ascending order
1371 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1376 /// Finds a route from us (payer) to the given target node (payee).
1378 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
1379 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1381 /// Private routing paths between a public node and the target may be included in `params.payee`.
1383 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1384 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1385 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1387 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1388 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1389 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1393 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
1394 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
1399 /// Panics if first_hops contains channels without short_channel_ids;
1400 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1402 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1403 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1404 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1405 pub fn find_route<L: Deref, GL: Deref, S: Score>(
1406 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1407 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1408 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1409 ) -> Result<Route, LightningError>
1410 where L::Target: Logger, GL::Target: Logger {
1411 let graph_lock = network_graph.read_only();
1412 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
1413 route_params.final_value_msat, logger, scorer, score_params,
1414 random_seed_bytes)?;
1415 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1419 pub(crate) fn get_route<L: Deref, S: Score>(
1420 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
1421 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, logger: L, scorer: &S, score_params: &S::ScoreParams,
1422 _random_seed_bytes: &[u8; 32]
1423 ) -> Result<Route, LightningError>
1424 where L::Target: Logger {
1425 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1426 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1427 // so use a dummy id for this in the blinded case.
1428 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1429 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1430 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1431 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1432 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1434 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1435 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1438 if final_value_msat > MAX_VALUE_MSAT {
1439 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1442 if final_value_msat == 0 {
1443 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1446 match &payment_params.payee {
1447 Payee::Clear { route_hints, node_id, .. } => {
1448 for route in route_hints.iter() {
1449 for hop in &route.0 {
1450 if hop.src_node_id == *node_id {
1451 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1456 Payee::Blinded { route_hints, .. } => {
1457 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1458 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});
1460 for (_, blinded_path) in route_hints.iter() {
1461 if blinded_path.blinded_hops.len() == 0 {
1462 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1463 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1464 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1465 } else if blinded_path.blinded_hops.len() == 1 &&
1466 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1467 && p.introduction_node_id != blinded_path.introduction_node_id)
1469 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1474 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1475 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1476 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});
1479 // The general routing idea is the following:
1480 // 1. Fill first/last hops communicated by the caller.
1481 // 2. Attempt to construct a path from payer to payee for transferring
1482 // any ~sufficient (described later) value.
1483 // If succeed, remember which channels were used and how much liquidity they have available,
1484 // so that future paths don't rely on the same liquidity.
1485 // 3. Proceed to the next step if:
1486 // - we hit the recommended target value;
1487 // - OR if we could not construct a new path. Any next attempt will fail too.
1488 // Otherwise, repeat step 2.
1489 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1490 // (not recommended value).
1491 // 5. If yes, proceed. If not, fail routing.
1492 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1493 // transferred up to the transfer target value.
1494 // 7. Reduce the value of the last path until we are sending only the target value.
1495 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1496 // them so that we're not sending two HTLCs along the same path.
1498 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1499 // distance from the payee
1501 // We are not a faithful Dijkstra's implementation because we can change values which impact
1502 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1503 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1504 // the value we are currently attempting to send over a path, we simply reduce the value being
1505 // sent along the path for any hops after that channel. This may imply that later fees (which
1506 // we've already tabulated) are lower because a smaller value is passing through the channels
1507 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1508 // channels which were selected earlier (and which may still be used for other paths without a
1509 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1512 // One potentially problematic case for this algorithm would be if there are many
1513 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1514 // graph walking), we may never find a path which is not liquidity-limited and has lower
1515 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1516 // Because we only consider paths with at least 5% of the total value being sent, the damage
1517 // from such a case should be limited, however this could be further reduced in the future by
1518 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1519 // limits for the purposes of fee calculation.
1521 // Alternatively, we could store more detailed path information in the heap (targets, below)
1522 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1523 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1524 // and practically (as we would need to store dynamically-allocated path information in heap
1525 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1526 // results of such an algorithm would likely be biased towards lower-value paths.
1528 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1529 // outside of our current search value, running a path search more times to gather candidate
1530 // paths at different values. While this may be acceptable, further path searches may increase
1531 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1532 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1533 // the same time, remaining generic across different payment values.
1535 let network_channels = network_graph.channels();
1536 let network_nodes = network_graph.nodes();
1538 if payment_params.max_path_count == 0 {
1539 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1542 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1543 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1545 let allow_mpp = if payment_params.max_path_count == 1 {
1547 } else if payment_params.payee.supports_basic_mpp() {
1549 } else if let Some(payee) = payee_node_id_opt {
1550 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1551 |info| info.features.supports_basic_mpp()))
1554 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1555 LoggedPayeePubkey(payment_params.payee.node_id()), if allow_mpp { "with" } else { "without" },
1556 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1559 // Prepare the data we'll use for payee-to-payer search by
1560 // inserting first hops suggested by the caller as targets.
1561 // Our search will then attempt to reach them while traversing from the payee node.
1562 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1563 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1564 if let Some(hops) = first_hops {
1566 if chan.get_outbound_payment_scid().is_none() {
1567 panic!("first_hops should be filled in with usable channels, not pending ones");
1569 if chan.counterparty.node_id == *our_node_pubkey {
1570 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1573 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1574 .or_insert(Vec::new())
1577 if first_hop_targets.is_empty() {
1578 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1582 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1583 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1584 // adding duplicate entries when we find a better path to a given node.
1585 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1587 // Map from node_id to information about the best current path to that node, including feerate
1589 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1591 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1592 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1593 // htlc_minimum with extra fees while still finding a cheaper path.
1594 let mut hit_minimum_limit;
1596 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1597 // We start with a path_value of the exact amount we want, and if that generates a route we may
1598 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1599 // amount we want in total across paths, selecting the best subset at the end.
1600 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1601 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1602 let mut path_value_msat = final_value_msat;
1604 // Routing Fragmentation Mitigation heuristic:
1606 // Routing fragmentation across many payment paths increases the overall routing
1607 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1608 // Taking too many smaller paths also increases the chance of payment failure.
1609 // Thus to avoid this effect, we require from our collected links to provide
1610 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1611 // This requirement is currently set to be 1/max_path_count of the payment
1612 // value to ensure we only ever return routes that do not violate this limit.
1613 let minimal_value_contribution_msat: u64 = if allow_mpp {
1614 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1619 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1620 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1621 // drop the requirement by setting this to 0.
1622 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1624 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1625 // determine if the channel can be used by additional MPP paths or to inform path finding
1626 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1627 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1629 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1630 HashMap::with_capacity(network_nodes.len());
1632 // Keeping track of how much value we already collected across other paths. Helps to decide
1633 // when we want to stop looking for new paths.
1634 let mut already_collected_value_msat = 0;
1636 for (_, channels) in first_hop_targets.iter_mut() {
1637 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1641 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1642 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1644 macro_rules! add_entry {
1645 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1646 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1647 // since that value has to be transferred over this channel.
1648 // Returns whether this channel caused an update to `targets`.
1649 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1650 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1651 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1652 // We "return" whether we updated the path at the end, and how much we can route via
1653 // this channel, via this:
1654 let mut did_add_update_path_to_src_node = None;
1655 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1656 // practice these cases should be caught earlier:
1657 // - for regular channels at channel announcement (TODO)
1658 // - for first and last hops early in get_route
1659 if $src_node_id != $dest_node_id {
1660 let scid_opt = $candidate.short_channel_id();
1661 let effective_capacity = $candidate.effective_capacity();
1662 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1664 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1665 // It may be misleading because we might later choose to reduce the value transferred
1666 // over these channels, and the channel which was insufficient might become sufficient.
1667 // Worst case: we drop a good channel here because it can't cover the high following
1668 // fees caused by one expensive channel, but then this channel could have been used
1669 // if the amount being transferred over this path is lower.
1670 // We do this for now, but this is a subject for removal.
1671 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1672 let used_liquidity_msat = used_liquidities
1673 .get(&$candidate.id($src_node_id < $dest_node_id))
1674 .map_or(0, |used_liquidity_msat| {
1675 available_value_contribution_msat = available_value_contribution_msat
1676 .saturating_sub(*used_liquidity_msat);
1677 *used_liquidity_msat
1680 // Verify the liquidity offered by this channel complies to the minimal contribution.
1681 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1682 // Do not consider candidate hops that would exceed the maximum path length.
1683 let path_length_to_node = $next_hops_path_length + 1;
1684 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1686 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1687 // In order to already account for some of the privacy enhancing random CLTV
1688 // expiry delta offset we add on top later, we subtract a rough estimate
1689 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1690 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1691 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1692 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1693 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1694 .saturating_add($candidate.cltv_expiry_delta());
1695 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1697 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1698 // Includes paying fees for the use of the following channels.
1699 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1700 Some(result) => result,
1701 // Can't overflow due to how the values were computed right above.
1702 None => unreachable!(),
1704 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1705 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1706 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1708 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1709 let may_overpay_to_meet_path_minimum_msat =
1710 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1711 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1712 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1713 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1715 let payment_failed_on_this_channel = scid_opt.map_or(false,
1716 |scid| payment_params.previously_failed_channels.contains(&scid));
1718 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1719 // bother considering this channel. If retrying with recommended_value_msat may
1720 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1721 // around again with a higher amount.
1722 if !contributes_sufficient_value || exceeds_max_path_length ||
1723 exceeds_cltv_delta_limit || payment_failed_on_this_channel {
1724 // Path isn't useful, ignore it and move on.
1725 } else if may_overpay_to_meet_path_minimum_msat {
1726 hit_minimum_limit = true;
1727 } else if over_path_minimum_msat {
1728 // Note that low contribution here (limited by available_liquidity_msat)
1729 // might violate htlc_minimum_msat on the hops which are next along the
1730 // payment path (upstream to the payee). To avoid that, we recompute
1731 // path fees knowing the final path contribution after constructing it.
1732 let path_htlc_minimum_msat = cmp::max(
1733 compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1734 .saturating_add($next_hops_path_htlc_minimum_msat),
1735 $candidate.htlc_minimum_msat());
1736 let hm_entry = dist.entry($src_node_id);
1737 let old_entry = hm_entry.or_insert_with(|| {
1738 // If there was previously no known way to access the source node
1739 // (recall it goes payee-to-payer) of short_channel_id, first add a
1740 // semi-dummy record just to compute the fees to reach the source node.
1741 // This will affect our decision on selecting short_channel_id
1742 // as a way to reach the $dest_node_id.
1744 node_id: $dest_node_id.clone(),
1745 candidate: $candidate.clone(),
1747 next_hops_fee_msat: u64::max_value(),
1748 hop_use_fee_msat: u64::max_value(),
1749 total_fee_msat: u64::max_value(),
1750 path_htlc_minimum_msat,
1751 path_penalty_msat: u64::max_value(),
1752 was_processed: false,
1753 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1754 value_contribution_msat,
1758 #[allow(unused_mut)] // We only use the mut in cfg(test)
1759 let mut should_process = !old_entry.was_processed;
1760 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1762 // In test/fuzzing builds, we do extra checks to make sure the skipping
1763 // of already-seen nodes only happens in cases we expect (see below).
1764 if !should_process { should_process = true; }
1768 let mut hop_use_fee_msat = 0;
1769 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1771 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1772 // will have the same effective-fee
1773 if $src_node_id != our_node_id {
1774 // Note that `u64::max_value` means we'll always fail the
1775 // `old_entry.total_fee_msat > total_fee_msat` check below
1776 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1777 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1780 let channel_usage = ChannelUsage {
1781 amount_msat: amount_to_transfer_over_msat,
1782 inflight_htlc_msat: used_liquidity_msat,
1785 let channel_penalty_msat = scid_opt.map_or(0,
1786 |scid| scorer.channel_penalty_msat(scid, &$src_node_id, &$dest_node_id,
1787 channel_usage, score_params));
1788 let path_penalty_msat = $next_hops_path_penalty_msat
1789 .saturating_add(channel_penalty_msat);
1790 let new_graph_node = RouteGraphNode {
1791 node_id: $src_node_id,
1792 lowest_fee_to_node: total_fee_msat,
1793 total_cltv_delta: hop_total_cltv_delta,
1794 value_contribution_msat,
1795 path_htlc_minimum_msat,
1797 path_length_to_node,
1800 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1801 // if this way is cheaper than the already known
1802 // (considering the cost to "reach" this channel from the route destination,
1803 // the cost of using this channel,
1804 // and the cost of routing to the source node of this channel).
1805 // Also, consider that htlc_minimum_msat_difference, because we might end up
1806 // paying it. Consider the following exploit:
1807 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1808 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1809 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1810 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1812 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1813 // but it may require additional tracking - we don't want to double-count
1814 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1815 // can't use something that may decrease on future hops.
1816 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1817 .saturating_add(old_entry.path_penalty_msat);
1818 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1819 .saturating_add(path_penalty_msat);
1821 if !old_entry.was_processed && new_cost < old_cost {
1822 targets.push(new_graph_node);
1823 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1824 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1825 old_entry.total_fee_msat = total_fee_msat;
1826 old_entry.node_id = $dest_node_id.clone();
1827 old_entry.candidate = $candidate.clone();
1828 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1829 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1830 old_entry.path_penalty_msat = path_penalty_msat;
1831 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1833 old_entry.value_contribution_msat = value_contribution_msat;
1835 did_add_update_path_to_src_node = Some(value_contribution_msat);
1836 } else if old_entry.was_processed && new_cost < old_cost {
1837 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1839 // If we're skipping processing a node which was previously
1840 // processed even though we found another path to it with a
1841 // cheaper fee, check that it was because the second path we
1842 // found (which we are processing now) has a lower value
1843 // contribution due to an HTLC minimum limit.
1845 // e.g. take a graph with two paths from node 1 to node 2, one
1846 // through channel A, and one through channel B. Channel A and
1847 // B are both in the to-process heap, with their scores set by
1848 // a higher htlc_minimum than fee.
1849 // Channel A is processed first, and the channels onwards from
1850 // node 1 are added to the to-process heap. Thereafter, we pop
1851 // Channel B off of the heap, note that it has a much more
1852 // restrictive htlc_maximum_msat, and recalculate the fees for
1853 // all of node 1's channels using the new, reduced, amount.
1855 // This would be bogus - we'd be selecting a higher-fee path
1856 // with a lower htlc_maximum_msat instead of the one we'd
1857 // already decided to use.
1858 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1860 value_contribution_msat + path_penalty_msat <
1861 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1869 did_add_update_path_to_src_node
1873 let default_node_features = default_node_features();
1875 // Find ways (channels with destination) to reach a given node and store them
1876 // in the corresponding data structures (routing graph etc).
1877 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1878 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1879 // This data can later be helpful to optimize routing (pay lower fees).
1880 macro_rules! add_entries_to_cheapest_to_target_node {
1881 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1882 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1883 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1884 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1885 let was_processed = elem.was_processed;
1886 elem.was_processed = true;
1889 // Entries are added to dist in add_entry!() when there is a channel from a node.
1890 // Because there are no channels from payee, it will not have a dist entry at this point.
1891 // If we're processing any other node, it is always be the result of a channel from it.
1892 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
1897 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1898 for details in first_channels {
1899 let candidate = CandidateRouteHop::FirstHop { details };
1900 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1901 $next_hops_value_contribution,
1902 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1903 $next_hops_cltv_delta, $next_hops_path_length);
1907 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1910 &default_node_features
1913 if !features.requires_unknown_bits() {
1914 for chan_id in $node.channels.iter() {
1915 let chan = network_channels.get(chan_id).unwrap();
1916 if !chan.features.requires_unknown_bits() {
1917 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1918 if first_hops.is_none() || *source != our_node_id {
1919 if directed_channel.direction().enabled {
1920 let candidate = CandidateRouteHop::PublicHop {
1921 info: directed_channel,
1922 short_channel_id: *chan_id,
1924 add_entry!(candidate, *source, $node_id,
1925 $fee_to_target_msat,
1926 $next_hops_value_contribution,
1927 $next_hops_path_htlc_minimum_msat,
1928 $next_hops_path_penalty_msat,
1929 $next_hops_cltv_delta, $next_hops_path_length);
1940 let mut payment_paths = Vec::<PaymentPath>::new();
1942 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1943 'paths_collection: loop {
1944 // For every new path, start from scratch, except for used_liquidities, which
1945 // helps to avoid reusing previously selected paths in future iterations.
1948 hit_minimum_limit = false;
1950 // If first hop is a private channel and the only way to reach the payee, this is the only
1951 // place where it could be added.
1952 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
1953 for details in first_channels {
1954 let candidate = CandidateRouteHop::FirstHop { details };
1955 let added = add_entry!(candidate, our_node_id, payee, 0, path_value_msat,
1956 0, 0u64, 0, 0).is_some();
1957 log_trace!(logger, "{} direct route to payee via {}",
1958 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
1962 // Add the payee as a target, so that the payee-to-payer
1963 // search algorithm knows what to start with.
1964 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
1965 // The payee is not in our network graph, so nothing to add here.
1966 // There is still a chance of reaching them via last_hops though,
1967 // so don't yet fail the payment here.
1968 // If not, targets.pop() will not even let us enter the loop in step 2.
1971 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
1976 // If a caller provided us with last hops, add them to routing targets. Since this happens
1977 // earlier than general path finding, they will be somewhat prioritized, although currently
1978 // it matters only if the fees are exactly the same.
1979 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
1980 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
1981 let have_intro_node_in_graph =
1982 // Only add the hops in this route to our candidate set if either
1983 // we have a direct channel to the first hop or the first hop is
1984 // in the regular network graph.
1985 first_hop_targets.get(&intro_node_id).is_some() ||
1986 network_nodes.get(&intro_node_id).is_some();
1987 if !have_intro_node_in_graph { continue }
1988 let candidate = if hint.1.blinded_hops.len() == 1 {
1989 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
1990 } else { CandidateRouteHop::Blinded { hint, hint_idx } };
1991 let mut path_contribution_msat = path_value_msat;
1992 if let Some(hop_used_msat) = add_entry!(candidate, intro_node_id, maybe_dummy_payee_node_id,
1993 0, path_contribution_msat, 0, 0_u64, 0, 0)
1995 path_contribution_msat = hop_used_msat;
1997 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
1998 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2000 for details in first_channels {
2001 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2002 add_entry!(first_hop_candidate, our_node_id, intro_node_id, 0, path_contribution_msat, 0,
2007 for route in payment_params.payee.unblinded_route_hints().iter()
2008 .filter(|route| !route.0.is_empty())
2010 let first_hop_in_route = &(route.0)[0];
2011 let have_hop_src_in_graph =
2012 // Only add the hops in this route to our candidate set if either
2013 // we have a direct channel to the first hop or the first hop is
2014 // in the regular network graph.
2015 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
2016 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
2017 if have_hop_src_in_graph {
2018 // We start building the path from reverse, i.e., from payee
2019 // to the first RouteHintHop in the path.
2020 let hop_iter = route.0.iter().rev();
2021 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2022 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2023 let mut hop_used = true;
2024 let mut aggregate_next_hops_fee_msat: u64 = 0;
2025 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2026 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2027 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2028 let mut aggregate_next_hops_path_length: u8 = 0;
2029 let mut aggregate_path_contribution_msat = path_value_msat;
2031 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2032 let source = NodeId::from_pubkey(&hop.src_node_id);
2033 let target = NodeId::from_pubkey(&prev_hop_id);
2034 let candidate = network_channels
2035 .get(&hop.short_channel_id)
2036 .and_then(|channel| channel.as_directed_to(&target))
2037 .map(|(info, _)| CandidateRouteHop::PublicHop {
2039 short_channel_id: hop.short_channel_id,
2041 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
2043 if let Some(hop_used_msat) = add_entry!(candidate, source, target,
2044 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2045 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2046 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2048 aggregate_path_contribution_msat = hop_used_msat;
2050 // If this hop was not used then there is no use checking the preceding
2051 // hops in the RouteHint. We can break by just searching for a direct
2052 // channel between last checked hop and first_hop_targets.
2056 let used_liquidity_msat = used_liquidities
2057 .get(&candidate.id(source < target)).copied()
2059 let channel_usage = ChannelUsage {
2060 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2061 inflight_htlc_msat: used_liquidity_msat,
2062 effective_capacity: candidate.effective_capacity(),
2064 let channel_penalty_msat = scorer.channel_penalty_msat(
2065 hop.short_channel_id, &source, &target, channel_usage, score_params
2067 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2068 .saturating_add(channel_penalty_msat);
2070 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2071 .saturating_add(hop.cltv_expiry_delta as u32);
2073 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2076 // Searching for a direct channel between last checked hop and first_hop_targets
2077 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&prev_hop_id)) {
2078 sort_first_hop_channels(first_channels, &used_liquidities,
2079 recommended_value_msat, our_node_pubkey);
2080 for details in first_channels {
2081 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2082 add_entry!(first_hop_candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
2083 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2084 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2085 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2093 // In the next values of the iterator, the aggregate fees already reflects
2094 // the sum of value sent from payer (final_value_msat) and routing fees
2095 // for the last node in the RouteHint. We need to just add the fees to
2096 // route through the current node so that the preceding node (next iteration)
2098 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2099 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2100 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2102 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
2103 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
2104 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
2105 .checked_add(hop_htlc_minimum_msat_inc);
2106 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
2108 if idx == route.0.len() - 1 {
2109 // The last hop in this iterator is the first hop in
2110 // overall RouteHint.
2111 // If this hop connects to a node with which we have a direct channel,
2112 // ignore the network graph and, if the last hop was added, add our
2113 // direct channel to the candidate set.
2115 // Note that we *must* check if the last hop was added as `add_entry`
2116 // always assumes that the third argument is a node to which we have a
2118 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2119 sort_first_hop_channels(first_channels, &used_liquidities,
2120 recommended_value_msat, our_node_pubkey);
2121 for details in first_channels {
2122 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2123 add_entry!(first_hop_candidate, our_node_id,
2124 NodeId::from_pubkey(&hop.src_node_id),
2125 aggregate_next_hops_fee_msat,
2126 aggregate_path_contribution_msat,
2127 aggregate_next_hops_path_htlc_minimum_msat,
2128 aggregate_next_hops_path_penalty_msat,
2129 aggregate_next_hops_cltv_delta,
2130 aggregate_next_hops_path_length);
2138 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2140 // At this point, targets are filled with the data from first and
2141 // last hops communicated by the caller, and the payment receiver.
2142 let mut found_new_path = false;
2145 // If this loop terminates due the exhaustion of targets, two situations are possible:
2146 // - not enough outgoing liquidity:
2147 // 0 < already_collected_value_msat < final_value_msat
2148 // - enough outgoing liquidity:
2149 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2150 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2151 // paths_collection will be stopped because found_new_path==false.
2152 // This is not necessarily a routing failure.
2153 '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() {
2155 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2156 // traversing the graph and arrange the path out of what we found.
2157 if node_id == our_node_id {
2158 let mut new_entry = dist.remove(&our_node_id).unwrap();
2159 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2162 let mut features_set = false;
2163 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
2164 for details in first_channels {
2165 if let Some(scid) = ordered_hops.last().unwrap().0.candidate.short_channel_id() {
2166 if details.get_outbound_payment_scid().unwrap() == scid {
2167 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2168 features_set = true;
2175 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
2176 if let Some(node_info) = node.announcement_info.as_ref() {
2177 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2179 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2182 // We can fill in features for everything except hops which were
2183 // provided via the invoice we're paying. We could guess based on the
2184 // recipient's features but for now we simply avoid guessing at all.
2188 // Means we succesfully traversed from the payer to the payee, now
2189 // save this path for the payment route. Also, update the liquidity
2190 // remaining on the used hops, so that we take them into account
2191 // while looking for more paths.
2192 if ordered_hops.last().unwrap().0.node_id == maybe_dummy_payee_node_id {
2196 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
2197 Some(payment_hop) => payment_hop,
2198 // We can't arrive at None because, if we ever add an entry to targets,
2199 // we also fill in the entry in dist (see add_entry!).
2200 None => unreachable!(),
2202 // We "propagate" the fees one hop backward (topologically) here,
2203 // so that fees paid for a HTLC forwarding on the current channel are
2204 // associated with the previous channel (where they will be subtracted).
2205 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2206 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2208 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2209 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2211 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2212 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2214 let mut payment_path = PaymentPath {hops: ordered_hops};
2216 // We could have possibly constructed a slightly inconsistent path: since we reduce
2217 // value being transferred along the way, we could have violated htlc_minimum_msat
2218 // on some channels we already passed (assuming dest->source direction). Here, we
2219 // recompute the fees again, so that if that's the case, we match the currently
2220 // underpaid htlc_minimum_msat with fees.
2221 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2222 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
2223 payment_path.update_value_and_recompute_fees(value_contribution_msat);
2225 // Since a path allows to transfer as much value as
2226 // the smallest channel it has ("bottleneck"), we should recompute
2227 // the fees so sender HTLC don't overpay fees when traversing
2228 // larger channels than the bottleneck. This may happen because
2229 // when we were selecting those channels we were not aware how much value
2230 // this path will transfer, and the relative fee for them
2231 // might have been computed considering a larger value.
2232 // Remember that we used these channels so that we don't rely
2233 // on the same liquidity in future paths.
2234 let mut prevented_redundant_path_selection = false;
2235 let prev_hop_iter = core::iter::once(&our_node_id)
2236 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
2237 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
2238 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2239 let used_liquidity_msat = used_liquidities
2240 .entry(hop.candidate.id(*prev_hop < hop.node_id))
2241 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2242 .or_insert(spent_on_hop_msat);
2243 let hop_capacity = hop.candidate.effective_capacity();
2244 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2245 if *used_liquidity_msat == hop_max_msat {
2246 // If this path used all of this channel's available liquidity, we know
2247 // this path will not be selected again in the next loop iteration.
2248 prevented_redundant_path_selection = true;
2250 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2252 if !prevented_redundant_path_selection {
2253 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2254 // we'll probably end up picking the same path again on the next iteration.
2255 // Decrease the available liquidity of a hop in the middle of the path.
2256 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2257 let exhausted = u64::max_value();
2258 log_trace!(logger, "Disabling route candidate {} for future path building iterations to
2259 avoid duplicates.", LoggedCandidateHop(victim_candidate));
2260 *used_liquidities.entry(victim_candidate.id(false)).or_default() = exhausted;
2261 *used_liquidities.entry(victim_candidate.id(true)).or_default() = exhausted;
2264 // Track the total amount all our collected paths allow to send so that we know
2265 // when to stop looking for more paths
2266 already_collected_value_msat += value_contribution_msat;
2268 payment_paths.push(payment_path);
2269 found_new_path = true;
2270 break 'path_construction;
2273 // If we found a path back to the payee, we shouldn't try to process it again. This is
2274 // the equivalent of the `elem.was_processed` check in
2275 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2276 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2278 // Otherwise, since the current target node is not us,
2279 // keep "unrolling" the payment graph from payee to payer by
2280 // finding a way to reach the current target from the payer side.
2281 match network_nodes.get(&node_id) {
2284 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2285 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2286 total_cltv_delta, path_length_to_node);
2292 if !found_new_path && channel_saturation_pow_half != 0 {
2293 channel_saturation_pow_half = 0;
2294 continue 'paths_collection;
2296 // If we don't support MPP, no use trying to gather more value ever.
2297 break 'paths_collection;
2301 // Stop either when the recommended value is reached or if no new path was found in this
2303 // In the latter case, making another path finding attempt won't help,
2304 // because we deterministically terminated the search due to low liquidity.
2305 if !found_new_path && channel_saturation_pow_half != 0 {
2306 channel_saturation_pow_half = 0;
2307 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2308 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2309 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2310 break 'paths_collection;
2311 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2312 // Further, if this was our first walk of the graph, and we weren't limited by an
2313 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2314 // limited by an htlc_minimum_msat value, find another path with a higher value,
2315 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2316 // still keeping a lower total fee than this path.
2317 if !hit_minimum_limit {
2318 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2319 break 'paths_collection;
2321 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
2322 path_value_msat = recommended_value_msat;
2327 if payment_paths.len() == 0 {
2328 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2331 if already_collected_value_msat < final_value_msat {
2332 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2336 let mut selected_route = payment_paths;
2338 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2339 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2341 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2342 // the value they contribute towards the payment amount.
2343 // We sort in descending order as we will remove from the front in `retain`, next.
2344 selected_route.sort_unstable_by(|a, b|
2345 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2346 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2349 // We should make sure that at least 1 path left.
2350 let mut paths_left = selected_route.len();
2351 selected_route.retain(|path| {
2352 if paths_left == 1 {
2355 let path_value_msat = path.get_value_msat();
2356 if path_value_msat <= overpaid_value_msat {
2357 overpaid_value_msat -= path_value_msat;
2363 debug_assert!(selected_route.len() > 0);
2365 if overpaid_value_msat != 0 {
2367 // Now, subtract the remaining overpaid value from the most-expensive path.
2368 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2369 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2370 selected_route.sort_unstable_by(|a, b| {
2371 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2372 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2373 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2375 let expensive_payment_path = selected_route.first_mut().unwrap();
2377 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2378 // can't go negative.
2379 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2380 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2384 // Sort by the path itself and combine redundant paths.
2385 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2386 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2388 selected_route.sort_unstable_by_key(|path| {
2389 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2390 debug_assert!(path.hops.len() <= key.len());
2391 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id(true)).zip(key.iter_mut()) {
2396 for idx in 0..(selected_route.len() - 1) {
2397 if idx + 1 >= selected_route.len() { break; }
2398 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id)),
2399 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id))) {
2400 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2401 selected_route[idx].update_value_and_recompute_fees(new_value);
2402 selected_route.remove(idx + 1);
2406 let mut paths = Vec::new();
2407 for payment_path in selected_route {
2408 let mut hops = Vec::with_capacity(payment_path.hops.len());
2409 for (hop, node_features) in payment_path.hops.iter()
2410 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2412 hops.push(RouteHop {
2413 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)})?,
2414 node_features: node_features.clone(),
2415 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2416 channel_features: hop.candidate.features(),
2417 fee_msat: hop.fee_msat,
2418 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2421 let mut final_cltv_delta = final_cltv_expiry_delta;
2422 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2423 if let Some(blinded_path) = h.candidate.blinded_path() {
2424 final_cltv_delta = h.candidate.cltv_expiry_delta();
2426 hops: blinded_path.blinded_hops.clone(),
2427 blinding_point: blinded_path.blinding_point,
2428 excess_final_cltv_expiry_delta: 0,
2429 final_value_msat: h.fee_msat,
2433 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2434 // applicable for the previous hop.
2435 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2436 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2439 paths.push(Path { hops, blinded_tail });
2441 // Make sure we would never create a route with more paths than we allow.
2442 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2444 if let Some(node_features) = payment_params.payee.node_features() {
2445 for path in paths.iter_mut() {
2446 path.hops.last_mut().unwrap().node_features = node_features.clone();
2450 let route = Route { paths, payment_params: Some(payment_params.clone()) };
2451 log_info!(logger, "Got route: {}", log_route!(route));
2455 // When an adversarial intermediary node observes a payment, it may be able to infer its
2456 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2457 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2458 // payment path by adding a randomized 'shadow route' offset to the final hop.
2459 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2460 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2462 let network_channels = network_graph.channels();
2463 let network_nodes = network_graph.nodes();
2465 for path in route.paths.iter_mut() {
2466 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2468 // Remember the last three nodes of the random walk and avoid looping back on them.
2469 // Init with the last three nodes from the actual path, if possible.
2470 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2471 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2472 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2474 // Choose the last publicly known node as the starting point for the random walk.
2475 let mut cur_hop: Option<NodeId> = None;
2476 let mut path_nonce = [0u8; 12];
2477 if let Some(starting_hop) = path.hops.iter().rev()
2478 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2479 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2480 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2483 // Init PRNG with the path-dependant nonce, which is static for private paths.
2484 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2485 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2487 // Pick a random path length in [1 .. 3]
2488 prng.process_in_place(&mut random_path_bytes);
2489 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2491 for random_hop in 0..random_walk_length {
2492 // If we don't find a suitable offset in the public network graph, we default to
2493 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2494 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2496 if let Some(cur_node_id) = cur_hop {
2497 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2498 // Randomly choose the next unvisited hop.
2499 prng.process_in_place(&mut random_path_bytes);
2500 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2501 .checked_rem(cur_node.channels.len())
2502 .and_then(|index| cur_node.channels.get(index))
2503 .and_then(|id| network_channels.get(id)) {
2504 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2505 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2506 nodes_to_avoid[random_hop] = *next_id;
2507 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2508 cur_hop = Some(*next_id);
2515 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2516 .checked_add(random_hop_offset)
2517 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2520 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2521 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2522 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2524 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2525 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2526 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2527 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2528 max_path_offset = cmp::max(
2529 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2530 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2531 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2533 // Add 'shadow' CLTV offset to the final hop
2534 if let Some(tail) = path.blinded_tail.as_mut() {
2535 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2536 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2538 if let Some(last_hop) = path.hops.last_mut() {
2539 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2540 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2545 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2546 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2548 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2549 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2550 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2551 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2552 ) -> Result<Route, LightningError>
2553 where L::Target: Logger, GL::Target: Logger {
2554 let graph_lock = network_graph.read_only();
2555 let mut route = build_route_from_hops_internal(
2556 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
2557 route_params.final_value_msat, logger, random_seed_bytes)?;
2558 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2562 fn build_route_from_hops_internal<L: Deref>(
2563 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
2564 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, logger: L,
2565 random_seed_bytes: &[u8; 32]
2566 ) -> Result<Route, LightningError> where L::Target: Logger {
2569 our_node_id: NodeId,
2570 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2573 impl Score for HopScorer {
2574 type ScoreParams = ();
2575 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2576 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2578 let mut cur_id = self.our_node_id;
2579 for i in 0..self.hop_ids.len() {
2580 if let Some(next_id) = self.hop_ids[i] {
2581 if cur_id == *source && next_id == *target {
2592 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
2594 fn payment_path_successful(&mut self, _path: &Path) {}
2596 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
2598 fn probe_successful(&mut self, _path: &Path) {}
2601 impl<'a> Writeable for HopScorer {
2603 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2608 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2609 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2612 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2613 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2614 for i in 0..hops.len() {
2615 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2618 let scorer = HopScorer { our_node_id, hop_ids };
2620 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
2621 logger, &scorer, &(), random_seed_bytes)
2626 use crate::blinded_path::{BlindedHop, BlindedPath};
2627 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2628 use crate::routing::utxo::UtxoResult;
2629 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2630 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2631 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
2632 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, Score, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2633 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2634 use crate::chain::transaction::OutPoint;
2635 use crate::sign::EntropySource;
2636 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2637 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2638 use crate::ln::channelmanager;
2639 use crate::offers::invoice::BlindedPayInfo;
2640 use crate::util::config::UserConfig;
2641 use crate::util::test_utils as ln_test_utils;
2642 use crate::util::chacha20::ChaCha20;
2643 use crate::util::ser::{Readable, Writeable};
2645 use crate::util::ser::Writer;
2647 use bitcoin::hashes::Hash;
2648 use bitcoin::network::constants::Network;
2649 use bitcoin::blockdata::constants::genesis_block;
2650 use bitcoin::blockdata::script::Builder;
2651 use bitcoin::blockdata::opcodes;
2652 use bitcoin::blockdata::transaction::TxOut;
2656 use bitcoin::secp256k1::{PublicKey,SecretKey};
2657 use bitcoin::secp256k1::Secp256k1;
2659 use crate::io::Cursor;
2660 use crate::prelude::*;
2661 use crate::sync::Arc;
2663 use core::convert::TryInto;
2665 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2666 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2667 channelmanager::ChannelDetails {
2668 channel_id: [0; 32],
2669 counterparty: channelmanager::ChannelCounterparty {
2672 unspendable_punishment_reserve: 0,
2673 forwarding_info: None,
2674 outbound_htlc_minimum_msat: None,
2675 outbound_htlc_maximum_msat: None,
2677 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2680 outbound_scid_alias: None,
2681 inbound_scid_alias: None,
2682 channel_value_satoshis: 0,
2685 outbound_capacity_msat,
2686 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2687 next_outbound_htlc_minimum_msat: 0,
2688 inbound_capacity_msat: 42,
2689 unspendable_punishment_reserve: None,
2690 confirmations_required: None,
2691 confirmations: None,
2692 force_close_spend_delay: None,
2693 is_outbound: true, is_channel_ready: true,
2694 is_usable: true, is_public: true,
2695 inbound_htlc_minimum_msat: None,
2696 inbound_htlc_maximum_msat: None,
2698 feerate_sat_per_1000_weight: None,
2699 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
2704 fn simple_route_test() {
2705 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2706 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2707 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2708 let scorer = ln_test_utils::TestScorer::new();
2709 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2710 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2712 // Simple route to 2 via 1
2714 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) {
2715 assert_eq!(err, "Cannot send a payment of 0 msat");
2716 } else { panic!(); }
2718 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2719 assert_eq!(route.paths[0].hops.len(), 2);
2721 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2722 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2723 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2724 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2725 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2726 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2728 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2729 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2730 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2731 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2732 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2733 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2737 fn invalid_first_hop_test() {
2738 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2739 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2740 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2741 let scorer = ln_test_utils::TestScorer::new();
2742 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2743 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2745 // Simple route to 2 via 1
2747 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2749 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2750 get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2751 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2752 } else { panic!(); }
2754 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2755 assert_eq!(route.paths[0].hops.len(), 2);
2759 fn htlc_minimum_test() {
2760 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2761 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2762 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2763 let scorer = ln_test_utils::TestScorer::new();
2764 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2765 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2767 // Simple route to 2 via 1
2769 // Disable other paths
2770 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2771 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2772 short_channel_id: 12,
2774 flags: 2, // to disable
2775 cltv_expiry_delta: 0,
2776 htlc_minimum_msat: 0,
2777 htlc_maximum_msat: MAX_VALUE_MSAT,
2779 fee_proportional_millionths: 0,
2780 excess_data: Vec::new()
2782 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2783 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2784 short_channel_id: 3,
2786 flags: 2, // to disable
2787 cltv_expiry_delta: 0,
2788 htlc_minimum_msat: 0,
2789 htlc_maximum_msat: MAX_VALUE_MSAT,
2791 fee_proportional_millionths: 0,
2792 excess_data: Vec::new()
2794 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2795 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2796 short_channel_id: 13,
2798 flags: 2, // to disable
2799 cltv_expiry_delta: 0,
2800 htlc_minimum_msat: 0,
2801 htlc_maximum_msat: MAX_VALUE_MSAT,
2803 fee_proportional_millionths: 0,
2804 excess_data: Vec::new()
2806 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2807 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2808 short_channel_id: 6,
2810 flags: 2, // to disable
2811 cltv_expiry_delta: 0,
2812 htlc_minimum_msat: 0,
2813 htlc_maximum_msat: MAX_VALUE_MSAT,
2815 fee_proportional_millionths: 0,
2816 excess_data: Vec::new()
2818 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2819 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2820 short_channel_id: 7,
2822 flags: 2, // to disable
2823 cltv_expiry_delta: 0,
2824 htlc_minimum_msat: 0,
2825 htlc_maximum_msat: MAX_VALUE_MSAT,
2827 fee_proportional_millionths: 0,
2828 excess_data: Vec::new()
2831 // Check against amount_to_transfer_over_msat.
2832 // Set minimal HTLC of 200_000_000 msat.
2833 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2834 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2835 short_channel_id: 2,
2838 cltv_expiry_delta: 0,
2839 htlc_minimum_msat: 200_000_000,
2840 htlc_maximum_msat: MAX_VALUE_MSAT,
2842 fee_proportional_millionths: 0,
2843 excess_data: Vec::new()
2846 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2848 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2849 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2850 short_channel_id: 4,
2853 cltv_expiry_delta: 0,
2854 htlc_minimum_msat: 0,
2855 htlc_maximum_msat: 199_999_999,
2857 fee_proportional_millionths: 0,
2858 excess_data: Vec::new()
2861 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2862 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) {
2863 assert_eq!(err, "Failed to find a path to the given destination");
2864 } else { panic!(); }
2866 // Lift the restriction on the first hop.
2867 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2868 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2869 short_channel_id: 2,
2872 cltv_expiry_delta: 0,
2873 htlc_minimum_msat: 0,
2874 htlc_maximum_msat: MAX_VALUE_MSAT,
2876 fee_proportional_millionths: 0,
2877 excess_data: Vec::new()
2880 // A payment above the minimum should pass
2881 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 199_999_999, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2882 assert_eq!(route.paths[0].hops.len(), 2);
2886 fn htlc_minimum_overpay_test() {
2887 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2888 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2889 let config = UserConfig::default();
2890 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
2891 let scorer = ln_test_utils::TestScorer::new();
2892 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2893 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2895 // A route to node#2 via two paths.
2896 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2897 // Thus, they can't send 60 without overpaying.
2898 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2899 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2900 short_channel_id: 2,
2903 cltv_expiry_delta: 0,
2904 htlc_minimum_msat: 35_000,
2905 htlc_maximum_msat: 40_000,
2907 fee_proportional_millionths: 0,
2908 excess_data: Vec::new()
2910 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2911 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2912 short_channel_id: 12,
2915 cltv_expiry_delta: 0,
2916 htlc_minimum_msat: 35_000,
2917 htlc_maximum_msat: 40_000,
2919 fee_proportional_millionths: 0,
2920 excess_data: Vec::new()
2924 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2925 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2926 short_channel_id: 13,
2929 cltv_expiry_delta: 0,
2930 htlc_minimum_msat: 0,
2931 htlc_maximum_msat: MAX_VALUE_MSAT,
2933 fee_proportional_millionths: 0,
2934 excess_data: Vec::new()
2936 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2937 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2938 short_channel_id: 4,
2941 cltv_expiry_delta: 0,
2942 htlc_minimum_msat: 0,
2943 htlc_maximum_msat: MAX_VALUE_MSAT,
2945 fee_proportional_millionths: 0,
2946 excess_data: Vec::new()
2949 // Disable other paths
2950 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2951 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2952 short_channel_id: 1,
2954 flags: 2, // to disable
2955 cltv_expiry_delta: 0,
2956 htlc_minimum_msat: 0,
2957 htlc_maximum_msat: MAX_VALUE_MSAT,
2959 fee_proportional_millionths: 0,
2960 excess_data: Vec::new()
2963 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2964 // Overpay fees to hit htlc_minimum_msat.
2965 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
2966 // TODO: this could be better balanced to overpay 10k and not 15k.
2967 assert_eq!(overpaid_fees, 15_000);
2969 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2970 // while taking even more fee to match htlc_minimum_msat.
2971 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2972 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2973 short_channel_id: 12,
2976 cltv_expiry_delta: 0,
2977 htlc_minimum_msat: 65_000,
2978 htlc_maximum_msat: 80_000,
2980 fee_proportional_millionths: 0,
2981 excess_data: Vec::new()
2983 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2984 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2985 short_channel_id: 2,
2988 cltv_expiry_delta: 0,
2989 htlc_minimum_msat: 0,
2990 htlc_maximum_msat: MAX_VALUE_MSAT,
2992 fee_proportional_millionths: 0,
2993 excess_data: Vec::new()
2995 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2996 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2997 short_channel_id: 4,
3000 cltv_expiry_delta: 0,
3001 htlc_minimum_msat: 0,
3002 htlc_maximum_msat: MAX_VALUE_MSAT,
3004 fee_proportional_millionths: 100_000,
3005 excess_data: Vec::new()
3008 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3009 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3010 assert_eq!(route.paths.len(), 1);
3011 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3012 let fees = route.paths[0].hops[0].fee_msat;
3013 assert_eq!(fees, 5_000);
3015 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3016 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3017 // the other channel.
3018 assert_eq!(route.paths.len(), 1);
3019 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3020 let fees = route.paths[0].hops[0].fee_msat;
3021 assert_eq!(fees, 5_000);
3025 fn disable_channels_test() {
3026 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3027 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3028 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3029 let scorer = ln_test_utils::TestScorer::new();
3030 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3031 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3033 // // Disable channels 4 and 12 by flags=2
3034 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3035 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3036 short_channel_id: 4,
3038 flags: 2, // to disable
3039 cltv_expiry_delta: 0,
3040 htlc_minimum_msat: 0,
3041 htlc_maximum_msat: MAX_VALUE_MSAT,
3043 fee_proportional_millionths: 0,
3044 excess_data: Vec::new()
3046 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3047 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3048 short_channel_id: 12,
3050 flags: 2, // to disable
3051 cltv_expiry_delta: 0,
3052 htlc_minimum_msat: 0,
3053 htlc_maximum_msat: MAX_VALUE_MSAT,
3055 fee_proportional_millionths: 0,
3056 excess_data: Vec::new()
3059 // If all the channels require some features we don't understand, route should fail
3060 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) {
3061 assert_eq!(err, "Failed to find a path to the given destination");
3062 } else { panic!(); }
3064 // If we specify a channel to node7, that overrides our local channel view and that gets used
3065 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3066 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();
3067 assert_eq!(route.paths[0].hops.len(), 2);
3069 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3070 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3071 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3072 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3073 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3074 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3076 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3077 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3078 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3079 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3080 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3081 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3085 fn disable_node_test() {
3086 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3087 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3088 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3089 let scorer = ln_test_utils::TestScorer::new();
3090 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3091 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3093 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3094 let mut unknown_features = NodeFeatures::empty();
3095 unknown_features.set_unknown_feature_required();
3096 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3097 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3098 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3100 // If all nodes require some features we don't understand, route should fail
3101 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) {
3102 assert_eq!(err, "Failed to find a path to the given destination");
3103 } else { panic!(); }
3105 // If we specify a channel to node7, that overrides our local channel view and that gets used
3106 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3107 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();
3108 assert_eq!(route.paths[0].hops.len(), 2);
3110 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3111 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3112 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3113 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3114 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3115 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3117 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3118 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3119 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3120 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3121 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3122 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3124 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3125 // naively) assume that the user checked the feature bits on the invoice, which override
3126 // the node_announcement.
3130 fn our_chans_test() {
3131 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3132 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3133 let scorer = ln_test_utils::TestScorer::new();
3134 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3135 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3137 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3138 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3139 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3140 assert_eq!(route.paths[0].hops.len(), 3);
3142 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3143 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3144 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3145 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3146 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3147 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3149 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3150 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3151 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3152 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3153 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3154 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3156 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3157 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3158 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3159 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3160 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3161 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3163 // If we specify a channel to node7, that overrides our local channel view and that gets used
3164 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3165 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3166 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();
3167 assert_eq!(route.paths[0].hops.len(), 2);
3169 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3170 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3171 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3172 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3173 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3174 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3176 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3177 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3178 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3179 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3180 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3181 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3184 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3185 let zero_fees = RoutingFees {
3187 proportional_millionths: 0,
3189 vec![RouteHint(vec![RouteHintHop {
3190 src_node_id: nodes[3],
3191 short_channel_id: 8,
3193 cltv_expiry_delta: (8 << 4) | 1,
3194 htlc_minimum_msat: None,
3195 htlc_maximum_msat: None,
3197 ]), RouteHint(vec![RouteHintHop {
3198 src_node_id: nodes[4],
3199 short_channel_id: 9,
3202 proportional_millionths: 0,
3204 cltv_expiry_delta: (9 << 4) | 1,
3205 htlc_minimum_msat: None,
3206 htlc_maximum_msat: None,
3207 }]), RouteHint(vec![RouteHintHop {
3208 src_node_id: nodes[5],
3209 short_channel_id: 10,
3211 cltv_expiry_delta: (10 << 4) | 1,
3212 htlc_minimum_msat: None,
3213 htlc_maximum_msat: None,
3217 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3218 let zero_fees = RoutingFees {
3220 proportional_millionths: 0,
3222 vec![RouteHint(vec![RouteHintHop {
3223 src_node_id: nodes[2],
3224 short_channel_id: 5,
3227 proportional_millionths: 0,
3229 cltv_expiry_delta: (5 << 4) | 1,
3230 htlc_minimum_msat: None,
3231 htlc_maximum_msat: None,
3233 src_node_id: nodes[3],
3234 short_channel_id: 8,
3236 cltv_expiry_delta: (8 << 4) | 1,
3237 htlc_minimum_msat: None,
3238 htlc_maximum_msat: None,
3240 ]), RouteHint(vec![RouteHintHop {
3241 src_node_id: nodes[4],
3242 short_channel_id: 9,
3245 proportional_millionths: 0,
3247 cltv_expiry_delta: (9 << 4) | 1,
3248 htlc_minimum_msat: None,
3249 htlc_maximum_msat: None,
3250 }]), RouteHint(vec![RouteHintHop {
3251 src_node_id: nodes[5],
3252 short_channel_id: 10,
3254 cltv_expiry_delta: (10 << 4) | 1,
3255 htlc_minimum_msat: None,
3256 htlc_maximum_msat: None,
3261 fn partial_route_hint_test() {
3262 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3263 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3264 let scorer = ln_test_utils::TestScorer::new();
3265 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3266 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3268 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3269 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3270 // RouteHint may be partially used by the algo to build the best path.
3272 // First check that last hop can't have its source as the payee.
3273 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3274 src_node_id: nodes[6],
3275 short_channel_id: 8,
3278 proportional_millionths: 0,
3280 cltv_expiry_delta: (8 << 4) | 1,
3281 htlc_minimum_msat: None,
3282 htlc_maximum_msat: None,
3285 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3286 invalid_last_hops.push(invalid_last_hop);
3288 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(invalid_last_hops).unwrap();
3289 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) {
3290 assert_eq!(err, "Route hint cannot have the payee as the source.");
3291 } else { panic!(); }
3294 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3295 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3296 assert_eq!(route.paths[0].hops.len(), 5);
3298 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3299 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3300 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3301 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3302 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3303 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3305 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3306 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3307 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3308 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3309 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3310 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3312 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3313 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3314 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3315 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3316 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3317 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3319 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3320 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3321 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3322 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3323 // If we have a peer in the node map, we'll use their features here since we don't have
3324 // a way of figuring out their features from the invoice:
3325 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3326 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3328 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3329 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3330 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3331 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3332 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3333 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3336 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3337 let zero_fees = RoutingFees {
3339 proportional_millionths: 0,
3341 vec![RouteHint(vec![RouteHintHop {
3342 src_node_id: nodes[3],
3343 short_channel_id: 8,
3345 cltv_expiry_delta: (8 << 4) | 1,
3346 htlc_minimum_msat: None,
3347 htlc_maximum_msat: None,
3348 }]), RouteHint(vec![
3350 ]), RouteHint(vec![RouteHintHop {
3351 src_node_id: nodes[5],
3352 short_channel_id: 10,
3354 cltv_expiry_delta: (10 << 4) | 1,
3355 htlc_minimum_msat: None,
3356 htlc_maximum_msat: None,
3361 fn ignores_empty_last_hops_test() {
3362 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3363 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3364 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3365 let scorer = ln_test_utils::TestScorer::new();
3366 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3367 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3369 // Test handling of an empty RouteHint passed in Invoice.
3371 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3372 assert_eq!(route.paths[0].hops.len(), 5);
3374 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3375 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3376 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3377 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3378 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3379 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3381 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3382 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3383 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3384 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3385 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3386 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3388 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3389 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3390 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3391 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3392 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3393 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3395 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3396 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3397 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3398 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3399 // If we have a peer in the node map, we'll use their features here since we don't have
3400 // a way of figuring out their features from the invoice:
3401 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3402 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3404 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3405 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3406 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3407 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3408 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3409 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3412 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3414 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3415 let zero_fees = RoutingFees {
3417 proportional_millionths: 0,
3419 vec![RouteHint(vec![RouteHintHop {
3420 src_node_id: hint_hops[0],
3421 short_channel_id: 0xff00,
3424 proportional_millionths: 0,
3426 cltv_expiry_delta: (5 << 4) | 1,
3427 htlc_minimum_msat: None,
3428 htlc_maximum_msat: None,
3430 src_node_id: hint_hops[1],
3431 short_channel_id: 0xff01,
3433 cltv_expiry_delta: (8 << 4) | 1,
3434 htlc_minimum_msat: None,
3435 htlc_maximum_msat: None,
3440 fn multi_hint_last_hops_test() {
3441 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3442 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3443 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3444 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3445 let scorer = ln_test_utils::TestScorer::new();
3446 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3447 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3448 // Test through channels 2, 3, 0xff00, 0xff01.
3449 // Test shows that multiple hop hints are considered.
3451 // Disabling channels 6 & 7 by flags=2
3452 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3453 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3454 short_channel_id: 6,
3456 flags: 2, // to disable
3457 cltv_expiry_delta: 0,
3458 htlc_minimum_msat: 0,
3459 htlc_maximum_msat: MAX_VALUE_MSAT,
3461 fee_proportional_millionths: 0,
3462 excess_data: Vec::new()
3464 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3465 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3466 short_channel_id: 7,
3468 flags: 2, // to disable
3469 cltv_expiry_delta: 0,
3470 htlc_minimum_msat: 0,
3471 htlc_maximum_msat: MAX_VALUE_MSAT,
3473 fee_proportional_millionths: 0,
3474 excess_data: Vec::new()
3477 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3478 assert_eq!(route.paths[0].hops.len(), 4);
3480 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3481 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3482 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3483 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3484 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3485 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3487 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3488 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3489 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3490 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3491 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3492 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3494 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3495 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3496 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3497 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3498 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3499 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3501 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3502 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3503 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3504 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3505 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3506 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3510 fn private_multi_hint_last_hops_test() {
3511 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3512 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3514 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3515 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3517 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3518 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3519 let scorer = ln_test_utils::TestScorer::new();
3520 // Test through channels 2, 3, 0xff00, 0xff01.
3521 // Test shows that multiple hop hints are considered.
3523 // Disabling channels 6 & 7 by flags=2
3524 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3525 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3526 short_channel_id: 6,
3528 flags: 2, // to disable
3529 cltv_expiry_delta: 0,
3530 htlc_minimum_msat: 0,
3531 htlc_maximum_msat: MAX_VALUE_MSAT,
3533 fee_proportional_millionths: 0,
3534 excess_data: Vec::new()
3536 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3537 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3538 short_channel_id: 7,
3540 flags: 2, // to disable
3541 cltv_expiry_delta: 0,
3542 htlc_minimum_msat: 0,
3543 htlc_maximum_msat: MAX_VALUE_MSAT,
3545 fee_proportional_millionths: 0,
3546 excess_data: Vec::new()
3549 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &[42u8; 32]).unwrap();
3550 assert_eq!(route.paths[0].hops.len(), 4);
3552 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3553 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3554 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3555 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3556 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3557 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3559 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3560 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3561 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3562 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3563 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3564 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3566 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3567 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3568 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3569 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3570 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3571 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3573 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3574 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3575 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3576 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3577 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3578 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3581 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3582 let zero_fees = RoutingFees {
3584 proportional_millionths: 0,
3586 vec![RouteHint(vec![RouteHintHop {
3587 src_node_id: nodes[4],
3588 short_channel_id: 11,
3590 cltv_expiry_delta: (11 << 4) | 1,
3591 htlc_minimum_msat: None,
3592 htlc_maximum_msat: None,
3594 src_node_id: nodes[3],
3595 short_channel_id: 8,
3597 cltv_expiry_delta: (8 << 4) | 1,
3598 htlc_minimum_msat: None,
3599 htlc_maximum_msat: None,
3600 }]), RouteHint(vec![RouteHintHop {
3601 src_node_id: nodes[4],
3602 short_channel_id: 9,
3605 proportional_millionths: 0,
3607 cltv_expiry_delta: (9 << 4) | 1,
3608 htlc_minimum_msat: None,
3609 htlc_maximum_msat: None,
3610 }]), RouteHint(vec![RouteHintHop {
3611 src_node_id: nodes[5],
3612 short_channel_id: 10,
3614 cltv_expiry_delta: (10 << 4) | 1,
3615 htlc_minimum_msat: None,
3616 htlc_maximum_msat: None,
3621 fn last_hops_with_public_channel_test() {
3622 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3623 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3624 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
3625 let scorer = ln_test_utils::TestScorer::new();
3626 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3627 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3628 // This test shows that public routes can be present in the invoice
3629 // which would be handled in the same manner.
3631 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3632 assert_eq!(route.paths[0].hops.len(), 5);
3634 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3635 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3636 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3637 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3638 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3639 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3641 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3642 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3643 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3644 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3645 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3646 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3648 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3649 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3650 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3651 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3652 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3653 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3655 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3656 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3657 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3658 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3659 // If we have a peer in the node map, we'll use their features here since we don't have
3660 // a way of figuring out their features from the invoice:
3661 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3662 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3664 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3665 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3666 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3667 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3668 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3669 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3673 fn our_chans_last_hop_connect_test() {
3674 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3675 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3676 let scorer = ln_test_utils::TestScorer::new();
3677 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3678 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3680 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3681 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3682 let mut last_hops = last_hops(&nodes);
3683 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3684 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();
3685 assert_eq!(route.paths[0].hops.len(), 2);
3687 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3688 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3689 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3690 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3691 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3692 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3694 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3695 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3696 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3697 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3698 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3699 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3701 last_hops[0].0[0].fees.base_msat = 1000;
3703 // Revert to via 6 as the fee on 8 goes up
3704 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops).unwrap();
3705 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3706 assert_eq!(route.paths[0].hops.len(), 4);
3708 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3709 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3710 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
3711 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3712 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3713 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3715 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3716 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3717 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3718 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
3719 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3720 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3722 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
3723 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3724 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3725 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3726 // If we have a peer in the node map, we'll use their features here since we don't have
3727 // a way of figuring out their features from the invoice:
3728 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3729 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3731 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3732 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3733 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3734 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3735 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3736 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3738 // ...but still use 8 for larger payments as 6 has a variable feerate
3739 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3740 assert_eq!(route.paths[0].hops.len(), 5);
3742 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3743 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3744 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3745 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3746 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3747 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3749 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3750 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3751 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3752 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3753 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3754 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3756 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3757 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3758 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3759 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3760 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3761 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3763 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3764 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3765 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
3766 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3767 // If we have a peer in the node map, we'll use their features here since we don't have
3768 // a way of figuring out their features from the invoice:
3769 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3770 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3772 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3773 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3774 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
3775 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3776 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3777 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3780 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> {
3781 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3782 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3783 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3785 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3786 let last_hops = RouteHint(vec![RouteHintHop {
3787 src_node_id: middle_node_id,
3788 short_channel_id: 8,
3791 proportional_millionths: last_hop_fee_prop,
3793 cltv_expiry_delta: (8 << 4) | 1,
3794 htlc_minimum_msat: None,
3795 htlc_maximum_msat: last_hop_htlc_max,
3797 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
3798 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3799 let scorer = ln_test_utils::TestScorer::new();
3800 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3801 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3802 let logger = ln_test_utils::TestLogger::new();
3803 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3804 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3805 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, &logger, &scorer, &(), &random_seed_bytes);
3810 fn unannounced_path_test() {
3811 // We should be able to send a payment to a destination without any help of a routing graph
3812 // if we have a channel with a common counterparty that appears in the first and last hop
3814 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3816 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3817 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3818 assert_eq!(route.paths[0].hops.len(), 2);
3820 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
3821 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3822 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
3823 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3824 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
3825 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3827 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
3828 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3829 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
3830 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3831 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3832 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3836 fn overflow_unannounced_path_test_liquidity_underflow() {
3837 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3838 // the last-hop had a fee which overflowed a u64, we'd panic.
3839 // This was due to us adding the first-hop from us unconditionally, causing us to think
3840 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3841 // In this test, we previously hit a subtraction underflow due to having less available
3842 // liquidity at the last hop than 0.
3843 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());
3847 fn overflow_unannounced_path_test_feerate_overflow() {
3848 // This tests for the same case as above, except instead of hitting a subtraction
3849 // underflow, we hit a case where the fee charged at a hop overflowed.
3850 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());
3854 fn available_amount_while_routing_test() {
3855 // Tests whether we choose the correct available channel amount while routing.
3857 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3858 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3859 let scorer = ln_test_utils::TestScorer::new();
3860 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3861 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3862 let config = UserConfig::default();
3863 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3865 // We will use a simple single-path route from
3866 // our node to node2 via node0: channels {1, 3}.
3868 // First disable all other paths.
3869 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3870 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3871 short_channel_id: 2,
3874 cltv_expiry_delta: 0,
3875 htlc_minimum_msat: 0,
3876 htlc_maximum_msat: 100_000,
3878 fee_proportional_millionths: 0,
3879 excess_data: Vec::new()
3881 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3882 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3883 short_channel_id: 12,
3886 cltv_expiry_delta: 0,
3887 htlc_minimum_msat: 0,
3888 htlc_maximum_msat: 100_000,
3890 fee_proportional_millionths: 0,
3891 excess_data: Vec::new()
3894 // Make the first channel (#1) very permissive,
3895 // and we will be testing all limits on the second channel.
3896 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3897 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3898 short_channel_id: 1,
3901 cltv_expiry_delta: 0,
3902 htlc_minimum_msat: 0,
3903 htlc_maximum_msat: 1_000_000_000,
3905 fee_proportional_millionths: 0,
3906 excess_data: Vec::new()
3909 // First, let's see if routing works if we have absolutely no idea about the available amount.
3910 // In this case, it should be set to 250_000 sats.
3911 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3912 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3913 short_channel_id: 3,
3916 cltv_expiry_delta: 0,
3917 htlc_minimum_msat: 0,
3918 htlc_maximum_msat: 250_000_000,
3920 fee_proportional_millionths: 0,
3921 excess_data: Vec::new()
3925 // Attempt to route more than available results in a failure.
3926 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3927 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3928 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3929 } else { panic!(); }
3933 // Now, attempt to route an exact amount we have should be fine.
3934 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000_000, Arc::clone(&logger), &scorer, &(),&random_seed_bytes).unwrap();
3935 assert_eq!(route.paths.len(), 1);
3936 let path = route.paths.last().unwrap();
3937 assert_eq!(path.hops.len(), 2);
3938 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3939 assert_eq!(path.final_value_msat(), 250_000_000);
3942 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3943 // Disable channel #1 and use another first hop.
3944 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3945 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3946 short_channel_id: 1,
3949 cltv_expiry_delta: 0,
3950 htlc_minimum_msat: 0,
3951 htlc_maximum_msat: 1_000_000_000,
3953 fee_proportional_millionths: 0,
3954 excess_data: Vec::new()
3957 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3958 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3961 // Attempt to route more than available results in a failure.
3962 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3963 &our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3964 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3965 } else { panic!(); }
3969 // Now, attempt to route an exact amount we have should be fine.
3970 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();
3971 assert_eq!(route.paths.len(), 1);
3972 let path = route.paths.last().unwrap();
3973 assert_eq!(path.hops.len(), 2);
3974 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3975 assert_eq!(path.final_value_msat(), 200_000_000);
3978 // Enable channel #1 back.
3979 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3980 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3981 short_channel_id: 1,
3984 cltv_expiry_delta: 0,
3985 htlc_minimum_msat: 0,
3986 htlc_maximum_msat: 1_000_000_000,
3988 fee_proportional_millionths: 0,
3989 excess_data: Vec::new()
3993 // Now let's see if routing works if we know only htlc_maximum_msat.
3994 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3995 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3996 short_channel_id: 3,
3999 cltv_expiry_delta: 0,
4000 htlc_minimum_msat: 0,
4001 htlc_maximum_msat: 15_000,
4003 fee_proportional_millionths: 0,
4004 excess_data: Vec::new()
4008 // Attempt to route more than available results in a failure.
4009 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4010 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4011 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4012 } else { panic!(); }
4016 // Now, attempt to route an exact amount we have should be fine.
4017 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4018 assert_eq!(route.paths.len(), 1);
4019 let path = route.paths.last().unwrap();
4020 assert_eq!(path.hops.len(), 2);
4021 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4022 assert_eq!(path.final_value_msat(), 15_000);
4025 // Now let's see if routing works if we know only capacity from the UTXO.
4027 // We can't change UTXO capacity on the fly, so we'll disable
4028 // the existing channel and add another one with the capacity we need.
4029 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4030 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4031 short_channel_id: 3,
4034 cltv_expiry_delta: 0,
4035 htlc_minimum_msat: 0,
4036 htlc_maximum_msat: MAX_VALUE_MSAT,
4038 fee_proportional_millionths: 0,
4039 excess_data: Vec::new()
4042 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4043 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4044 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4045 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4046 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4048 *chain_monitor.utxo_ret.lock().unwrap() =
4049 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4050 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4052 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4053 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4054 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4055 short_channel_id: 333,
4058 cltv_expiry_delta: (3 << 4) | 1,
4059 htlc_minimum_msat: 0,
4060 htlc_maximum_msat: 15_000,
4062 fee_proportional_millionths: 0,
4063 excess_data: Vec::new()
4065 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4066 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4067 short_channel_id: 333,
4070 cltv_expiry_delta: (3 << 4) | 2,
4071 htlc_minimum_msat: 0,
4072 htlc_maximum_msat: 15_000,
4074 fee_proportional_millionths: 0,
4075 excess_data: Vec::new()
4079 // Attempt to route more than available results in a failure.
4080 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4081 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4082 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4083 } else { panic!(); }
4087 // Now, attempt to route an exact amount we have should be fine.
4088 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4089 assert_eq!(route.paths.len(), 1);
4090 let path = route.paths.last().unwrap();
4091 assert_eq!(path.hops.len(), 2);
4092 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4093 assert_eq!(path.final_value_msat(), 15_000);
4096 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4097 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4098 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4099 short_channel_id: 333,
4102 cltv_expiry_delta: 0,
4103 htlc_minimum_msat: 0,
4104 htlc_maximum_msat: 10_000,
4106 fee_proportional_millionths: 0,
4107 excess_data: Vec::new()
4111 // Attempt to route more than available results in a failure.
4112 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4113 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4114 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4115 } else { panic!(); }
4119 // Now, attempt to route an exact amount we have should be fine.
4120 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4121 assert_eq!(route.paths.len(), 1);
4122 let path = route.paths.last().unwrap();
4123 assert_eq!(path.hops.len(), 2);
4124 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4125 assert_eq!(path.final_value_msat(), 10_000);
4130 fn available_liquidity_last_hop_test() {
4131 // Check that available liquidity properly limits the path even when only
4132 // one of the latter hops is limited.
4133 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4134 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4135 let scorer = ln_test_utils::TestScorer::new();
4136 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4137 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4138 let config = UserConfig::default();
4139 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4141 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4142 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4143 // Total capacity: 50 sats.
4145 // Disable other potential paths.
4146 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4147 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4148 short_channel_id: 2,
4151 cltv_expiry_delta: 0,
4152 htlc_minimum_msat: 0,
4153 htlc_maximum_msat: 100_000,
4155 fee_proportional_millionths: 0,
4156 excess_data: Vec::new()
4158 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4159 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4160 short_channel_id: 7,
4163 cltv_expiry_delta: 0,
4164 htlc_minimum_msat: 0,
4165 htlc_maximum_msat: 100_000,
4167 fee_proportional_millionths: 0,
4168 excess_data: Vec::new()
4173 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4174 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4175 short_channel_id: 12,
4178 cltv_expiry_delta: 0,
4179 htlc_minimum_msat: 0,
4180 htlc_maximum_msat: 100_000,
4182 fee_proportional_millionths: 0,
4183 excess_data: Vec::new()
4185 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4186 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4187 short_channel_id: 13,
4190 cltv_expiry_delta: 0,
4191 htlc_minimum_msat: 0,
4192 htlc_maximum_msat: 100_000,
4194 fee_proportional_millionths: 0,
4195 excess_data: Vec::new()
4198 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4199 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4200 short_channel_id: 6,
4203 cltv_expiry_delta: 0,
4204 htlc_minimum_msat: 0,
4205 htlc_maximum_msat: 50_000,
4207 fee_proportional_millionths: 0,
4208 excess_data: Vec::new()
4210 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4211 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4212 short_channel_id: 11,
4215 cltv_expiry_delta: 0,
4216 htlc_minimum_msat: 0,
4217 htlc_maximum_msat: 100_000,
4219 fee_proportional_millionths: 0,
4220 excess_data: Vec::new()
4223 // Attempt to route more than available results in a failure.
4224 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4225 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4226 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4227 } else { panic!(); }
4231 // Now, attempt to route 49 sats (just a bit below the capacity).
4232 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4233 assert_eq!(route.paths.len(), 1);
4234 let mut total_amount_paid_msat = 0;
4235 for path in &route.paths {
4236 assert_eq!(path.hops.len(), 4);
4237 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4238 total_amount_paid_msat += path.final_value_msat();
4240 assert_eq!(total_amount_paid_msat, 49_000);
4244 // Attempt to route an exact amount is also fine
4245 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4246 assert_eq!(route.paths.len(), 1);
4247 let mut total_amount_paid_msat = 0;
4248 for path in &route.paths {
4249 assert_eq!(path.hops.len(), 4);
4250 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4251 total_amount_paid_msat += path.final_value_msat();
4253 assert_eq!(total_amount_paid_msat, 50_000);
4258 fn ignore_fee_first_hop_test() {
4259 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4260 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4261 let scorer = ln_test_utils::TestScorer::new();
4262 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4263 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4264 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4266 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4267 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4268 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4269 short_channel_id: 1,
4272 cltv_expiry_delta: 0,
4273 htlc_minimum_msat: 0,
4274 htlc_maximum_msat: 100_000,
4275 fee_base_msat: 1_000_000,
4276 fee_proportional_millionths: 0,
4277 excess_data: Vec::new()
4279 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4280 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4281 short_channel_id: 3,
4284 cltv_expiry_delta: 0,
4285 htlc_minimum_msat: 0,
4286 htlc_maximum_msat: 50_000,
4288 fee_proportional_millionths: 0,
4289 excess_data: Vec::new()
4293 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4294 assert_eq!(route.paths.len(), 1);
4295 let mut total_amount_paid_msat = 0;
4296 for path in &route.paths {
4297 assert_eq!(path.hops.len(), 2);
4298 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4299 total_amount_paid_msat += path.final_value_msat();
4301 assert_eq!(total_amount_paid_msat, 50_000);
4306 fn simple_mpp_route_test() {
4307 let (secp_ctx, _, _, _, _) = build_graph();
4308 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4309 let config = UserConfig::default();
4310 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4311 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4312 do_simple_mpp_route_test(clear_payment_params);
4314 // MPP to a 1-hop blinded path for nodes[2]
4315 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
4316 let blinded_path = BlindedPath {
4317 introduction_node_id: nodes[2],
4318 blinding_point: ln_test_utils::pubkey(42),
4319 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4321 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4323 fee_proportional_millionths: 0,
4324 htlc_minimum_msat: 0,
4325 htlc_maximum_msat: 0,
4326 cltv_expiry_delta: 0,
4327 features: BlindedHopFeatures::empty(),
4329 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4330 .with_bolt12_features(bolt12_features.clone()).unwrap();
4331 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4333 // MPP to 3 2-hop blinded paths
4334 let mut blinded_path_node_0 = blinded_path.clone();
4335 blinded_path_node_0.introduction_node_id = nodes[0];
4336 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4337 let mut node_0_payinfo = blinded_payinfo.clone();
4338 node_0_payinfo.htlc_maximum_msat = 50_000;
4340 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4341 blinded_path_node_7.introduction_node_id = nodes[7];
4342 let mut node_7_payinfo = blinded_payinfo.clone();
4343 node_7_payinfo.htlc_maximum_msat = 60_000;
4345 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4346 blinded_path_node_1.introduction_node_id = nodes[1];
4347 let mut node_1_payinfo = blinded_payinfo.clone();
4348 node_1_payinfo.htlc_maximum_msat = 180_000;
4350 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4352 (node_0_payinfo, blinded_path_node_0),
4353 (node_7_payinfo, blinded_path_node_7),
4354 (node_1_payinfo, blinded_path_node_1)
4356 .with_bolt12_features(bolt12_features).unwrap();
4357 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4361 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4362 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4363 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4364 let scorer = ln_test_utils::TestScorer::new();
4365 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4366 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4368 // We need a route consisting of 3 paths:
4369 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4370 // To achieve this, the amount being transferred should be around
4371 // the total capacity of these 3 paths.
4373 // First, we set limits on these (previously unlimited) channels.
4374 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4376 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4377 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4378 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4379 short_channel_id: 1,
4382 cltv_expiry_delta: 0,
4383 htlc_minimum_msat: 0,
4384 htlc_maximum_msat: 100_000,
4386 fee_proportional_millionths: 0,
4387 excess_data: Vec::new()
4389 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4390 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4391 short_channel_id: 3,
4394 cltv_expiry_delta: 0,
4395 htlc_minimum_msat: 0,
4396 htlc_maximum_msat: 50_000,
4398 fee_proportional_millionths: 0,
4399 excess_data: Vec::new()
4402 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4403 // (total limit 60).
4404 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4405 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4406 short_channel_id: 12,
4409 cltv_expiry_delta: 0,
4410 htlc_minimum_msat: 0,
4411 htlc_maximum_msat: 60_000,
4413 fee_proportional_millionths: 0,
4414 excess_data: Vec::new()
4416 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4417 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4418 short_channel_id: 13,
4421 cltv_expiry_delta: 0,
4422 htlc_minimum_msat: 0,
4423 htlc_maximum_msat: 60_000,
4425 fee_proportional_millionths: 0,
4426 excess_data: Vec::new()
4429 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4430 // (total capacity 180 sats).
4431 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4432 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4433 short_channel_id: 2,
4436 cltv_expiry_delta: 0,
4437 htlc_minimum_msat: 0,
4438 htlc_maximum_msat: 200_000,
4440 fee_proportional_millionths: 0,
4441 excess_data: Vec::new()
4443 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4444 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4445 short_channel_id: 4,
4448 cltv_expiry_delta: 0,
4449 htlc_minimum_msat: 0,
4450 htlc_maximum_msat: 180_000,
4452 fee_proportional_millionths: 0,
4453 excess_data: Vec::new()
4457 // Attempt to route more than available results in a failure.
4458 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4459 &our_id, &payment_params, &network_graph.read_only(), None, 300_000,
4460 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4461 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4462 } else { panic!(); }
4466 // Attempt to route while setting max_path_count to 0 results in a failure.
4467 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4468 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4469 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100,
4470 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4471 assert_eq!(err, "Can't find a route with no paths allowed.");
4472 } else { panic!(); }
4476 // Attempt to route while setting max_path_count to 3 results in a failure.
4477 // This is the case because the minimal_value_contribution_msat would require each path
4478 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4479 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4480 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4481 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000,
4482 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4483 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4484 } else { panic!(); }
4488 // Now, attempt to route 250 sats (just a bit below the capacity).
4489 // Our algorithm should provide us with these 3 paths.
4490 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4491 250_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4492 assert_eq!(route.paths.len(), 3);
4493 let mut total_amount_paid_msat = 0;
4494 for path in &route.paths {
4495 if let Some(bt) = &path.blinded_tail {
4496 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4498 assert_eq!(path.hops.len(), 2);
4499 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4501 total_amount_paid_msat += path.final_value_msat();
4503 assert_eq!(total_amount_paid_msat, 250_000);
4507 // Attempt to route an exact amount is also fine
4508 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4509 290_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4510 assert_eq!(route.paths.len(), 3);
4511 let mut total_amount_paid_msat = 0;
4512 for path in &route.paths {
4513 if payment_params.payee.blinded_route_hints().len() != 0 {
4514 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
4515 if let Some(bt) = &path.blinded_tail {
4516 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4517 if bt.hops.len() > 1 {
4518 assert_eq!(path.hops.last().unwrap().pubkey,
4519 payment_params.payee.blinded_route_hints().iter()
4520 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
4521 .map(|(_, p)| p.introduction_node_id).unwrap());
4523 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4526 assert_eq!(path.hops.len(), 2);
4527 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4529 total_amount_paid_msat += path.final_value_msat();
4531 assert_eq!(total_amount_paid_msat, 290_000);
4536 fn long_mpp_route_test() {
4537 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4538 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4539 let scorer = ln_test_utils::TestScorer::new();
4540 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4541 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4542 let config = UserConfig::default();
4543 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4545 // We need a route consisting of 3 paths:
4546 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4547 // Note that these paths overlap (channels 5, 12, 13).
4548 // We will route 300 sats.
4549 // Each path will have 100 sats capacity, those channels which
4550 // are used twice will have 200 sats capacity.
4552 // Disable other potential paths.
4553 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4554 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4555 short_channel_id: 2,
4558 cltv_expiry_delta: 0,
4559 htlc_minimum_msat: 0,
4560 htlc_maximum_msat: 100_000,
4562 fee_proportional_millionths: 0,
4563 excess_data: Vec::new()
4565 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4566 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4567 short_channel_id: 7,
4570 cltv_expiry_delta: 0,
4571 htlc_minimum_msat: 0,
4572 htlc_maximum_msat: 100_000,
4574 fee_proportional_millionths: 0,
4575 excess_data: Vec::new()
4578 // Path via {node0, node2} is channels {1, 3, 5}.
4579 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4580 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4581 short_channel_id: 1,
4584 cltv_expiry_delta: 0,
4585 htlc_minimum_msat: 0,
4586 htlc_maximum_msat: 100_000,
4588 fee_proportional_millionths: 0,
4589 excess_data: Vec::new()
4591 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4592 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4593 short_channel_id: 3,
4596 cltv_expiry_delta: 0,
4597 htlc_minimum_msat: 0,
4598 htlc_maximum_msat: 100_000,
4600 fee_proportional_millionths: 0,
4601 excess_data: Vec::new()
4604 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4605 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4606 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4607 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4608 short_channel_id: 5,
4611 cltv_expiry_delta: 0,
4612 htlc_minimum_msat: 0,
4613 htlc_maximum_msat: 200_000,
4615 fee_proportional_millionths: 0,
4616 excess_data: Vec::new()
4619 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4620 // Add 100 sats to the capacities of {12, 13}, because these channels
4621 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4622 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4623 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4624 short_channel_id: 12,
4627 cltv_expiry_delta: 0,
4628 htlc_minimum_msat: 0,
4629 htlc_maximum_msat: 200_000,
4631 fee_proportional_millionths: 0,
4632 excess_data: Vec::new()
4634 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4635 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4636 short_channel_id: 13,
4639 cltv_expiry_delta: 0,
4640 htlc_minimum_msat: 0,
4641 htlc_maximum_msat: 200_000,
4643 fee_proportional_millionths: 0,
4644 excess_data: Vec::new()
4647 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4648 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4649 short_channel_id: 6,
4652 cltv_expiry_delta: 0,
4653 htlc_minimum_msat: 0,
4654 htlc_maximum_msat: 100_000,
4656 fee_proportional_millionths: 0,
4657 excess_data: Vec::new()
4659 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4660 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4661 short_channel_id: 11,
4664 cltv_expiry_delta: 0,
4665 htlc_minimum_msat: 0,
4666 htlc_maximum_msat: 100_000,
4668 fee_proportional_millionths: 0,
4669 excess_data: Vec::new()
4672 // Path via {node7, node2} is channels {12, 13, 5}.
4673 // We already limited them to 200 sats (they are used twice for 100 sats).
4674 // Nothing to do here.
4677 // Attempt to route more than available results in a failure.
4678 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4679 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4680 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4681 } else { panic!(); }
4685 // Now, attempt to route 300 sats (exact amount we can route).
4686 // Our algorithm should provide us with these 3 paths, 100 sats each.
4687 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4688 assert_eq!(route.paths.len(), 3);
4690 let mut total_amount_paid_msat = 0;
4691 for path in &route.paths {
4692 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4693 total_amount_paid_msat += path.final_value_msat();
4695 assert_eq!(total_amount_paid_msat, 300_000);
4701 fn mpp_cheaper_route_test() {
4702 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4703 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4704 let scorer = ln_test_utils::TestScorer::new();
4705 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4706 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4707 let config = UserConfig::default();
4708 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4710 // This test checks that if we have two cheaper paths and one more expensive path,
4711 // so that liquidity-wise any 2 of 3 combination is sufficient,
4712 // two cheaper paths will be taken.
4713 // These paths have equal available liquidity.
4715 // We need a combination of 3 paths:
4716 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4717 // Note that these paths overlap (channels 5, 12, 13).
4718 // Each path will have 100 sats capacity, those channels which
4719 // are used twice will have 200 sats capacity.
4721 // Disable other potential paths.
4722 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4723 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4724 short_channel_id: 2,
4727 cltv_expiry_delta: 0,
4728 htlc_minimum_msat: 0,
4729 htlc_maximum_msat: 100_000,
4731 fee_proportional_millionths: 0,
4732 excess_data: Vec::new()
4734 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4735 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4736 short_channel_id: 7,
4739 cltv_expiry_delta: 0,
4740 htlc_minimum_msat: 0,
4741 htlc_maximum_msat: 100_000,
4743 fee_proportional_millionths: 0,
4744 excess_data: Vec::new()
4747 // Path via {node0, node2} is channels {1, 3, 5}.
4748 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4749 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4750 short_channel_id: 1,
4753 cltv_expiry_delta: 0,
4754 htlc_minimum_msat: 0,
4755 htlc_maximum_msat: 100_000,
4757 fee_proportional_millionths: 0,
4758 excess_data: Vec::new()
4760 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4761 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4762 short_channel_id: 3,
4765 cltv_expiry_delta: 0,
4766 htlc_minimum_msat: 0,
4767 htlc_maximum_msat: 100_000,
4769 fee_proportional_millionths: 0,
4770 excess_data: Vec::new()
4773 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4774 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4775 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4776 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4777 short_channel_id: 5,
4780 cltv_expiry_delta: 0,
4781 htlc_minimum_msat: 0,
4782 htlc_maximum_msat: 200_000,
4784 fee_proportional_millionths: 0,
4785 excess_data: Vec::new()
4788 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4789 // Add 100 sats to the capacities of {12, 13}, because these channels
4790 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4791 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4792 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4793 short_channel_id: 12,
4796 cltv_expiry_delta: 0,
4797 htlc_minimum_msat: 0,
4798 htlc_maximum_msat: 200_000,
4800 fee_proportional_millionths: 0,
4801 excess_data: Vec::new()
4803 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4804 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4805 short_channel_id: 13,
4808 cltv_expiry_delta: 0,
4809 htlc_minimum_msat: 0,
4810 htlc_maximum_msat: 200_000,
4812 fee_proportional_millionths: 0,
4813 excess_data: Vec::new()
4816 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4817 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4818 short_channel_id: 6,
4821 cltv_expiry_delta: 0,
4822 htlc_minimum_msat: 0,
4823 htlc_maximum_msat: 100_000,
4824 fee_base_msat: 1_000,
4825 fee_proportional_millionths: 0,
4826 excess_data: Vec::new()
4828 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4829 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4830 short_channel_id: 11,
4833 cltv_expiry_delta: 0,
4834 htlc_minimum_msat: 0,
4835 htlc_maximum_msat: 100_000,
4837 fee_proportional_millionths: 0,
4838 excess_data: Vec::new()
4841 // Path via {node7, node2} is channels {12, 13, 5}.
4842 // We already limited them to 200 sats (they are used twice for 100 sats).
4843 // Nothing to do here.
4846 // Now, attempt to route 180 sats.
4847 // Our algorithm should provide us with these 2 paths.
4848 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4849 assert_eq!(route.paths.len(), 2);
4851 let mut total_value_transferred_msat = 0;
4852 let mut total_paid_msat = 0;
4853 for path in &route.paths {
4854 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4855 total_value_transferred_msat += path.final_value_msat();
4856 for hop in &path.hops {
4857 total_paid_msat += hop.fee_msat;
4860 // If we paid fee, this would be higher.
4861 assert_eq!(total_value_transferred_msat, 180_000);
4862 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4863 assert_eq!(total_fees_paid, 0);
4868 fn fees_on_mpp_route_test() {
4869 // This test makes sure that MPP algorithm properly takes into account
4870 // fees charged on the channels, by making the fees impactful:
4871 // if the fee is not properly accounted for, the behavior is different.
4872 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4873 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4874 let scorer = ln_test_utils::TestScorer::new();
4875 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4876 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4877 let config = UserConfig::default();
4878 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4880 // We need a route consisting of 2 paths:
4881 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4882 // We will route 200 sats, Each path will have 100 sats capacity.
4884 // This test is not particularly stable: e.g.,
4885 // there's a way to route via {node0, node2, node4}.
4886 // It works while pathfinding is deterministic, but can be broken otherwise.
4887 // It's fine to ignore this concern for now.
4889 // Disable other potential paths.
4890 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4891 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4892 short_channel_id: 2,
4895 cltv_expiry_delta: 0,
4896 htlc_minimum_msat: 0,
4897 htlc_maximum_msat: 100_000,
4899 fee_proportional_millionths: 0,
4900 excess_data: Vec::new()
4903 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4904 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4905 short_channel_id: 7,
4908 cltv_expiry_delta: 0,
4909 htlc_minimum_msat: 0,
4910 htlc_maximum_msat: 100_000,
4912 fee_proportional_millionths: 0,
4913 excess_data: Vec::new()
4916 // Path via {node0, node2} is channels {1, 3, 5}.
4917 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4918 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4919 short_channel_id: 1,
4922 cltv_expiry_delta: 0,
4923 htlc_minimum_msat: 0,
4924 htlc_maximum_msat: 100_000,
4926 fee_proportional_millionths: 0,
4927 excess_data: Vec::new()
4929 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4930 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4931 short_channel_id: 3,
4934 cltv_expiry_delta: 0,
4935 htlc_minimum_msat: 0,
4936 htlc_maximum_msat: 100_000,
4938 fee_proportional_millionths: 0,
4939 excess_data: Vec::new()
4942 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4943 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4944 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4945 short_channel_id: 5,
4948 cltv_expiry_delta: 0,
4949 htlc_minimum_msat: 0,
4950 htlc_maximum_msat: 100_000,
4952 fee_proportional_millionths: 0,
4953 excess_data: Vec::new()
4956 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4957 // All channels should be 100 sats capacity. But for the fee experiment,
4958 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4959 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4960 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4961 // so no matter how large are other channels,
4962 // the whole path will be limited by 100 sats with just these 2 conditions:
4963 // - channel 12 capacity is 250 sats
4964 // - fee for channel 6 is 150 sats
4965 // Let's test this by enforcing these 2 conditions and removing other limits.
4966 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4967 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4968 short_channel_id: 12,
4971 cltv_expiry_delta: 0,
4972 htlc_minimum_msat: 0,
4973 htlc_maximum_msat: 250_000,
4975 fee_proportional_millionths: 0,
4976 excess_data: Vec::new()
4978 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4979 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4980 short_channel_id: 13,
4983 cltv_expiry_delta: 0,
4984 htlc_minimum_msat: 0,
4985 htlc_maximum_msat: MAX_VALUE_MSAT,
4987 fee_proportional_millionths: 0,
4988 excess_data: Vec::new()
4991 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4992 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4993 short_channel_id: 6,
4996 cltv_expiry_delta: 0,
4997 htlc_minimum_msat: 0,
4998 htlc_maximum_msat: MAX_VALUE_MSAT,
4999 fee_base_msat: 150_000,
5000 fee_proportional_millionths: 0,
5001 excess_data: Vec::new()
5003 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5004 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5005 short_channel_id: 11,
5008 cltv_expiry_delta: 0,
5009 htlc_minimum_msat: 0,
5010 htlc_maximum_msat: MAX_VALUE_MSAT,
5012 fee_proportional_millionths: 0,
5013 excess_data: Vec::new()
5017 // Attempt to route more than available results in a failure.
5018 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5019 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5020 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5021 } else { panic!(); }
5025 // Now, attempt to route 200 sats (exact amount we can route).
5026 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5027 assert_eq!(route.paths.len(), 2);
5029 let mut total_amount_paid_msat = 0;
5030 for path in &route.paths {
5031 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5032 total_amount_paid_msat += path.final_value_msat();
5034 assert_eq!(total_amount_paid_msat, 200_000);
5035 assert_eq!(route.get_total_fees(), 150_000);
5040 fn mpp_with_last_hops() {
5041 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5042 // via a single last-hop route hint, we'd fail to route if we first collected routes
5043 // totaling close but not quite enough to fund the full payment.
5045 // This was because we considered last-hop hints to have exactly the sought payment amount
5046 // instead of the amount we were trying to collect, needlessly limiting our path searching
5047 // at the very first hop.
5049 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5050 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5051 // to only have the remaining to-collect amount in available liquidity.
5053 // This bug appeared in production in some specific channel configurations.
5054 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5055 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5056 let scorer = ln_test_utils::TestScorer::new();
5057 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5058 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5059 let config = UserConfig::default();
5060 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5061 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5062 src_node_id: nodes[2],
5063 short_channel_id: 42,
5064 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5065 cltv_expiry_delta: 42,
5066 htlc_minimum_msat: None,
5067 htlc_maximum_msat: None,
5068 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5070 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5071 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5072 // would first use the no-fee route and then fail to find a path along the second route as
5073 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5074 // under 5% of our payment amount.
5075 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5076 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5077 short_channel_id: 1,
5080 cltv_expiry_delta: (5 << 4) | 5,
5081 htlc_minimum_msat: 0,
5082 htlc_maximum_msat: 99_000,
5083 fee_base_msat: u32::max_value(),
5084 fee_proportional_millionths: u32::max_value(),
5085 excess_data: Vec::new()
5087 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5088 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5089 short_channel_id: 2,
5092 cltv_expiry_delta: (5 << 4) | 3,
5093 htlc_minimum_msat: 0,
5094 htlc_maximum_msat: 99_000,
5095 fee_base_msat: u32::max_value(),
5096 fee_proportional_millionths: u32::max_value(),
5097 excess_data: Vec::new()
5099 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5100 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5101 short_channel_id: 4,
5104 cltv_expiry_delta: (4 << 4) | 1,
5105 htlc_minimum_msat: 0,
5106 htlc_maximum_msat: MAX_VALUE_MSAT,
5108 fee_proportional_millionths: 0,
5109 excess_data: Vec::new()
5111 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5112 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5113 short_channel_id: 13,
5115 flags: 0|2, // Channel disabled
5116 cltv_expiry_delta: (13 << 4) | 1,
5117 htlc_minimum_msat: 0,
5118 htlc_maximum_msat: MAX_VALUE_MSAT,
5120 fee_proportional_millionths: 2000000,
5121 excess_data: Vec::new()
5124 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5126 let mut route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5127 assert_eq!(route.paths.len(), 2);
5128 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5129 // Paths are manually ordered ordered by SCID, so:
5130 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5131 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5132 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5133 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5134 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5135 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5136 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5137 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5138 assert_eq!(route.get_total_fees(), 1);
5139 assert_eq!(route.get_total_amount(), 100_000);
5143 fn drop_lowest_channel_mpp_route_test() {
5144 // This test checks that low-capacity channel is dropped when after
5145 // path finding we realize that we found more capacity than we need.
5146 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5147 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5148 let scorer = ln_test_utils::TestScorer::new();
5149 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5150 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5151 let config = UserConfig::default();
5152 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5153 .with_max_channel_saturation_power_of_half(0);
5155 // We need a route consisting of 3 paths:
5156 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5158 // The first and the second paths should be sufficient, but the third should be
5159 // cheaper, so that we select it but drop later.
5161 // First, we set limits on these (previously unlimited) channels.
5162 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5164 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5165 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5166 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5167 short_channel_id: 1,
5170 cltv_expiry_delta: 0,
5171 htlc_minimum_msat: 0,
5172 htlc_maximum_msat: 100_000,
5174 fee_proportional_millionths: 0,
5175 excess_data: Vec::new()
5177 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5178 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5179 short_channel_id: 3,
5182 cltv_expiry_delta: 0,
5183 htlc_minimum_msat: 0,
5184 htlc_maximum_msat: 50_000,
5186 fee_proportional_millionths: 0,
5187 excess_data: Vec::new()
5190 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5191 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5192 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5193 short_channel_id: 12,
5196 cltv_expiry_delta: 0,
5197 htlc_minimum_msat: 0,
5198 htlc_maximum_msat: 60_000,
5200 fee_proportional_millionths: 0,
5201 excess_data: Vec::new()
5203 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5204 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5205 short_channel_id: 13,
5208 cltv_expiry_delta: 0,
5209 htlc_minimum_msat: 0,
5210 htlc_maximum_msat: 60_000,
5212 fee_proportional_millionths: 0,
5213 excess_data: Vec::new()
5216 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5217 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5218 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5219 short_channel_id: 2,
5222 cltv_expiry_delta: 0,
5223 htlc_minimum_msat: 0,
5224 htlc_maximum_msat: 20_000,
5226 fee_proportional_millionths: 0,
5227 excess_data: Vec::new()
5229 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5230 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5231 short_channel_id: 4,
5234 cltv_expiry_delta: 0,
5235 htlc_minimum_msat: 0,
5236 htlc_maximum_msat: 20_000,
5238 fee_proportional_millionths: 0,
5239 excess_data: Vec::new()
5243 // Attempt to route more than available results in a failure.
5244 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5245 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5246 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5247 } else { panic!(); }
5251 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5252 // Our algorithm should provide us with these 3 paths.
5253 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5254 assert_eq!(route.paths.len(), 3);
5255 let mut total_amount_paid_msat = 0;
5256 for path in &route.paths {
5257 assert_eq!(path.hops.len(), 2);
5258 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5259 total_amount_paid_msat += path.final_value_msat();
5261 assert_eq!(total_amount_paid_msat, 125_000);
5265 // Attempt to route without the last small cheap channel
5266 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5267 assert_eq!(route.paths.len(), 2);
5268 let mut total_amount_paid_msat = 0;
5269 for path in &route.paths {
5270 assert_eq!(path.hops.len(), 2);
5271 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5272 total_amount_paid_msat += path.final_value_msat();
5274 assert_eq!(total_amount_paid_msat, 90_000);
5279 fn min_criteria_consistency() {
5280 // Test that we don't use an inconsistent metric between updating and walking nodes during
5281 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5282 // was updated with a different criterion from the heap sorting, resulting in loops in
5283 // calculated paths. We test for that specific case here.
5285 // We construct a network that looks like this:
5287 // node2 -1(3)2- node3
5291 // node1 -1(5)2- node4 -1(1)2- node6
5297 // We create a loop on the side of our real path - our destination is node 6, with a
5298 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5299 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5300 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5301 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5302 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5303 // "previous hop" being set to node 3, creating a loop in the path.
5304 let secp_ctx = Secp256k1::new();
5305 let logger = Arc::new(ln_test_utils::TestLogger::new());
5306 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5307 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5308 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5309 let scorer = ln_test_utils::TestScorer::new();
5310 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5311 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5312 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5314 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5315 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5316 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5317 short_channel_id: 6,
5320 cltv_expiry_delta: (6 << 4) | 0,
5321 htlc_minimum_msat: 0,
5322 htlc_maximum_msat: MAX_VALUE_MSAT,
5324 fee_proportional_millionths: 0,
5325 excess_data: Vec::new()
5327 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5329 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5330 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5331 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5332 short_channel_id: 5,
5335 cltv_expiry_delta: (5 << 4) | 0,
5336 htlc_minimum_msat: 0,
5337 htlc_maximum_msat: MAX_VALUE_MSAT,
5339 fee_proportional_millionths: 0,
5340 excess_data: Vec::new()
5342 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5344 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5345 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5346 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5347 short_channel_id: 4,
5350 cltv_expiry_delta: (4 << 4) | 0,
5351 htlc_minimum_msat: 0,
5352 htlc_maximum_msat: MAX_VALUE_MSAT,
5354 fee_proportional_millionths: 0,
5355 excess_data: Vec::new()
5357 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5359 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5360 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5361 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5362 short_channel_id: 3,
5365 cltv_expiry_delta: (3 << 4) | 0,
5366 htlc_minimum_msat: 0,
5367 htlc_maximum_msat: MAX_VALUE_MSAT,
5369 fee_proportional_millionths: 0,
5370 excess_data: Vec::new()
5372 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5374 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5375 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5376 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5377 short_channel_id: 2,
5380 cltv_expiry_delta: (2 << 4) | 0,
5381 htlc_minimum_msat: 0,
5382 htlc_maximum_msat: MAX_VALUE_MSAT,
5384 fee_proportional_millionths: 0,
5385 excess_data: Vec::new()
5388 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5389 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5390 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5391 short_channel_id: 1,
5394 cltv_expiry_delta: (1 << 4) | 0,
5395 htlc_minimum_msat: 100,
5396 htlc_maximum_msat: MAX_VALUE_MSAT,
5398 fee_proportional_millionths: 0,
5399 excess_data: Vec::new()
5401 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5404 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5405 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5406 assert_eq!(route.paths.len(), 1);
5407 assert_eq!(route.paths[0].hops.len(), 3);
5409 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5410 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5411 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5412 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5413 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5414 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5416 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5417 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5418 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5419 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5420 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5421 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5423 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5424 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5425 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5426 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5427 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5428 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5434 fn exact_fee_liquidity_limit() {
5435 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5436 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5437 // we calculated fees on a higher value, resulting in us ignoring such paths.
5438 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5439 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5440 let scorer = ln_test_utils::TestScorer::new();
5441 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5442 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5443 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5445 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5447 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5448 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5449 short_channel_id: 2,
5452 cltv_expiry_delta: 0,
5453 htlc_minimum_msat: 0,
5454 htlc_maximum_msat: 85_000,
5456 fee_proportional_millionths: 0,
5457 excess_data: Vec::new()
5460 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5461 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5462 short_channel_id: 12,
5465 cltv_expiry_delta: (4 << 4) | 1,
5466 htlc_minimum_msat: 0,
5467 htlc_maximum_msat: 270_000,
5469 fee_proportional_millionths: 1000000,
5470 excess_data: Vec::new()
5474 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5475 // 200% fee charged channel 13 in the 1-to-2 direction.
5476 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5477 assert_eq!(route.paths.len(), 1);
5478 assert_eq!(route.paths[0].hops.len(), 2);
5480 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5481 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5482 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5483 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5484 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5485 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5487 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5488 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5489 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5490 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5491 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5492 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5497 fn htlc_max_reduction_below_min() {
5498 // Test that if, while walking the graph, we reduce the value being sent to meet an
5499 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5500 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5501 // resulting in us thinking there is no possible path, even if other paths exist.
5502 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5503 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5504 let scorer = ln_test_utils::TestScorer::new();
5505 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5506 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5507 let config = UserConfig::default();
5508 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5510 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5511 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5512 // then try to send 90_000.
5513 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5514 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5515 short_channel_id: 2,
5518 cltv_expiry_delta: 0,
5519 htlc_minimum_msat: 0,
5520 htlc_maximum_msat: 80_000,
5522 fee_proportional_millionths: 0,
5523 excess_data: Vec::new()
5525 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5526 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5527 short_channel_id: 4,
5530 cltv_expiry_delta: (4 << 4) | 1,
5531 htlc_minimum_msat: 90_000,
5532 htlc_maximum_msat: MAX_VALUE_MSAT,
5534 fee_proportional_millionths: 0,
5535 excess_data: Vec::new()
5539 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5540 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5541 // expensive) channels 12-13 path.
5542 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5543 assert_eq!(route.paths.len(), 1);
5544 assert_eq!(route.paths[0].hops.len(), 2);
5546 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5547 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5548 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5549 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5550 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5551 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5553 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5554 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5555 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5556 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5557 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5558 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5563 fn multiple_direct_first_hops() {
5564 // Previously we'd only ever considered one first hop path per counterparty.
5565 // However, as we don't restrict users to one channel per peer, we really need to support
5566 // looking at all first hop paths.
5567 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5568 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5569 // route over multiple channels with the same first hop.
5570 let secp_ctx = Secp256k1::new();
5571 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5572 let logger = Arc::new(ln_test_utils::TestLogger::new());
5573 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5574 let scorer = ln_test_utils::TestScorer::new();
5575 let config = UserConfig::default();
5576 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5577 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5578 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5581 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5582 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5583 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5584 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5585 assert_eq!(route.paths.len(), 1);
5586 assert_eq!(route.paths[0].hops.len(), 1);
5588 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5589 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5590 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5593 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5594 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5595 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5596 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5597 assert_eq!(route.paths.len(), 2);
5598 assert_eq!(route.paths[0].hops.len(), 1);
5599 assert_eq!(route.paths[1].hops.len(), 1);
5601 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5602 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5604 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5605 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5607 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5608 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5612 // If we have a bunch of outbound channels to the same node, where most are not
5613 // sufficient to pay the full payment, but one is, we should default to just using the
5614 // one single channel that has sufficient balance, avoiding MPP.
5616 // If we have several options above the 3xpayment value threshold, we should pick the
5617 // smallest of them, avoiding further fragmenting our available outbound balance to
5619 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5620 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5621 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5622 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5623 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5624 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5625 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5626 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5627 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5628 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5629 assert_eq!(route.paths.len(), 1);
5630 assert_eq!(route.paths[0].hops.len(), 1);
5632 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5633 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5634 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5639 fn prefers_shorter_route_with_higher_fees() {
5640 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5641 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5642 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5644 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5645 let scorer = ln_test_utils::TestScorer::new();
5646 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5647 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5648 let route = get_route(
5649 &our_id, &payment_params, &network_graph.read_only(), None, 100,
5650 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5652 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5654 assert_eq!(route.get_total_fees(), 100);
5655 assert_eq!(route.get_total_amount(), 100);
5656 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5658 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5659 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5660 let scorer = FixedPenaltyScorer::with_penalty(100);
5661 let route = get_route(
5662 &our_id, &payment_params, &network_graph.read_only(), None, 100,
5663 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5665 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5667 assert_eq!(route.get_total_fees(), 300);
5668 assert_eq!(route.get_total_amount(), 100);
5669 assert_eq!(path, vec![2, 4, 7, 10]);
5672 struct BadChannelScorer {
5673 short_channel_id: u64,
5677 impl Writeable for BadChannelScorer {
5678 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5680 impl Score for BadChannelScorer {
5681 type ScoreParams = ();
5682 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5683 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5686 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5687 fn payment_path_successful(&mut self, _path: &Path) {}
5688 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5689 fn probe_successful(&mut self, _path: &Path) {}
5692 struct BadNodeScorer {
5697 impl Writeable for BadNodeScorer {
5698 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5701 impl Score for BadNodeScorer {
5702 type ScoreParams = ();
5703 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5704 if *target == self.node_id { u64::max_value() } else { 0 }
5707 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5708 fn payment_path_successful(&mut self, _path: &Path) {}
5709 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5710 fn probe_successful(&mut self, _path: &Path) {}
5714 fn avoids_routing_through_bad_channels_and_nodes() {
5715 let (secp_ctx, network, _, _, logger) = build_graph();
5716 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5717 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5718 let network_graph = network.read_only();
5720 // A path to nodes[6] exists when no penalties are applied to any channel.
5721 let scorer = ln_test_utils::TestScorer::new();
5722 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5723 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5724 let route = get_route(
5725 &our_id, &payment_params, &network_graph, None, 100,
5726 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5728 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5730 assert_eq!(route.get_total_fees(), 100);
5731 assert_eq!(route.get_total_amount(), 100);
5732 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5734 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5735 let scorer = BadChannelScorer { short_channel_id: 6 };
5736 let route = get_route(
5737 &our_id, &payment_params, &network_graph, None, 100,
5738 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5740 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5742 assert_eq!(route.get_total_fees(), 300);
5743 assert_eq!(route.get_total_amount(), 100);
5744 assert_eq!(path, vec![2, 4, 7, 10]);
5746 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5747 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5749 &our_id, &payment_params, &network_graph, None, 100,
5750 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5752 Err(LightningError { err, .. } ) => {
5753 assert_eq!(err, "Failed to find a path to the given destination");
5755 Ok(_) => panic!("Expected error"),
5760 fn total_fees_single_path() {
5762 paths: vec![Path { hops: vec![
5764 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5765 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5766 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5769 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5770 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5771 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5774 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5775 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5776 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5778 ], blinded_tail: None }],
5779 payment_params: None,
5782 assert_eq!(route.get_total_fees(), 250);
5783 assert_eq!(route.get_total_amount(), 225);
5787 fn total_fees_multi_path() {
5789 paths: vec![Path { hops: vec![
5791 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5792 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5793 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5796 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5797 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5798 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5800 ], blinded_tail: None }, Path { hops: vec![
5802 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5803 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5804 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5807 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5808 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5809 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5811 ], blinded_tail: None }],
5812 payment_params: None,
5815 assert_eq!(route.get_total_fees(), 200);
5816 assert_eq!(route.get_total_amount(), 300);
5820 fn total_empty_route_no_panic() {
5821 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5822 // would both panic if the route was completely empty. We test to ensure they return 0
5823 // here, even though its somewhat nonsensical as a route.
5824 let route = Route { paths: Vec::new(), payment_params: None };
5826 assert_eq!(route.get_total_fees(), 0);
5827 assert_eq!(route.get_total_amount(), 0);
5831 fn limits_total_cltv_delta() {
5832 let (secp_ctx, network, _, _, logger) = build_graph();
5833 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5834 let network_graph = network.read_only();
5836 let scorer = ln_test_utils::TestScorer::new();
5838 // Make sure that generally there is at least one route available
5839 let feasible_max_total_cltv_delta = 1008;
5840 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5841 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5842 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5843 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5844 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5845 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5846 assert_ne!(path.len(), 0);
5848 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5849 let fail_max_total_cltv_delta = 23;
5850 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5851 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5852 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5854 Err(LightningError { err, .. } ) => {
5855 assert_eq!(err, "Failed to find a path to the given destination");
5857 Ok(_) => panic!("Expected error"),
5862 fn avoids_recently_failed_paths() {
5863 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5864 // randomly inserting channels into it until we can't find a route anymore.
5865 let (secp_ctx, network, _, _, logger) = build_graph();
5866 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5867 let network_graph = network.read_only();
5869 let scorer = ln_test_utils::TestScorer::new();
5870 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5871 .with_max_path_count(1);
5872 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5873 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5875 // We should be able to find a route initially, and then after we fail a few random
5876 // channels eventually we won't be able to any longer.
5877 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).is_ok());
5879 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5880 for chan in route.paths[0].hops.iter() {
5881 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5883 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5884 % route.paths[0].hops.len();
5885 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
5891 fn limits_path_length() {
5892 let (secp_ctx, network, _, _, logger) = build_line_graph();
5893 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5894 let network_graph = network.read_only();
5896 let scorer = ln_test_utils::TestScorer::new();
5897 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5898 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5900 // First check we can actually create a long route on this graph.
5901 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
5902 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100,
5903 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5904 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5905 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5907 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5908 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
5909 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100,
5910 Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5912 Err(LightningError { err, .. } ) => {
5913 assert_eq!(err, "Failed to find a path to the given destination");
5915 Ok(_) => panic!("Expected error"),
5920 fn adds_and_limits_cltv_offset() {
5921 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5922 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5924 let scorer = ln_test_utils::TestScorer::new();
5926 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5927 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5928 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5929 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5930 assert_eq!(route.paths.len(), 1);
5932 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5934 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5935 let mut route_default = route.clone();
5936 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5937 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5938 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5939 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5940 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5942 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5943 let mut route_limited = route.clone();
5944 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5945 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5946 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5947 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5948 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5952 fn adds_plausible_cltv_offset() {
5953 let (secp_ctx, network, _, _, logger) = build_graph();
5954 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5955 let network_graph = network.read_only();
5956 let network_nodes = network_graph.nodes();
5957 let network_channels = network_graph.channels();
5958 let scorer = ln_test_utils::TestScorer::new();
5959 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5960 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5961 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5963 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100,
5964 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5965 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5967 let mut path_plausibility = vec![];
5969 for p in route.paths {
5970 // 1. Select random observation point
5971 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5972 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5974 prng.process_in_place(&mut random_bytes);
5975 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
5976 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
5978 // 2. Calculate what CLTV expiry delta we would observe there
5979 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5981 // 3. Starting from the observation point, find candidate paths
5982 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5983 candidates.push_back((observation_point, vec![]));
5985 let mut found_plausible_candidate = false;
5987 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5988 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5989 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5990 found_plausible_candidate = true;
5991 break 'candidate_loop;
5995 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5996 for channel_id in &cur_node.channels {
5997 if let Some(channel_info) = network_channels.get(&channel_id) {
5998 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5999 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6000 if cur_path_cltv_deltas.iter().sum::<u32>()
6001 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6002 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6003 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6004 candidates.push_back((*next_id, new_path_cltv_deltas));
6012 path_plausibility.push(found_plausible_candidate);
6014 assert!(path_plausibility.iter().all(|x| *x));
6018 fn builds_correct_path_from_hops() {
6019 let (secp_ctx, network, _, _, logger) = build_graph();
6020 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6021 let network_graph = network.read_only();
6023 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6024 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6026 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6027 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6028 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
6029 &network_graph, 100, Arc::clone(&logger), &random_seed_bytes).unwrap();
6030 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6031 assert_eq!(hops.len(), route.paths[0].hops.len());
6032 for (idx, hop_pubkey) in hops.iter().enumerate() {
6033 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6038 fn avoids_saturating_channels() {
6039 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6040 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6041 let decay_params = ProbabilisticScoringDecayParameters::default();
6042 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6044 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6045 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6046 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6047 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6048 short_channel_id: 4,
6051 cltv_expiry_delta: (4 << 4) | 1,
6052 htlc_minimum_msat: 0,
6053 htlc_maximum_msat: 250_000_000,
6055 fee_proportional_millionths: 0,
6056 excess_data: Vec::new()
6058 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6059 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6060 short_channel_id: 13,
6063 cltv_expiry_delta: (13 << 4) | 1,
6064 htlc_minimum_msat: 0,
6065 htlc_maximum_msat: 250_000_000,
6067 fee_proportional_millionths: 0,
6068 excess_data: Vec::new()
6071 let config = UserConfig::default();
6072 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6073 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6074 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6075 // 100,000 sats is less than the available liquidity on each channel, set above.
6076 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();
6077 assert_eq!(route.paths.len(), 2);
6078 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6079 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6082 #[cfg(not(feature = "no-std"))]
6083 pub(super) fn random_init_seed() -> u64 {
6084 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6085 use core::hash::{BuildHasher, Hasher};
6086 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6087 println!("Using seed of {}", seed);
6092 #[cfg(not(feature = "no-std"))]
6093 fn generate_routes() {
6094 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6096 let logger = ln_test_utils::TestLogger::new();
6097 let graph = match super::bench_utils::read_network_graph(&logger) {
6105 let params = ProbabilisticScoringFeeParameters::default();
6106 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6107 let features = super::InvoiceFeatures::empty();
6109 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6113 #[cfg(not(feature = "no-std"))]
6114 fn generate_routes_mpp() {
6115 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6117 let logger = ln_test_utils::TestLogger::new();
6118 let graph = match super::bench_utils::read_network_graph(&logger) {
6126 let params = ProbabilisticScoringFeeParameters::default();
6127 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6128 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6130 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6134 #[cfg(not(feature = "no-std"))]
6135 fn generate_large_mpp_routes() {
6136 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6138 let logger = ln_test_utils::TestLogger::new();
6139 let graph = match super::bench_utils::read_network_graph(&logger) {
6147 let params = ProbabilisticScoringFeeParameters::default();
6148 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6149 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6151 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6155 fn honors_manual_penalties() {
6156 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6157 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6159 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6160 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6162 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6163 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6165 // First check set manual penalties are returned by the scorer.
6166 let usage = ChannelUsage {
6168 inflight_htlc_msat: 0,
6169 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6171 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6172 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6173 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
6175 // Then check we can get a normal route
6176 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6177 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6178 assert!(route.is_ok());
6180 // Then check that we can't get a route if we ban an intermediate node.
6181 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6182 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6183 assert!(route.is_err());
6185 // Finally make sure we can route again, when we remove the ban.
6186 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6187 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6188 assert!(route.is_ok());
6192 fn abide_by_route_hint_max_htlc() {
6193 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6194 // params in the final route.
6195 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6196 let netgraph = network_graph.read_only();
6197 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6198 let scorer = ln_test_utils::TestScorer::new();
6199 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6200 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6201 let config = UserConfig::default();
6203 let max_htlc_msat = 50_000;
6204 let route_hint_1 = RouteHint(vec![RouteHintHop {
6205 src_node_id: nodes[2],
6206 short_channel_id: 42,
6209 proportional_millionths: 0,
6211 cltv_expiry_delta: 10,
6212 htlc_minimum_msat: None,
6213 htlc_maximum_msat: Some(max_htlc_msat),
6215 let dest_node_id = ln_test_utils::pubkey(42);
6216 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6217 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6218 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6220 // Make sure we'll error if our route hints don't have enough liquidity according to their
6221 // htlc_maximum_msat.
6222 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6223 &payment_params, &netgraph, None, max_htlc_msat + 1, Arc::clone(&logger), &scorer, &(),
6226 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6227 } else { panic!(); }
6229 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6230 let mut route_hint_2 = route_hint_1.clone();
6231 route_hint_2.0[0].short_channel_id = 43;
6232 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6233 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6234 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6235 let route = get_route(&our_id, &payment_params, &netgraph, None, max_htlc_msat + 1,
6236 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6237 assert_eq!(route.paths.len(), 2);
6238 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6239 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6243 fn direct_channel_to_hints_with_max_htlc() {
6244 // Check that if we have a first hop channel peer that's connected to multiple provided route
6245 // hints, that we properly split the payment between the route hints if needed.
6246 let logger = Arc::new(ln_test_utils::TestLogger::new());
6247 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6248 let scorer = ln_test_utils::TestScorer::new();
6249 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6250 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6251 let config = UserConfig::default();
6253 let our_node_id = ln_test_utils::pubkey(42);
6254 let intermed_node_id = ln_test_utils::pubkey(43);
6255 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6257 let amt_msat = 900_000;
6258 let max_htlc_msat = 500_000;
6259 let route_hint_1 = RouteHint(vec![RouteHintHop {
6260 src_node_id: intermed_node_id,
6261 short_channel_id: 44,
6264 proportional_millionths: 0,
6266 cltv_expiry_delta: 10,
6267 htlc_minimum_msat: None,
6268 htlc_maximum_msat: Some(max_htlc_msat),
6270 src_node_id: intermed_node_id,
6271 short_channel_id: 45,
6274 proportional_millionths: 0,
6276 cltv_expiry_delta: 10,
6277 htlc_minimum_msat: None,
6278 // Check that later route hint max htlcs don't override earlier ones
6279 htlc_maximum_msat: Some(max_htlc_msat - 50),
6281 let mut route_hint_2 = route_hint_1.clone();
6282 route_hint_2.0[0].short_channel_id = 46;
6283 route_hint_2.0[1].short_channel_id = 47;
6284 let dest_node_id = ln_test_utils::pubkey(44);
6285 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6286 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6287 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6289 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6290 Some(&first_hop.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6291 &random_seed_bytes).unwrap();
6292 assert_eq!(route.paths.len(), 2);
6293 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6294 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6295 assert_eq!(route.get_total_amount(), amt_msat);
6297 // Re-run but with two first hop channels connected to the same route hint peers that must be
6299 let first_hops = vec![
6300 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6301 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6303 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6304 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6305 &random_seed_bytes).unwrap();
6306 assert_eq!(route.paths.len(), 2);
6307 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6308 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6309 assert_eq!(route.get_total_amount(), amt_msat);
6311 // Make sure this works for blinded route hints.
6312 let blinded_path = BlindedPath {
6313 introduction_node_id: intermed_node_id,
6314 blinding_point: ln_test_utils::pubkey(42),
6316 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6317 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6320 let blinded_payinfo = BlindedPayInfo {
6322 fee_proportional_millionths: 0,
6323 htlc_minimum_msat: 1,
6324 htlc_maximum_msat: max_htlc_msat,
6325 cltv_expiry_delta: 10,
6326 features: BlindedHopFeatures::empty(),
6328 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6329 let payment_params = PaymentParameters::blinded(vec![
6330 (blinded_payinfo.clone(), blinded_path.clone()),
6331 (blinded_payinfo.clone(), blinded_path.clone())])
6332 .with_bolt12_features(bolt12_features).unwrap();
6333 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6334 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6335 &random_seed_bytes).unwrap();
6336 assert_eq!(route.paths.len(), 2);
6337 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6338 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6339 assert_eq!(route.get_total_amount(), amt_msat);
6343 fn blinded_route_ser() {
6344 let blinded_path_1 = BlindedPath {
6345 introduction_node_id: ln_test_utils::pubkey(42),
6346 blinding_point: ln_test_utils::pubkey(43),
6348 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6349 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6352 let blinded_path_2 = BlindedPath {
6353 introduction_node_id: ln_test_utils::pubkey(46),
6354 blinding_point: ln_test_utils::pubkey(47),
6356 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6357 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6360 // (De)serialize a Route with 1 blinded path out of two total paths.
6361 let mut route = Route { paths: vec![Path {
6362 hops: vec![RouteHop {
6363 pubkey: ln_test_utils::pubkey(50),
6364 node_features: NodeFeatures::empty(),
6365 short_channel_id: 42,
6366 channel_features: ChannelFeatures::empty(),
6368 cltv_expiry_delta: 0,
6370 blinded_tail: Some(BlindedTail {
6371 hops: blinded_path_1.blinded_hops,
6372 blinding_point: blinded_path_1.blinding_point,
6373 excess_final_cltv_expiry_delta: 40,
6374 final_value_msat: 100,
6376 hops: vec![RouteHop {
6377 pubkey: ln_test_utils::pubkey(51),
6378 node_features: NodeFeatures::empty(),
6379 short_channel_id: 43,
6380 channel_features: ChannelFeatures::empty(),
6382 cltv_expiry_delta: 0,
6383 }], blinded_tail: None }],
6384 payment_params: None,
6386 let encoded_route = route.encode();
6387 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6388 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6389 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6391 // (De)serialize a Route with two paths, each containing a blinded tail.
6392 route.paths[1].blinded_tail = Some(BlindedTail {
6393 hops: blinded_path_2.blinded_hops,
6394 blinding_point: blinded_path_2.blinding_point,
6395 excess_final_cltv_expiry_delta: 41,
6396 final_value_msat: 101,
6398 let encoded_route = route.encode();
6399 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6400 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6401 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6405 fn blinded_path_inflight_processing() {
6406 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6407 // account for the blinded tail's final amount_msat.
6408 let mut inflight_htlcs = InFlightHtlcs::new();
6409 let blinded_path = BlindedPath {
6410 introduction_node_id: ln_test_utils::pubkey(43),
6411 blinding_point: ln_test_utils::pubkey(48),
6412 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
6415 hops: vec![RouteHop {
6416 pubkey: ln_test_utils::pubkey(42),
6417 node_features: NodeFeatures::empty(),
6418 short_channel_id: 42,
6419 channel_features: ChannelFeatures::empty(),
6421 cltv_expiry_delta: 0,
6424 pubkey: blinded_path.introduction_node_id,
6425 node_features: NodeFeatures::empty(),
6426 short_channel_id: 43,
6427 channel_features: ChannelFeatures::empty(),
6429 cltv_expiry_delta: 0,
6431 blinded_tail: Some(BlindedTail {
6432 hops: blinded_path.blinded_hops,
6433 blinding_point: blinded_path.blinding_point,
6434 excess_final_cltv_expiry_delta: 0,
6435 final_value_msat: 200,
6438 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
6439 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
6440 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
6444 fn blinded_path_cltv_shadow_offset() {
6445 // Make sure we add a shadow offset when sending to blinded paths.
6446 let blinded_path = BlindedPath {
6447 introduction_node_id: ln_test_utils::pubkey(43),
6448 blinding_point: ln_test_utils::pubkey(44),
6450 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
6451 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
6454 let mut route = Route { paths: vec![Path {
6455 hops: vec![RouteHop {
6456 pubkey: ln_test_utils::pubkey(42),
6457 node_features: NodeFeatures::empty(),
6458 short_channel_id: 42,
6459 channel_features: ChannelFeatures::empty(),
6461 cltv_expiry_delta: 0,
6464 pubkey: blinded_path.introduction_node_id,
6465 node_features: NodeFeatures::empty(),
6466 short_channel_id: 43,
6467 channel_features: ChannelFeatures::empty(),
6469 cltv_expiry_delta: 0,
6472 blinded_tail: Some(BlindedTail {
6473 hops: blinded_path.blinded_hops,
6474 blinding_point: blinded_path.blinding_point,
6475 excess_final_cltv_expiry_delta: 0,
6476 final_value_msat: 200,
6478 }], payment_params: None};
6480 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
6481 let (_, network_graph, _, _, _) = build_line_graph();
6482 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
6483 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
6484 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
6488 fn simple_blinded_route_hints() {
6489 do_simple_blinded_route_hints(1);
6490 do_simple_blinded_route_hints(2);
6491 do_simple_blinded_route_hints(3);
6494 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
6495 // Check that we can generate a route to a blinded path with the expected hops.
6496 let (secp_ctx, network, _, _, logger) = build_graph();
6497 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6498 let network_graph = network.read_only();
6500 let scorer = ln_test_utils::TestScorer::new();
6501 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6502 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6504 let mut blinded_path = BlindedPath {
6505 introduction_node_id: nodes[2],
6506 blinding_point: ln_test_utils::pubkey(42),
6507 blinded_hops: Vec::with_capacity(num_blinded_hops),
6509 for i in 0..num_blinded_hops {
6510 blinded_path.blinded_hops.push(
6511 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
6514 let blinded_payinfo = BlindedPayInfo {
6516 fee_proportional_millionths: 500,
6517 htlc_minimum_msat: 1000,
6518 htlc_maximum_msat: 100_000_000,
6519 cltv_expiry_delta: 15,
6520 features: BlindedHopFeatures::empty(),
6523 let final_amt_msat = 1001;
6524 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
6525 let route = get_route(&our_id, &payment_params, &network_graph, None, final_amt_msat , Arc::clone(&logger),
6526 &scorer, &(), &random_seed_bytes).unwrap();
6527 assert_eq!(route.paths.len(), 1);
6528 assert_eq!(route.paths[0].hops.len(), 2);
6530 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
6531 assert_eq!(tail.hops, blinded_path.blinded_hops);
6532 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
6533 assert_eq!(tail.final_value_msat, 1001);
6535 let final_hop = route.paths[0].hops.last().unwrap();
6536 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
6537 if tail.hops.len() > 1 {
6538 assert_eq!(final_hop.fee_msat,
6539 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
6540 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
6542 assert_eq!(final_hop.fee_msat, 0);
6543 assert_eq!(final_hop.cltv_expiry_delta, 0);
6548 fn blinded_path_routing_errors() {
6549 // Check that we can generate a route to a blinded path with the expected hops.
6550 let (secp_ctx, network, _, _, logger) = build_graph();
6551 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6552 let network_graph = network.read_only();
6554 let scorer = ln_test_utils::TestScorer::new();
6555 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6556 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6558 let mut invalid_blinded_path = BlindedPath {
6559 introduction_node_id: nodes[2],
6560 blinding_point: ln_test_utils::pubkey(42),
6562 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
6565 let blinded_payinfo = BlindedPayInfo {
6567 fee_proportional_millionths: 500,
6568 htlc_minimum_msat: 1000,
6569 htlc_maximum_msat: 100_000_000,
6570 cltv_expiry_delta: 15,
6571 features: BlindedHopFeatures::empty(),
6574 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
6575 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
6576 let payment_params = PaymentParameters::blinded(vec![
6577 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
6578 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
6579 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6580 &scorer, &(), &random_seed_bytes)
6582 Err(LightningError { err, .. }) => {
6583 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
6585 _ => panic!("Expected error")
6588 invalid_blinded_path.introduction_node_id = our_id;
6589 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
6590 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6591 &scorer, &(), &random_seed_bytes)
6593 Err(LightningError { err, .. }) => {
6594 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
6596 _ => panic!("Expected error")
6599 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
6600 invalid_blinded_path.blinded_hops.clear();
6601 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
6602 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6603 &scorer, &(), &random_seed_bytes)
6605 Err(LightningError { err, .. }) => {
6606 assert_eq!(err, "0-hop blinded path provided");
6608 _ => panic!("Expected error")
6613 fn matching_intro_node_paths_provided() {
6614 // Check that if multiple blinded paths with the same intro node are provided in payment
6615 // parameters, we'll return the correct paths in the resulting MPP route.
6616 let (secp_ctx, network, _, _, logger) = build_graph();
6617 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6618 let network_graph = network.read_only();
6620 let scorer = ln_test_utils::TestScorer::new();
6621 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6622 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6623 let config = UserConfig::default();
6625 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6626 let blinded_path_1 = BlindedPath {
6627 introduction_node_id: nodes[2],
6628 blinding_point: ln_test_utils::pubkey(42),
6630 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6631 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6634 let blinded_payinfo_1 = BlindedPayInfo {
6636 fee_proportional_millionths: 0,
6637 htlc_minimum_msat: 0,
6638 htlc_maximum_msat: 30_000,
6639 cltv_expiry_delta: 0,
6640 features: BlindedHopFeatures::empty(),
6643 let mut blinded_path_2 = blinded_path_1.clone();
6644 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
6645 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
6646 blinded_payinfo_2.htlc_maximum_msat = 70_000;
6648 let blinded_hints = vec![
6649 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
6650 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
6652 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
6653 .with_bolt12_features(bolt12_features.clone()).unwrap();
6655 let route = get_route(&our_id, &payment_params, &network_graph, None,
6656 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6657 assert_eq!(route.paths.len(), 2);
6658 let mut total_amount_paid_msat = 0;
6659 for path in route.paths.into_iter() {
6660 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6661 if let Some(bt) = &path.blinded_tail {
6662 assert_eq!(bt.blinding_point,
6663 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
6664 .map(|(_, bp)| bp.blinding_point).unwrap());
6665 } else { panic!(); }
6666 total_amount_paid_msat += path.final_value_msat();
6668 assert_eq!(total_amount_paid_msat, 100_000);
6672 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
6673 pub(crate) mod bench_utils {
6677 use bitcoin::hashes::Hash;
6678 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
6680 use crate::chain::transaction::OutPoint;
6681 use crate::sign::{EntropySource, KeysManager};
6682 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
6683 use crate::ln::features::InvoiceFeatures;
6684 use crate::routing::gossip::NetworkGraph;
6685 use crate::util::config::UserConfig;
6686 use crate::util::ser::ReadableArgs;
6687 use crate::util::test_utils::TestLogger;
6689 /// Tries to open a network graph file, or panics with a URL to fetch it.
6690 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
6691 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
6692 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
6693 .or_else(|_| { // Fall back to guessing based on the binary location
6694 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
6695 let mut path = std::env::current_exe().unwrap();
6696 path.pop(); // lightning-...
6698 path.pop(); // debug
6699 path.pop(); // target
6700 path.push("lightning");
6701 path.push("net_graph-2023-01-18.bin");
6704 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
6705 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
6706 let mut path = std::env::current_exe().unwrap();
6707 path.pop(); // bench...
6709 path.pop(); // debug
6710 path.pop(); // target
6711 path.pop(); // bench
6712 path.push("lightning");
6713 path.push("net_graph-2023-01-18.bin");
6716 .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");
6717 #[cfg(require_route_graph_test)]
6718 return Ok(res.unwrap());
6719 #[cfg(not(require_route_graph_test))]
6723 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
6724 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
6727 pub(crate) fn payer_pubkey() -> PublicKey {
6728 let secp_ctx = Secp256k1::new();
6729 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
6733 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
6735 channel_id: [0; 32],
6736 counterparty: ChannelCounterparty {
6737 features: channelmanager::provided_init_features(&UserConfig::default()),
6739 unspendable_punishment_reserve: 0,
6740 forwarding_info: None,
6741 outbound_htlc_minimum_msat: None,
6742 outbound_htlc_maximum_msat: None,
6744 funding_txo: Some(OutPoint {
6745 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
6748 short_channel_id: Some(1),
6749 inbound_scid_alias: None,
6750 outbound_scid_alias: None,
6751 channel_value_satoshis: 10_000_000_000,
6753 balance_msat: 10_000_000_000,
6754 outbound_capacity_msat: 10_000_000_000,
6755 next_outbound_htlc_minimum_msat: 0,
6756 next_outbound_htlc_limit_msat: 10_000_000_000,
6757 inbound_capacity_msat: 0,
6758 unspendable_punishment_reserve: None,
6759 confirmations_required: None,
6760 confirmations: None,
6761 force_close_spend_delay: None,
6763 is_channel_ready: true,
6766 inbound_htlc_minimum_msat: None,
6767 inbound_htlc_maximum_msat: None,
6769 feerate_sat_per_1000_weight: None,
6770 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
6774 pub(crate) fn generate_test_routes<S: Score>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
6775 score_params: &S::ScoreParams, features: InvoiceFeatures, mut seed: u64,
6776 starting_amount: u64, route_count: usize,
6777 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
6778 let payer = payer_pubkey();
6779 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
6780 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6782 let nodes = graph.read_only().nodes().clone();
6783 let mut route_endpoints = Vec::new();
6784 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
6785 // with some routes we picked being un-routable.
6786 for _ in 0..route_count * 3 / 2 {
6788 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6789 let src = PublicKey::from_slice(nodes.unordered_keys()
6790 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6791 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6792 let dst = PublicKey::from_slice(nodes.unordered_keys()
6793 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6794 let params = PaymentParameters::from_node_id(dst, 42)
6795 .with_bolt11_features(features.clone()).unwrap();
6796 let first_hop = first_hop(src);
6797 let amt = starting_amount + seed % 1_000_000;
6799 get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]),
6800 amt, &TestLogger::new(), &scorer, score_params, &random_seed_bytes).is_ok();
6802 // ...and seed the scorer with success and failure data...
6803 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6804 let mut score_amt = seed % 1_000_000_000;
6806 // Generate fail/success paths for a wider range of potential amounts with
6807 // MPP enabled to give us a chance to apply penalties for more potential
6809 let mpp_features = channelmanager::provided_invoice_features(&UserConfig::default());
6810 let params = PaymentParameters::from_node_id(dst, 42)
6811 .with_bolt11_features(mpp_features).unwrap();
6813 let route_res = get_route(&payer, ¶ms, &graph.read_only(),
6814 Some(&[&first_hop]), score_amt, &TestLogger::new(), &scorer,
6815 score_params, &random_seed_bytes);
6816 if let Ok(route) = route_res {
6817 for path in route.paths {
6818 if seed & 0x80 == 0 {
6819 scorer.payment_path_successful(&path);
6821 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
6822 scorer.payment_path_failed(&path, short_channel_id);
6824 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6828 // If we couldn't find a path with a higer amount, reduce and try again.
6832 route_endpoints.push((first_hop, params, amt));
6838 // Because we've changed channel scores, it's possible we'll take different routes to the
6839 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
6840 // requires a too-high CLTV delta.
6841 route_endpoints.retain(|(first_hop, params, amt)| {
6842 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
6843 &TestLogger::new(), &scorer, score_params, &random_seed_bytes).is_ok()
6845 route_endpoints.truncate(route_count);
6846 assert_eq!(route_endpoints.len(), route_count);
6854 use crate::sign::{EntropySource, KeysManager};
6855 use crate::ln::channelmanager;
6856 use crate::ln::features::InvoiceFeatures;
6857 use crate::routing::gossip::NetworkGraph;
6858 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
6859 use crate::util::config::UserConfig;
6860 use crate::util::logger::{Logger, Record};
6861 use crate::util::test_utils::TestLogger;
6863 use criterion::Criterion;
6865 struct DummyLogger {}
6866 impl Logger for DummyLogger {
6867 fn log(&self, _record: &Record) {}
6870 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
6871 let logger = TestLogger::new();
6872 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6873 let scorer = FixedPenaltyScorer::with_penalty(0);
6874 generate_routes(bench, &network_graph, scorer, &(), InvoiceFeatures::empty(), 0,
6875 "generate_routes_with_zero_penalty_scorer");
6878 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
6879 let logger = TestLogger::new();
6880 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6881 let scorer = FixedPenaltyScorer::with_penalty(0);
6882 generate_routes(bench, &network_graph, scorer, &(),
6883 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
6884 "generate_mpp_routes_with_zero_penalty_scorer");
6887 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6888 let logger = TestLogger::new();
6889 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6890 let params = ProbabilisticScoringFeeParameters::default();
6891 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6892 generate_routes(bench, &network_graph, scorer, ¶ms, InvoiceFeatures::empty(), 0,
6893 "generate_routes_with_probabilistic_scorer");
6896 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6897 let logger = TestLogger::new();
6898 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6899 let params = ProbabilisticScoringFeeParameters::default();
6900 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6901 generate_routes(bench, &network_graph, scorer, ¶ms,
6902 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
6903 "generate_mpp_routes_with_probabilistic_scorer");
6906 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6907 let logger = TestLogger::new();
6908 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6909 let params = ProbabilisticScoringFeeParameters::default();
6910 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6911 generate_routes(bench, &network_graph, scorer, ¶ms,
6912 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
6913 "generate_large_mpp_routes_with_probabilistic_scorer");
6916 fn generate_routes<S: Score>(
6917 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
6918 score_params: &S::ScoreParams, features: InvoiceFeatures, starting_amount: u64,
6919 bench_name: &'static str,
6921 let payer = bench_utils::payer_pubkey();
6922 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
6923 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6925 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
6926 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
6928 // ...then benchmark finding paths between the nodes we learned.
6930 bench.bench_function(bench_name, |b| b.iter(|| {
6931 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
6932 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
6933 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());