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::{Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
20 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
21 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice};
22 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
23 use crate::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp};
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;
35 /// A [`Router`] implemented using [`find_route`].
36 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> where
38 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
42 random_seed_bytes: Mutex<[u8; 32]>,
47 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> DefaultRouter<G, L, S, SP, Sc> where
49 S::Target: for <'a> LockableScore<'a, ScoreLookUp = 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: ScoreLookUp<ScoreParams = SP>> Router for DefaultRouter<G, L, S, SP, Sc> where
60 S::Target: for <'a> LockableScore<'a, ScoreLookUp = 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.read_lock(), &inflight_htlcs),
83 /// A trait defining behavior for routing a payment.
85 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
87 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
88 /// and [`RouteParameters::final_value_msat`], respectively.
90 &self, payer: &PublicKey, route_params: &RouteParameters,
91 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
92 ) -> Result<Route, LightningError>;
93 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
95 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
96 /// and [`RouteParameters::final_value_msat`], respectively.
98 /// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
100 fn find_route_with_id(
101 &self, payer: &PublicKey, route_params: &RouteParameters,
102 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
103 _payment_hash: PaymentHash, _payment_id: PaymentId
104 ) -> Result<Route, LightningError> {
105 self.find_route(payer, route_params, first_hops, inflight_htlcs)
109 /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
111 /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
114 /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
115 pub struct ScorerAccountingForInFlightHtlcs<'a, SP: Sized, Sc: 'a + ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> {
117 // Maps a channel's short channel id and its direction to the liquidity used up.
118 inflight_htlcs: &'a InFlightHtlcs,
120 impl<'a, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> ScorerAccountingForInFlightHtlcs<'a, SP, Sc, S> {
121 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
122 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
123 ScorerAccountingForInFlightHtlcs {
131 impl<'a, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> Writeable for ScorerAccountingForInFlightHtlcs<'a, SP, Sc, S> {
132 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.scorer.write(writer) }
135 impl<'a, SP: Sized, Sc: 'a + ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, SP, Sc, S> {
136 type ScoreParams = Sc::ScoreParams;
137 fn channel_penalty_msat(&self, short_channel_id: u64, source: &NodeId, target: &NodeId, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
138 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
139 source, target, short_channel_id
141 let usage = ChannelUsage {
142 inflight_htlc_msat: usage.inflight_htlc_msat + used_liquidity,
146 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
148 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
153 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
154 /// in-use channel liquidity.
156 pub struct InFlightHtlcs(
157 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
158 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
159 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
161 HashMap<(u64, bool), u64>
165 /// Constructs an empty `InFlightHtlcs`.
166 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
168 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
169 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
170 if path.hops.is_empty() { return };
172 let mut cumulative_msat = 0;
173 if let Some(tail) = &path.blinded_tail {
174 cumulative_msat += tail.final_value_msat;
177 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
178 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
179 // the router excludes the payer node. In the following lines, the payer's information is
180 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
181 // in our sliding window of two.
182 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
183 .map(|hop| hop.pubkey)
184 .chain(core::iter::once(payer_node_id));
186 // Taking the reversed vector from above, we zip it with just the reversed hops list to
187 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
188 // the total amount sent.
189 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
190 cumulative_msat += next_hop.fee_msat;
192 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
193 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
194 .or_insert(cumulative_msat);
198 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
200 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
202 .entry((channel_scid, source < target))
203 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
204 .or_insert(used_msat);
207 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
209 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
210 self.0.get(&(channel_scid, source < target)).map(|v| *v)
214 impl Writeable for InFlightHtlcs {
215 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
218 impl Readable for InFlightHtlcs {
219 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
220 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
221 Ok(Self(infight_map))
225 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
226 /// that leads to it.
227 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
228 pub struct RouteHop {
229 /// The node_id of the node at this hop.
230 pub pubkey: PublicKey,
231 /// The node_announcement features of the node at this hop. For the last hop, these may be
232 /// amended to match the features present in the invoice this node generated.
233 pub node_features: NodeFeatures,
234 /// The channel that should be used from the previous hop to reach this node.
235 pub short_channel_id: u64,
236 /// The channel_announcement features of the channel that should be used from the previous hop
237 /// to reach this node.
238 pub channel_features: ChannelFeatures,
239 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
240 /// If this is the last hop in [`Path::hops`]:
241 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
242 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
244 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
246 /// The CLTV delta added for this hop.
247 /// If this is the last hop in [`Path::hops`]:
248 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
249 /// * otherwise, this is the CLTV delta expected at the destination
251 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
252 pub cltv_expiry_delta: u32,
255 impl_writeable_tlv_based!(RouteHop, {
256 (0, pubkey, required),
257 (2, node_features, required),
258 (4, short_channel_id, required),
259 (6, channel_features, required),
260 (8, fee_msat, required),
261 (10, cltv_expiry_delta, required),
264 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
265 /// their [`Bolt12Invoice`].
267 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
268 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
269 pub struct BlindedTail {
270 /// The hops of the [`BlindedPath`] provided by the recipient.
272 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
273 pub hops: Vec<BlindedHop>,
274 /// The blinding point of the [`BlindedPath`] provided by the recipient.
276 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
277 pub blinding_point: PublicKey,
278 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
279 /// inferring the destination. May be 0.
280 pub excess_final_cltv_expiry_delta: u32,
281 /// The total amount paid on this [`Path`], excluding the fees.
282 pub final_value_msat: u64,
285 impl_writeable_tlv_based!(BlindedTail, {
286 (0, hops, required_vec),
287 (2, blinding_point, required),
288 (4, excess_final_cltv_expiry_delta, required),
289 (6, final_value_msat, required),
292 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
293 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
294 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
296 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
297 pub hops: Vec<RouteHop>,
298 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
299 pub blinded_tail: Option<BlindedTail>,
303 /// Gets the fees for a given path, excluding any excess paid to the recipient.
304 pub fn fee_msat(&self) -> u64 {
305 match &self.blinded_tail {
306 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
308 // Do not count last hop of each path since that's the full value of the payment
309 self.hops.split_last().map_or(0,
310 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
315 /// Gets the total amount paid on this [`Path`], excluding the fees.
316 pub fn final_value_msat(&self) -> u64 {
317 match &self.blinded_tail {
318 Some(blinded_tail) => blinded_tail.final_value_msat,
319 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
323 /// Gets the final hop's CLTV expiry delta.
324 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
325 match &self.blinded_tail {
327 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
332 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
333 /// it can take multiple paths. Each path is composed of one or more hops through the network.
334 #[derive(Clone, Hash, PartialEq, Eq)]
336 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
337 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
339 pub paths: Vec<Path>,
340 /// The `route_params` parameter passed to [`find_route`].
342 /// This is used by `ChannelManager` to track information which may be required for retries.
344 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
345 pub route_params: Option<RouteParameters>,
349 /// Returns the total amount of fees paid on this [`Route`].
351 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
352 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
353 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
355 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
356 pub fn get_total_fees(&self) -> u64 {
357 let overpaid_value_msat = self.route_params.as_ref()
358 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
359 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
362 /// Returns the total amount paid on this [`Route`], excluding the fees.
364 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
365 /// we had to reach the [`htlc_minimum_msat`] limits.
367 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
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 // For compatibility with LDK versions prior to 0.0.117, we take the individual
398 // RouteParameters' fields and reconstruct them on read.
399 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
400 (2, blinded_tails, optional_vec),
401 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
407 impl Readable for Route {
408 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
409 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
410 let path_count: u64 = Readable::read(reader)?;
411 if path_count == 0 { return Err(DecodeError::InvalidValue); }
412 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
413 let mut min_final_cltv_expiry_delta = u32::max_value();
414 for _ in 0..path_count {
415 let hop_count: u8 = Readable::read(reader)?;
416 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
417 for _ in 0..hop_count {
418 hops.push(Readable::read(reader)?);
420 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
421 min_final_cltv_expiry_delta =
422 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
423 paths.push(Path { hops, blinded_tail: None });
425 _init_and_read_len_prefixed_tlv_fields!(reader, {
426 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
427 (2, blinded_tails, optional_vec),
428 (3, final_value_msat, option),
430 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
431 if blinded_tails.len() != 0 {
432 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
433 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
434 path.blinded_tail = blinded_tail_opt;
438 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
439 let route_params = match (payment_params, final_value_msat) {
440 (Some(payment_params), Some(final_value_msat)) => {
441 Some(RouteParameters { payment_params, final_value_msat })
446 Ok(Route { paths, route_params })
450 /// Parameters needed to find a [`Route`].
452 /// Passed to [`find_route`] and [`build_route_from_hops`].
453 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
454 pub struct RouteParameters {
455 /// The parameters of the failed payment path.
456 pub payment_params: PaymentParameters,
458 /// The amount in msats sent on the failed payment path.
459 pub final_value_msat: u64,
462 impl RouteParameters {
463 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
464 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
465 Self { payment_params, final_value_msat }
469 impl Writeable for RouteParameters {
470 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
471 write_tlv_fields!(writer, {
472 (0, self.payment_params, required),
473 (2, self.final_value_msat, required),
474 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
475 // `RouteParameters` directly. For compatibility, we write it here.
476 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
482 impl Readable for RouteParameters {
483 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
484 _init_and_read_len_prefixed_tlv_fields!(reader, {
485 (0, payment_params, (required: ReadableArgs, 0)),
486 (2, final_value_msat, required),
487 (4, final_cltv_delta, option),
489 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
490 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
491 if final_cltv_expiry_delta == &0 {
492 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
497 final_value_msat: final_value_msat.0.unwrap(),
502 /// Maximum total CTLV difference we allow for a full payment path.
503 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
505 /// Maximum number of paths we allow an (MPP) payment to have.
506 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
507 // limits, but for now more than 10 paths likely carries too much one-path failure.
508 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
510 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
512 // The median hop CLTV expiry delta currently seen in the network.
513 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
515 // During routing, we only consider paths shorter than our maximum length estimate.
516 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
517 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
518 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
520 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
521 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
522 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
523 // (payment_secret and total_msat) = 93 bytes for the final hop.
524 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
525 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
526 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
528 /// Information used to route a payment.
529 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
530 pub struct PaymentParameters {
531 /// Information about the payee, such as their features and route hints for their channels.
534 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
535 pub expiry_time: Option<u64>,
537 /// The maximum total CLTV delta we accept for the route.
538 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
539 pub max_total_cltv_expiry_delta: u32,
541 /// The maximum number of paths that may be used by (MPP) payments.
542 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
543 pub max_path_count: u8,
545 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
546 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
547 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
548 /// increasing failure probability for those paths.
550 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
551 /// restriction have been found. While paths which meet this criteria will be searched for, it
552 /// is ultimately up to the scorer to select them over other paths.
554 /// A value of 0 will allow payments up to and including a channel's total announced usable
555 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
558 pub max_channel_saturation_power_of_half: u8,
560 /// A list of SCIDs which this payment was previously attempted over and which caused the
561 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
563 pub previously_failed_channels: Vec<u64>,
566 impl Writeable for PaymentParameters {
567 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
568 let mut clear_hints = &vec![];
569 let mut blinded_hints = &vec![];
571 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
572 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
574 write_tlv_fields!(writer, {
575 (0, self.payee.node_id(), option),
576 (1, self.max_total_cltv_expiry_delta, required),
577 (2, self.payee.features(), option),
578 (3, self.max_path_count, required),
579 (4, *clear_hints, required_vec),
580 (5, self.max_channel_saturation_power_of_half, required),
581 (6, self.expiry_time, option),
582 (7, self.previously_failed_channels, required_vec),
583 (8, *blinded_hints, optional_vec),
584 (9, self.payee.final_cltv_expiry_delta(), option),
590 impl ReadableArgs<u32> for PaymentParameters {
591 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
592 _init_and_read_len_prefixed_tlv_fields!(reader, {
593 (0, payee_pubkey, option),
594 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
595 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
596 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
597 (4, clear_route_hints, required_vec),
598 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
599 (6, expiry_time, option),
600 (7, previously_failed_channels, optional_vec),
601 (8, blinded_route_hints, optional_vec),
602 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
604 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
605 let payee = if blinded_route_hints.len() != 0 {
606 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
608 route_hints: blinded_route_hints,
609 features: features.and_then(|f: Features| f.bolt12()),
613 route_hints: clear_route_hints,
614 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
615 features: features.and_then(|f| f.bolt11()),
616 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
620 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
621 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
623 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
625 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
631 impl PaymentParameters {
632 /// Creates a payee with the node id of the given `pubkey`.
634 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
636 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
638 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
640 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
641 max_path_count: DEFAULT_MAX_PATH_COUNT,
642 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
643 previously_failed_channels: Vec::new(),
647 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
649 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
652 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
653 /// whether your router will be allowed to find a multi-part route for this payment. If you
654 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
655 /// [`RecipientOnionFields::secret_only`].
657 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
658 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
659 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
660 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
661 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
664 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
665 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
666 /// [`PaymentParameters::expiry_time`].
667 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
668 Self::blinded(invoice.payment_paths().to_vec())
669 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
670 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
673 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
674 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
676 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
678 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
679 max_path_count: DEFAULT_MAX_PATH_COUNT,
680 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
681 previously_failed_channels: Vec::new(),
685 /// Includes the payee's features. Errors if the parameters were not initialized with
686 /// [`PaymentParameters::from_bolt12_invoice`].
688 /// This is not exported to bindings users since bindings don't support move semantics
689 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
691 Payee::Clear { .. } => Err(()),
692 Payee::Blinded { route_hints, .. } =>
693 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
697 /// Includes the payee's features. Errors if the parameters were initialized with
698 /// [`PaymentParameters::from_bolt12_invoice`].
700 /// This is not exported to bindings users since bindings don't support move semantics
701 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
703 Payee::Blinded { .. } => Err(()),
704 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
706 payee: Payee::Clear {
707 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
713 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
714 /// [`PaymentParameters::from_bolt12_invoice`].
716 /// This is not exported to bindings users since bindings don't support move semantics
717 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
719 Payee::Blinded { .. } => Err(()),
720 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
722 payee: Payee::Clear {
723 route_hints, node_id, features, final_cltv_expiry_delta,
729 /// Includes a payment expiration in seconds relative to the UNIX epoch.
731 /// This is not exported to bindings users since bindings don't support move semantics
732 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
733 Self { expiry_time: Some(expiry_time), ..self }
736 /// Includes a limit for the total CLTV expiry delta which is considered during routing
738 /// This is not exported to bindings users since bindings don't support move semantics
739 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
740 Self { max_total_cltv_expiry_delta, ..self }
743 /// Includes a limit for the maximum number of payment paths that may be used.
745 /// This is not exported to bindings users since bindings don't support move semantics
746 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
747 Self { max_path_count, ..self }
750 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
751 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
753 /// This is not exported to bindings users since bindings don't support move semantics
754 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
755 Self { max_channel_saturation_power_of_half, ..self }
759 /// The recipient of a payment, differing based on whether they've hidden their identity with route
761 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
763 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
764 /// will be included in the final [`Route`].
766 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
768 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
769 /// Features supported by the payee.
771 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
773 features: Option<Bolt12InvoiceFeatures>,
775 /// The recipient included these route hints in their BOLT11 invoice.
777 /// The node id of the payee.
779 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
780 route_hints: Vec<RouteHint>,
781 /// Features supported by the payee.
783 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
784 /// does not contain any features.
786 /// [`for_keysend`]: PaymentParameters::for_keysend
787 features: Option<Bolt11InvoiceFeatures>,
788 /// The minimum CLTV delta at the end of the route. This value must not be zero.
789 final_cltv_expiry_delta: u32,
794 fn node_id(&self) -> Option<PublicKey> {
796 Self::Clear { node_id, .. } => Some(*node_id),
800 fn node_features(&self) -> Option<NodeFeatures> {
802 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
803 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
806 fn supports_basic_mpp(&self) -> bool {
808 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
809 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
812 fn features(&self) -> Option<FeaturesRef> {
814 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
815 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
818 fn final_cltv_expiry_delta(&self) -> Option<u32> {
820 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
824 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
826 Self::Blinded { route_hints, .. } => &route_hints[..],
827 Self::Clear { .. } => &[]
831 fn unblinded_route_hints(&self) -> &[RouteHint] {
833 Self::Blinded { .. } => &[],
834 Self::Clear { route_hints, .. } => &route_hints[..]
839 enum FeaturesRef<'a> {
840 Bolt11(&'a Bolt11InvoiceFeatures),
841 Bolt12(&'a Bolt12InvoiceFeatures),
844 Bolt11(Bolt11InvoiceFeatures),
845 Bolt12(Bolt12InvoiceFeatures),
849 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
851 Self::Bolt12(f) => Some(f),
855 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
857 Self::Bolt11(f) => Some(f),
863 impl<'a> Writeable for FeaturesRef<'a> {
864 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
866 Self::Bolt11(f) => Ok(f.write(w)?),
867 Self::Bolt12(f) => Ok(f.write(w)?),
872 impl ReadableArgs<bool> for Features {
873 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
874 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
875 Ok(Self::Bolt12(Readable::read(reader)?))
879 /// A list of hops along a payment path terminating with a channel to the recipient.
880 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
881 pub struct RouteHint(pub Vec<RouteHintHop>);
883 impl Writeable for RouteHint {
884 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
885 (self.0.len() as u64).write(writer)?;
886 for hop in self.0.iter() {
893 impl Readable for RouteHint {
894 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
895 let hop_count: u64 = Readable::read(reader)?;
896 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
897 for _ in 0..hop_count {
898 hops.push(Readable::read(reader)?);
904 /// A channel descriptor for a hop along a payment path.
905 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
906 pub struct RouteHintHop {
907 /// The node_id of the non-target end of the route
908 pub src_node_id: PublicKey,
909 /// The short_channel_id of this channel
910 pub short_channel_id: u64,
911 /// The fees which must be paid to use this channel
912 pub fees: RoutingFees,
913 /// The difference in CLTV values between this node and the next node.
914 pub cltv_expiry_delta: u16,
915 /// The minimum value, in msat, which must be relayed to the next hop.
916 pub htlc_minimum_msat: Option<u64>,
917 /// The maximum value in msat available for routing with a single HTLC.
918 pub htlc_maximum_msat: Option<u64>,
921 impl_writeable_tlv_based!(RouteHintHop, {
922 (0, src_node_id, required),
923 (1, htlc_minimum_msat, option),
924 (2, short_channel_id, required),
925 (3, htlc_maximum_msat, option),
927 (6, cltv_expiry_delta, required),
930 #[derive(Eq, PartialEq)]
931 struct RouteGraphNode {
933 lowest_fee_to_node: u64,
934 total_cltv_delta: u32,
935 // The maximum value a yet-to-be-constructed payment path might flow through this node.
936 // This value is upper-bounded by us by:
937 // - how much is needed for a path being constructed
938 // - how much value can channels following this node (up to the destination) can contribute,
939 // considering their capacity and fees
940 value_contribution_msat: u64,
941 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
942 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
943 path_htlc_minimum_msat: u64,
944 /// All penalties incurred from this hop on the way to the destination, as calculated using
946 path_penalty_msat: u64,
947 /// The number of hops walked up to this node.
948 path_length_to_node: u8,
951 impl cmp::Ord for RouteGraphNode {
952 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
953 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
954 .saturating_add(other.path_penalty_msat);
955 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
956 .saturating_add(self.path_penalty_msat);
957 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
961 impl cmp::PartialOrd for RouteGraphNode {
962 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
963 Some(self.cmp(other))
967 /// A wrapper around the various hop representations.
969 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
970 #[derive(Clone, Debug)]
971 enum CandidateRouteHop<'a> {
972 /// A hop from the payer, where the outbound liquidity is known.
974 details: &'a ChannelDetails,
976 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
978 info: DirectedChannelInfo<'a>,
979 short_channel_id: u64,
981 /// A hop to the payee found in the BOLT 11 payment invoice, though not necessarily a direct
984 hint: &'a RouteHintHop,
986 /// The payee's identity is concealed behind blinded paths provided in a BOLT 12 invoice.
988 hint: &'a (BlindedPayInfo, BlindedPath),
991 /// Similar to [`Self::Blinded`], but the path here has 1 blinded hop. `BlindedPayInfo` provided
992 /// for 1-hop blinded paths is ignored because it is meant to apply to the hops *between* the
993 /// introduction node and the destination. Useful for tracking that we need to include a blinded
994 /// path at the end of our [`Route`].
996 hint: &'a (BlindedPayInfo, BlindedPath),
1001 impl<'a> CandidateRouteHop<'a> {
1002 fn short_channel_id(&self) -> Option<u64> {
1004 CandidateRouteHop::FirstHop { details } => Some(details.get_outbound_payment_scid().unwrap()),
1005 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
1006 CandidateRouteHop::PrivateHop { hint } => Some(hint.short_channel_id),
1007 CandidateRouteHop::Blinded { .. } => None,
1008 CandidateRouteHop::OneHopBlinded { .. } => None,
1012 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1013 fn features(&self) -> ChannelFeatures {
1015 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
1016 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
1017 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
1018 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
1019 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
1023 fn cltv_expiry_delta(&self) -> u32 {
1025 CandidateRouteHop::FirstHop { .. } => 0,
1026 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1027 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
1028 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1029 CandidateRouteHop::OneHopBlinded { .. } => 0,
1033 fn htlc_minimum_msat(&self) -> u64 {
1035 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_minimum_msat,
1036 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1037 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
1038 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1039 CandidateRouteHop::OneHopBlinded { .. } => 0,
1043 fn fees(&self) -> RoutingFees {
1045 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1046 base_msat: 0, proportional_millionths: 0,
1048 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1049 CandidateRouteHop::PrivateHop { hint } => hint.fees,
1050 CandidateRouteHop::Blinded { hint, .. } => {
1052 base_msat: hint.0.fee_base_msat,
1053 proportional_millionths: hint.0.fee_proportional_millionths
1056 CandidateRouteHop::OneHopBlinded { .. } =>
1057 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1061 fn effective_capacity(&self) -> EffectiveCapacity {
1063 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
1064 liquidity_msat: details.next_outbound_htlc_limit_msat,
1066 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1067 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }} =>
1068 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1069 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }} =>
1070 EffectiveCapacity::Infinite,
1071 CandidateRouteHop::Blinded { hint, .. } =>
1072 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1073 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1077 fn id(&self, channel_direction: bool /* src_node_id < target_node_id */) -> CandidateHopId {
1079 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1080 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1081 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), channel_direction)),
1084 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1086 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1094 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1095 enum CandidateHopId {
1096 /// Contains (scid, src_node_id < target_node_id)
1098 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1103 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1104 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1106 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1107 EffectiveCapacity::Infinite => u64::max_value(),
1108 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1109 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1110 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1111 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1112 // expected to have been generated from up-to-date capacity information.
1113 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1114 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1115 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1119 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1120 -> bool where I1::Item: PartialEq<I2::Item> {
1122 let a = iter_a.next();
1123 let b = iter_b.next();
1124 if a.is_none() && b.is_none() { return true; }
1125 if a.is_none() || b.is_none() { return false; }
1126 if a.unwrap().ne(&b.unwrap()) { return false; }
1130 /// It's useful to keep track of the hops associated with the fees required to use them,
1131 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1132 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1133 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1135 struct PathBuildingHop<'a> {
1136 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
1137 // is a larger refactor and will require careful performance analysis.
1139 candidate: CandidateRouteHop<'a>,
1142 /// All the fees paid *after* this channel on the way to the destination
1143 next_hops_fee_msat: u64,
1144 /// Fee paid for the use of the current channel (see candidate.fees()).
1145 /// The value will be actually deducted from the counterparty balance on the previous link.
1146 hop_use_fee_msat: u64,
1147 /// Used to compare channels when choosing the for routing.
1148 /// Includes paying for the use of a hop and the following hops, as well as
1149 /// an estimated cost of reaching this hop.
1150 /// Might get stale when fees are recomputed. Primarily for internal use.
1151 total_fee_msat: u64,
1152 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1153 /// walk and may be invalid thereafter.
1154 path_htlc_minimum_msat: u64,
1155 /// All penalties incurred from this channel on the way to the destination, as calculated using
1156 /// channel scoring.
1157 path_penalty_msat: u64,
1158 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1159 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1160 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1161 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1162 /// avoid processing them again.
1163 was_processed: bool,
1164 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1165 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1166 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1167 // value_contribution_msat, which requires tracking it here. See comments below where it is
1168 // used for more info.
1169 value_contribution_msat: u64,
1172 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1173 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1174 let mut debug_struct = f.debug_struct("PathBuildingHop");
1176 .field("node_id", &self.node_id)
1177 .field("short_channel_id", &self.candidate.short_channel_id())
1178 .field("total_fee_msat", &self.total_fee_msat)
1179 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1180 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1181 .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)))
1182 .field("path_penalty_msat", &self.path_penalty_msat)
1183 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1184 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1185 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1186 let debug_struct = debug_struct
1187 .field("value_contribution_msat", &self.value_contribution_msat);
1188 debug_struct.finish()
1192 // Instantiated with a list of hops with correct data in them collected during path finding,
1193 // an instance of this struct should be further modified only via given methods.
1195 struct PaymentPath<'a> {
1196 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1199 impl<'a> PaymentPath<'a> {
1200 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1201 fn get_value_msat(&self) -> u64 {
1202 self.hops.last().unwrap().0.fee_msat
1205 fn get_path_penalty_msat(&self) -> u64 {
1206 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1209 fn get_total_fee_paid_msat(&self) -> u64 {
1210 if self.hops.len() < 1 {
1214 // Can't use next_hops_fee_msat because it gets outdated.
1215 for (i, (hop, _)) in self.hops.iter().enumerate() {
1216 if i != self.hops.len() - 1 {
1217 result += hop.fee_msat;
1223 fn get_cost_msat(&self) -> u64 {
1224 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1227 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1228 // to change fees may result in an inconsistency.
1230 // Sometimes we call this function right after constructing a path which is inconsistent in
1231 // that it the value being transferred has decreased while we were doing path finding, leading
1232 // to the fees being paid not lining up with the actual limits.
1234 // Note that this function is not aware of the available_liquidity limit, and thus does not
1235 // support increasing the value being transferred beyond what was selected during the initial
1237 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
1238 let mut total_fee_paid_msat = 0 as u64;
1239 for i in (0..self.hops.len()).rev() {
1240 let last_hop = i == self.hops.len() - 1;
1242 // For non-last-hop, this value will represent the fees paid on the current hop. It
1243 // will consist of the fees for the use of the next hop, and extra fees to match
1244 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1245 let mut cur_hop_fees_msat = 0;
1247 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1250 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1251 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1252 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1253 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1254 // set it too high just to maliciously take more fees by exploiting this
1255 // match htlc_minimum_msat logic.
1256 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1257 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1258 // Note that there is a risk that *previous hops* (those closer to us, as we go
1259 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1261 // This might make us end up with a broken route, although this should be super-rare
1262 // in practice, both because of how healthy channels look like, and how we pick
1263 // channels in add_entry.
1264 // Also, this can't be exploited more heavily than *announce a free path and fail
1266 cur_hop_transferred_amount_msat += extra_fees_msat;
1267 total_fee_paid_msat += extra_fees_msat;
1268 cur_hop_fees_msat += extra_fees_msat;
1272 // Final hop is a special case: it usually has just value_msat (by design), but also
1273 // it still could overpay for the htlc_minimum_msat.
1274 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1276 // Propagate updated fees for the use of the channels to one hop back, where they
1277 // will be actually paid (fee_msat). The last hop is handled above separately.
1278 cur_hop.fee_msat = cur_hop_fees_msat;
1281 // Fee for the use of the current hop which will be deducted on the previous hop.
1282 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1283 // this channel is free for us.
1285 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1286 cur_hop.hop_use_fee_msat = new_fee;
1287 total_fee_paid_msat += new_fee;
1289 // It should not be possible because this function is called only to reduce the
1290 // value. In that case, compute_fee was already called with the same fees for
1291 // larger amount and there was no overflow.
1300 /// Calculate the fees required to route the given amount over a channel with the given fees.
1301 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1302 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1303 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1307 /// Calculate the fees required to route the given amount over a channel with the given fees,
1308 /// saturating to [`u64::max_value`].
1309 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1310 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1311 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1312 .saturating_add(channel_fees.base_msat as u64)
1315 /// The default `features` we assume for a node in a route, when no `features` are known about that
1318 /// Default features are:
1319 /// * variable_length_onion_optional
1320 fn default_node_features() -> NodeFeatures {
1321 let mut features = NodeFeatures::empty();
1322 features.set_variable_length_onion_optional();
1326 struct LoggedPayeePubkey(Option<PublicKey>);
1327 impl fmt::Display for LoggedPayeePubkey {
1328 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1331 "payee node id ".fmt(f)?;
1335 "blinded payee".fmt(f)
1341 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1342 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1343 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1345 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1346 "blinded route hint with introduction node id ".fmt(f)?;
1347 hint.1.introduction_node_id.fmt(f)?;
1348 " and blinding point ".fmt(f)?;
1349 hint.1.blinding_point.fmt(f)
1351 CandidateRouteHop::FirstHop { .. } => {
1352 "first hop with SCID ".fmt(f)?;
1353 self.0.short_channel_id().unwrap().fmt(f)
1355 CandidateRouteHop::PrivateHop { .. } => {
1356 "route hint with SCID ".fmt(f)?;
1357 self.0.short_channel_id().unwrap().fmt(f)
1361 self.0.short_channel_id().unwrap().fmt(f)
1368 fn sort_first_hop_channels(
1369 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1370 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1372 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1373 // most like to use.
1375 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1376 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1379 // Second, because simply always sorting in descending order would always use our largest
1380 // available outbound capacity, needlessly fragmenting our available channel capacities,
1381 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1382 // which have enough, but not too much, capacity for the payment.
1384 // Available outbound balances factor in liquidity already reserved for previously found paths.
1385 channels.sort_unstable_by(|chan_a, chan_b| {
1386 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1387 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1388 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1389 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1390 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1391 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1392 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1393 // Sort in descending order
1394 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1396 // Sort in ascending order
1397 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1402 /// Finds a route from us (payer) to the given target node (payee).
1404 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1405 /// in the given [`RouteParameters::payment_params`].
1406 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1408 /// Private routing paths between a public node and the target may be included in the `payee` field
1409 /// of [`RouteParameters::payment_params`].
1411 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1412 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1413 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1415 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1416 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1417 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1421 /// Panics if first_hops contains channels without `short_channel_id`s;
1422 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1424 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1425 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1426 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1427 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1428 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1429 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1430 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1431 ) -> Result<Route, LightningError>
1432 where L::Target: Logger, GL::Target: Logger {
1433 let graph_lock = network_graph.read_only();
1434 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1435 scorer, score_params, random_seed_bytes)?;
1436 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1440 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1441 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1442 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1443 _random_seed_bytes: &[u8; 32]
1444 ) -> Result<Route, LightningError>
1445 where L::Target: Logger {
1447 let payment_params = &route_params.payment_params;
1448 let final_value_msat = route_params.final_value_msat;
1449 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1450 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1451 // so use a dummy id for this in the blinded case.
1452 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1453 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1454 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1455 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1456 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1458 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1459 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1462 if final_value_msat > MAX_VALUE_MSAT {
1463 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1466 if final_value_msat == 0 {
1467 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1470 match &payment_params.payee {
1471 Payee::Clear { route_hints, node_id, .. } => {
1472 for route in route_hints.iter() {
1473 for hop in &route.0 {
1474 if hop.src_node_id == *node_id {
1475 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1480 Payee::Blinded { route_hints, .. } => {
1481 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1482 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});
1484 for (_, blinded_path) in route_hints.iter() {
1485 if blinded_path.blinded_hops.len() == 0 {
1486 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1487 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1488 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1489 } else if blinded_path.blinded_hops.len() == 1 &&
1490 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1491 && p.introduction_node_id != blinded_path.introduction_node_id)
1493 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1498 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1499 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1500 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});
1503 // The general routing idea is the following:
1504 // 1. Fill first/last hops communicated by the caller.
1505 // 2. Attempt to construct a path from payer to payee for transferring
1506 // any ~sufficient (described later) value.
1507 // If succeed, remember which channels were used and how much liquidity they have available,
1508 // so that future paths don't rely on the same liquidity.
1509 // 3. Proceed to the next step if:
1510 // - we hit the recommended target value;
1511 // - OR if we could not construct a new path. Any next attempt will fail too.
1512 // Otherwise, repeat step 2.
1513 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1514 // (not recommended value).
1515 // 5. If yes, proceed. If not, fail routing.
1516 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1517 // transferred up to the transfer target value.
1518 // 7. Reduce the value of the last path until we are sending only the target value.
1519 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1520 // them so that we're not sending two HTLCs along the same path.
1522 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1523 // distance from the payee
1525 // We are not a faithful Dijkstra's implementation because we can change values which impact
1526 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1527 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1528 // the value we are currently attempting to send over a path, we simply reduce the value being
1529 // sent along the path for any hops after that channel. This may imply that later fees (which
1530 // we've already tabulated) are lower because a smaller value is passing through the channels
1531 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1532 // channels which were selected earlier (and which may still be used for other paths without a
1533 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1536 // One potentially problematic case for this algorithm would be if there are many
1537 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1538 // graph walking), we may never find a path which is not liquidity-limited and has lower
1539 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1540 // Because we only consider paths with at least 5% of the total value being sent, the damage
1541 // from such a case should be limited, however this could be further reduced in the future by
1542 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1543 // limits for the purposes of fee calculation.
1545 // Alternatively, we could store more detailed path information in the heap (targets, below)
1546 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1547 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1548 // and practically (as we would need to store dynamically-allocated path information in heap
1549 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1550 // results of such an algorithm would likely be biased towards lower-value paths.
1552 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1553 // outside of our current search value, running a path search more times to gather candidate
1554 // paths at different values. While this may be acceptable, further path searches may increase
1555 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1556 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1557 // the same time, remaining generic across different payment values.
1559 let network_channels = network_graph.channels();
1560 let network_nodes = network_graph.nodes();
1562 if payment_params.max_path_count == 0 {
1563 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1566 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1567 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1569 let allow_mpp = if payment_params.max_path_count == 1 {
1571 } else if payment_params.payee.supports_basic_mpp() {
1573 } else if let Some(payee) = payee_node_id_opt {
1574 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1575 |info| info.features.supports_basic_mpp()))
1578 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1579 LoggedPayeePubkey(payment_params.payee.node_id()), if allow_mpp { "with" } else { "without" },
1580 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1583 // Prepare the data we'll use for payee-to-payer search by
1584 // inserting first hops suggested by the caller as targets.
1585 // Our search will then attempt to reach them while traversing from the payee node.
1586 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1587 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1588 if let Some(hops) = first_hops {
1590 if chan.get_outbound_payment_scid().is_none() {
1591 panic!("first_hops should be filled in with usable channels, not pending ones");
1593 if chan.counterparty.node_id == *our_node_pubkey {
1594 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1597 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1598 .or_insert(Vec::new())
1601 if first_hop_targets.is_empty() {
1602 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1606 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1607 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1608 // adding duplicate entries when we find a better path to a given node.
1609 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1611 // Map from node_id to information about the best current path to that node, including feerate
1613 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1615 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1616 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1617 // htlc_minimum with extra fees while still finding a cheaper path.
1618 let mut hit_minimum_limit;
1620 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1621 // We start with a path_value of the exact amount we want, and if that generates a route we may
1622 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1623 // amount we want in total across paths, selecting the best subset at the end.
1624 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1625 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1626 let mut path_value_msat = final_value_msat;
1628 // Routing Fragmentation Mitigation heuristic:
1630 // Routing fragmentation across many payment paths increases the overall routing
1631 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1632 // Taking too many smaller paths also increases the chance of payment failure.
1633 // Thus to avoid this effect, we require from our collected links to provide
1634 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1635 // This requirement is currently set to be 1/max_path_count of the payment
1636 // value to ensure we only ever return routes that do not violate this limit.
1637 let minimal_value_contribution_msat: u64 = if allow_mpp {
1638 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1643 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1644 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1645 // drop the requirement by setting this to 0.
1646 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1648 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1649 // determine if the channel can be used by additional MPP paths or to inform path finding
1650 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1651 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1653 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1654 HashMap::with_capacity(network_nodes.len());
1656 // Keeping track of how much value we already collected across other paths. Helps to decide
1657 // when we want to stop looking for new paths.
1658 let mut already_collected_value_msat = 0;
1660 for (_, channels) in first_hop_targets.iter_mut() {
1661 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1665 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1666 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1668 // Remember how many candidates we ignored to allow for some logging afterwards.
1669 let mut num_ignored_value_contribution = 0;
1670 let mut num_ignored_path_length_limit = 0;
1671 let mut num_ignored_cltv_delta_limit = 0;
1672 let mut num_ignored_previously_failed = 0;
1674 macro_rules! add_entry {
1675 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1676 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1677 // since that value has to be transferred over this channel.
1678 // Returns whether this channel caused an update to `targets`.
1679 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1680 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1681 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1682 // We "return" whether we updated the path at the end, and how much we can route via
1683 // this channel, via this:
1684 let mut did_add_update_path_to_src_node = None;
1685 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1686 // practice these cases should be caught earlier:
1687 // - for regular channels at channel announcement (TODO)
1688 // - for first and last hops early in get_route
1689 if $src_node_id != $dest_node_id {
1690 let scid_opt = $candidate.short_channel_id();
1691 let effective_capacity = $candidate.effective_capacity();
1692 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1694 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1695 // It may be misleading because we might later choose to reduce the value transferred
1696 // over these channels, and the channel which was insufficient might become sufficient.
1697 // Worst case: we drop a good channel here because it can't cover the high following
1698 // fees caused by one expensive channel, but then this channel could have been used
1699 // if the amount being transferred over this path is lower.
1700 // We do this for now, but this is a subject for removal.
1701 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1702 let used_liquidity_msat = used_liquidities
1703 .get(&$candidate.id($src_node_id < $dest_node_id))
1704 .map_or(0, |used_liquidity_msat| {
1705 available_value_contribution_msat = available_value_contribution_msat
1706 .saturating_sub(*used_liquidity_msat);
1707 *used_liquidity_msat
1710 // Verify the liquidity offered by this channel complies to the minimal contribution.
1711 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1712 // Do not consider candidate hops that would exceed the maximum path length.
1713 let path_length_to_node = $next_hops_path_length + 1;
1714 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1716 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1717 // In order to already account for some of the privacy enhancing random CLTV
1718 // expiry delta offset we add on top later, we subtract a rough estimate
1719 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1720 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1721 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1722 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1723 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1724 .saturating_add($candidate.cltv_expiry_delta());
1725 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1727 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1728 // Includes paying fees for the use of the following channels.
1729 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1730 Some(result) => result,
1731 // Can't overflow due to how the values were computed right above.
1732 None => unreachable!(),
1734 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1735 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1736 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1738 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1739 let may_overpay_to_meet_path_minimum_msat =
1740 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1741 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1742 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1743 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1745 let payment_failed_on_this_channel = scid_opt.map_or(false,
1746 |scid| payment_params.previously_failed_channels.contains(&scid));
1748 let should_log_candidate = match $candidate {
1749 CandidateRouteHop::FirstHop { .. } => true,
1750 CandidateRouteHop::PrivateHop { .. } => true,
1751 CandidateRouteHop::Blinded { .. } => true,
1755 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1756 // bother considering this channel. If retrying with recommended_value_msat may
1757 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1758 // around again with a higher amount.
1759 if !contributes_sufficient_value {
1760 if should_log_candidate {
1761 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
1763 num_ignored_value_contribution += 1;
1764 } else if exceeds_max_path_length {
1765 if should_log_candidate {
1766 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
1768 num_ignored_path_length_limit += 1;
1769 } else if exceeds_cltv_delta_limit {
1770 if should_log_candidate {
1771 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
1773 num_ignored_cltv_delta_limit += 1;
1774 } else if payment_failed_on_this_channel {
1775 if should_log_candidate {
1776 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
1778 num_ignored_previously_failed += 1;
1779 } else if may_overpay_to_meet_path_minimum_msat {
1780 hit_minimum_limit = true;
1781 } else if over_path_minimum_msat {
1782 // Note that low contribution here (limited by available_liquidity_msat)
1783 // might violate htlc_minimum_msat on the hops which are next along the
1784 // payment path (upstream to the payee). To avoid that, we recompute
1785 // path fees knowing the final path contribution after constructing it.
1786 let path_htlc_minimum_msat = cmp::max(
1787 compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1788 .saturating_add($next_hops_path_htlc_minimum_msat),
1789 $candidate.htlc_minimum_msat());
1790 let hm_entry = dist.entry($src_node_id);
1791 let old_entry = hm_entry.or_insert_with(|| {
1792 // If there was previously no known way to access the source node
1793 // (recall it goes payee-to-payer) of short_channel_id, first add a
1794 // semi-dummy record just to compute the fees to reach the source node.
1795 // This will affect our decision on selecting short_channel_id
1796 // as a way to reach the $dest_node_id.
1798 node_id: $dest_node_id.clone(),
1799 candidate: $candidate.clone(),
1801 next_hops_fee_msat: u64::max_value(),
1802 hop_use_fee_msat: u64::max_value(),
1803 total_fee_msat: u64::max_value(),
1804 path_htlc_minimum_msat,
1805 path_penalty_msat: u64::max_value(),
1806 was_processed: false,
1807 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1808 value_contribution_msat,
1812 #[allow(unused_mut)] // We only use the mut in cfg(test)
1813 let mut should_process = !old_entry.was_processed;
1814 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1816 // In test/fuzzing builds, we do extra checks to make sure the skipping
1817 // of already-seen nodes only happens in cases we expect (see below).
1818 if !should_process { should_process = true; }
1822 let mut hop_use_fee_msat = 0;
1823 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1825 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1826 // will have the same effective-fee
1827 if $src_node_id != our_node_id {
1828 // Note that `u64::max_value` means we'll always fail the
1829 // `old_entry.total_fee_msat > total_fee_msat` check below
1830 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1831 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1834 let channel_usage = ChannelUsage {
1835 amount_msat: amount_to_transfer_over_msat,
1836 inflight_htlc_msat: used_liquidity_msat,
1839 let channel_penalty_msat = scid_opt.map_or(0,
1840 |scid| scorer.channel_penalty_msat(scid, &$src_node_id, &$dest_node_id,
1841 channel_usage, score_params));
1842 let path_penalty_msat = $next_hops_path_penalty_msat
1843 .saturating_add(channel_penalty_msat);
1844 let new_graph_node = RouteGraphNode {
1845 node_id: $src_node_id,
1846 lowest_fee_to_node: total_fee_msat,
1847 total_cltv_delta: hop_total_cltv_delta,
1848 value_contribution_msat,
1849 path_htlc_minimum_msat,
1851 path_length_to_node,
1854 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1855 // if this way is cheaper than the already known
1856 // (considering the cost to "reach" this channel from the route destination,
1857 // the cost of using this channel,
1858 // and the cost of routing to the source node of this channel).
1859 // Also, consider that htlc_minimum_msat_difference, because we might end up
1860 // paying it. Consider the following exploit:
1861 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1862 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1863 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1864 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1866 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1867 // but it may require additional tracking - we don't want to double-count
1868 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1869 // can't use something that may decrease on future hops.
1870 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1871 .saturating_add(old_entry.path_penalty_msat);
1872 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1873 .saturating_add(path_penalty_msat);
1875 if !old_entry.was_processed && new_cost < old_cost {
1876 targets.push(new_graph_node);
1877 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1878 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1879 old_entry.total_fee_msat = total_fee_msat;
1880 old_entry.node_id = $dest_node_id.clone();
1881 old_entry.candidate = $candidate.clone();
1882 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1883 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1884 old_entry.path_penalty_msat = path_penalty_msat;
1885 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1887 old_entry.value_contribution_msat = value_contribution_msat;
1889 did_add_update_path_to_src_node = Some(value_contribution_msat);
1890 } else if old_entry.was_processed && new_cost < old_cost {
1891 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1893 // If we're skipping processing a node which was previously
1894 // processed even though we found another path to it with a
1895 // cheaper fee, check that it was because the second path we
1896 // found (which we are processing now) has a lower value
1897 // contribution due to an HTLC minimum limit.
1899 // e.g. take a graph with two paths from node 1 to node 2, one
1900 // through channel A, and one through channel B. Channel A and
1901 // B are both in the to-process heap, with their scores set by
1902 // a higher htlc_minimum than fee.
1903 // Channel A is processed first, and the channels onwards from
1904 // node 1 are added to the to-process heap. Thereafter, we pop
1905 // Channel B off of the heap, note that it has a much more
1906 // restrictive htlc_maximum_msat, and recalculate the fees for
1907 // all of node 1's channels using the new, reduced, amount.
1909 // This would be bogus - we'd be selecting a higher-fee path
1910 // with a lower htlc_maximum_msat instead of the one we'd
1911 // already decided to use.
1912 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1914 value_contribution_msat + path_penalty_msat <
1915 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1923 did_add_update_path_to_src_node
1927 let default_node_features = default_node_features();
1929 // Find ways (channels with destination) to reach a given node and store them
1930 // in the corresponding data structures (routing graph etc).
1931 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1932 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1933 // This data can later be helpful to optimize routing (pay lower fees).
1934 macro_rules! add_entries_to_cheapest_to_target_node {
1935 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1936 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1937 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1938 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1939 let was_processed = elem.was_processed;
1940 elem.was_processed = true;
1943 // Entries are added to dist in add_entry!() when there is a channel from a node.
1944 // Because there are no channels from payee, it will not have a dist entry at this point.
1945 // If we're processing any other node, it is always be the result of a channel from it.
1946 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
1951 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1952 for details in first_channels {
1953 let candidate = CandidateRouteHop::FirstHop { details };
1954 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1955 $next_hops_value_contribution,
1956 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1957 $next_hops_cltv_delta, $next_hops_path_length);
1961 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1964 &default_node_features
1967 if !features.requires_unknown_bits() {
1968 for chan_id in $node.channels.iter() {
1969 let chan = network_channels.get(chan_id).unwrap();
1970 if !chan.features.requires_unknown_bits() {
1971 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1972 if first_hops.is_none() || *source != our_node_id {
1973 if directed_channel.direction().enabled {
1974 let candidate = CandidateRouteHop::PublicHop {
1975 info: directed_channel,
1976 short_channel_id: *chan_id,
1978 add_entry!(candidate, *source, $node_id,
1979 $fee_to_target_msat,
1980 $next_hops_value_contribution,
1981 $next_hops_path_htlc_minimum_msat,
1982 $next_hops_path_penalty_msat,
1983 $next_hops_cltv_delta, $next_hops_path_length);
1994 let mut payment_paths = Vec::<PaymentPath>::new();
1996 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1997 'paths_collection: loop {
1998 // For every new path, start from scratch, except for used_liquidities, which
1999 // helps to avoid reusing previously selected paths in future iterations.
2002 hit_minimum_limit = false;
2004 // If first hop is a private channel and the only way to reach the payee, this is the only
2005 // place where it could be added.
2006 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2007 for details in first_channels {
2008 let candidate = CandidateRouteHop::FirstHop { details };
2009 let added = add_entry!(candidate, our_node_id, payee, 0, path_value_msat,
2010 0, 0u64, 0, 0).is_some();
2011 log_trace!(logger, "{} direct route to payee via {}",
2012 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2016 // Add the payee as a target, so that the payee-to-payer
2017 // search algorithm knows what to start with.
2018 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2019 // The payee is not in our network graph, so nothing to add here.
2020 // There is still a chance of reaching them via last_hops though,
2021 // so don't yet fail the payment here.
2022 // If not, targets.pop() will not even let us enter the loop in step 2.
2025 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
2030 // If a caller provided us with last hops, add them to routing targets. Since this happens
2031 // earlier than general path finding, they will be somewhat prioritized, although currently
2032 // it matters only if the fees are exactly the same.
2033 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2034 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2035 let have_intro_node_in_graph =
2036 // Only add the hops in this route to our candidate set if either
2037 // we have a direct channel to the first hop or the first hop is
2038 // in the regular network graph.
2039 first_hop_targets.get(&intro_node_id).is_some() ||
2040 network_nodes.get(&intro_node_id).is_some();
2041 if !have_intro_node_in_graph { continue }
2042 let candidate = if hint.1.blinded_hops.len() == 1 {
2043 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
2044 } else { CandidateRouteHop::Blinded { hint, hint_idx } };
2045 let mut path_contribution_msat = path_value_msat;
2046 if let Some(hop_used_msat) = add_entry!(candidate, intro_node_id, maybe_dummy_payee_node_id,
2047 0, path_contribution_msat, 0, 0_u64, 0, 0)
2049 path_contribution_msat = hop_used_msat;
2051 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2052 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2054 for details in first_channels {
2055 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2056 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2060 add_entry!(first_hop_candidate, our_node_id, intro_node_id, blinded_path_fee,
2061 path_contribution_msat, candidate.htlc_minimum_msat(), 0_u64,
2062 candidate.cltv_expiry_delta(),
2063 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2067 for route in payment_params.payee.unblinded_route_hints().iter()
2068 .filter(|route| !route.0.is_empty())
2070 let first_hop_in_route = &(route.0)[0];
2071 let have_hop_src_in_graph =
2072 // Only add the hops in this route to our candidate set if either
2073 // we have a direct channel to the first hop or the first hop is
2074 // in the regular network graph.
2075 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
2076 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
2077 if have_hop_src_in_graph {
2078 // We start building the path from reverse, i.e., from payee
2079 // to the first RouteHintHop in the path.
2080 let hop_iter = route.0.iter().rev();
2081 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2082 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2083 let mut hop_used = true;
2084 let mut aggregate_next_hops_fee_msat: u64 = 0;
2085 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2086 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2087 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2088 let mut aggregate_next_hops_path_length: u8 = 0;
2089 let mut aggregate_path_contribution_msat = path_value_msat;
2091 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2092 let source = NodeId::from_pubkey(&hop.src_node_id);
2093 let target = NodeId::from_pubkey(&prev_hop_id);
2094 let candidate = network_channels
2095 .get(&hop.short_channel_id)
2096 .and_then(|channel| channel.as_directed_to(&target))
2097 .map(|(info, _)| CandidateRouteHop::PublicHop {
2099 short_channel_id: hop.short_channel_id,
2101 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
2103 if let Some(hop_used_msat) = add_entry!(candidate, source, target,
2104 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2105 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2106 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2108 aggregate_path_contribution_msat = hop_used_msat;
2110 // If this hop was not used then there is no use checking the preceding
2111 // hops in the RouteHint. We can break by just searching for a direct
2112 // channel between last checked hop and first_hop_targets.
2116 let used_liquidity_msat = used_liquidities
2117 .get(&candidate.id(source < target)).copied()
2119 let channel_usage = ChannelUsage {
2120 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2121 inflight_htlc_msat: used_liquidity_msat,
2122 effective_capacity: candidate.effective_capacity(),
2124 let channel_penalty_msat = scorer.channel_penalty_msat(
2125 hop.short_channel_id, &source, &target, channel_usage, score_params
2127 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2128 .saturating_add(channel_penalty_msat);
2130 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2131 .saturating_add(hop.cltv_expiry_delta as u32);
2133 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2136 // Searching for a direct channel between last checked hop and first_hop_targets
2137 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&prev_hop_id)) {
2138 sort_first_hop_channels(first_channels, &used_liquidities,
2139 recommended_value_msat, our_node_pubkey);
2140 for details in first_channels {
2141 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2142 add_entry!(first_hop_candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
2143 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2144 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2145 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2153 // In the next values of the iterator, the aggregate fees already reflects
2154 // the sum of value sent from payer (final_value_msat) and routing fees
2155 // for the last node in the RouteHint. We need to just add the fees to
2156 // route through the current node so that the preceding node (next iteration)
2158 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2159 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2160 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2162 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
2163 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
2164 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
2165 .checked_add(hop_htlc_minimum_msat_inc);
2166 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
2168 if idx == route.0.len() - 1 {
2169 // The last hop in this iterator is the first hop in
2170 // overall RouteHint.
2171 // If this hop connects to a node with which we have a direct channel,
2172 // ignore the network graph and, if the last hop was added, add our
2173 // direct channel to the candidate set.
2175 // Note that we *must* check if the last hop was added as `add_entry`
2176 // always assumes that the third argument is a node to which we have a
2178 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2179 sort_first_hop_channels(first_channels, &used_liquidities,
2180 recommended_value_msat, our_node_pubkey);
2181 for details in first_channels {
2182 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2183 add_entry!(first_hop_candidate, our_node_id,
2184 NodeId::from_pubkey(&hop.src_node_id),
2185 aggregate_next_hops_fee_msat,
2186 aggregate_path_contribution_msat,
2187 aggregate_next_hops_path_htlc_minimum_msat,
2188 aggregate_next_hops_path_penalty_msat,
2189 aggregate_next_hops_cltv_delta,
2190 aggregate_next_hops_path_length);
2198 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2200 // At this point, targets are filled with the data from first and
2201 // last hops communicated by the caller, and the payment receiver.
2202 let mut found_new_path = false;
2205 // If this loop terminates due the exhaustion of targets, two situations are possible:
2206 // - not enough outgoing liquidity:
2207 // 0 < already_collected_value_msat < final_value_msat
2208 // - enough outgoing liquidity:
2209 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2210 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2211 // paths_collection will be stopped because found_new_path==false.
2212 // This is not necessarily a routing failure.
2213 '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() {
2215 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2216 // traversing the graph and arrange the path out of what we found.
2217 if node_id == our_node_id {
2218 let mut new_entry = dist.remove(&our_node_id).unwrap();
2219 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2222 let mut features_set = false;
2223 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
2224 for details in first_channels {
2225 if let Some(scid) = ordered_hops.last().unwrap().0.candidate.short_channel_id() {
2226 if details.get_outbound_payment_scid().unwrap() == scid {
2227 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2228 features_set = true;
2235 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
2236 if let Some(node_info) = node.announcement_info.as_ref() {
2237 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2239 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2242 // We can fill in features for everything except hops which were
2243 // provided via the invoice we're paying. We could guess based on the
2244 // recipient's features but for now we simply avoid guessing at all.
2248 // Means we succesfully traversed from the payer to the payee, now
2249 // save this path for the payment route. Also, update the liquidity
2250 // remaining on the used hops, so that we take them into account
2251 // while looking for more paths.
2252 if ordered_hops.last().unwrap().0.node_id == maybe_dummy_payee_node_id {
2256 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
2257 Some(payment_hop) => payment_hop,
2258 // We can't arrive at None because, if we ever add an entry to targets,
2259 // we also fill in the entry in dist (see add_entry!).
2260 None => unreachable!(),
2262 // We "propagate" the fees one hop backward (topologically) here,
2263 // so that fees paid for a HTLC forwarding on the current channel are
2264 // associated with the previous channel (where they will be subtracted).
2265 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2266 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2268 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2269 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2271 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2272 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2274 let mut payment_path = PaymentPath {hops: ordered_hops};
2276 // We could have possibly constructed a slightly inconsistent path: since we reduce
2277 // value being transferred along the way, we could have violated htlc_minimum_msat
2278 // on some channels we already passed (assuming dest->source direction). Here, we
2279 // recompute the fees again, so that if that's the case, we match the currently
2280 // underpaid htlc_minimum_msat with fees.
2281 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2282 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
2283 payment_path.update_value_and_recompute_fees(value_contribution_msat);
2285 // Since a path allows to transfer as much value as
2286 // the smallest channel it has ("bottleneck"), we should recompute
2287 // the fees so sender HTLC don't overpay fees when traversing
2288 // larger channels than the bottleneck. This may happen because
2289 // when we were selecting those channels we were not aware how much value
2290 // this path will transfer, and the relative fee for them
2291 // might have been computed considering a larger value.
2292 // Remember that we used these channels so that we don't rely
2293 // on the same liquidity in future paths.
2294 let mut prevented_redundant_path_selection = false;
2295 let prev_hop_iter = core::iter::once(&our_node_id)
2296 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
2297 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
2298 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2299 let used_liquidity_msat = used_liquidities
2300 .entry(hop.candidate.id(*prev_hop < hop.node_id))
2301 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2302 .or_insert(spent_on_hop_msat);
2303 let hop_capacity = hop.candidate.effective_capacity();
2304 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2305 if *used_liquidity_msat == hop_max_msat {
2306 // If this path used all of this channel's available liquidity, we know
2307 // this path will not be selected again in the next loop iteration.
2308 prevented_redundant_path_selection = true;
2310 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2312 if !prevented_redundant_path_selection {
2313 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2314 // we'll probably end up picking the same path again on the next iteration.
2315 // Decrease the available liquidity of a hop in the middle of the path.
2316 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2317 let exhausted = u64::max_value();
2318 log_trace!(logger, "Disabling route candidate {} for future path building iterations to
2319 avoid duplicates.", LoggedCandidateHop(victim_candidate));
2320 *used_liquidities.entry(victim_candidate.id(false)).or_default() = exhausted;
2321 *used_liquidities.entry(victim_candidate.id(true)).or_default() = exhausted;
2324 // Track the total amount all our collected paths allow to send so that we know
2325 // when to stop looking for more paths
2326 already_collected_value_msat += value_contribution_msat;
2328 payment_paths.push(payment_path);
2329 found_new_path = true;
2330 break 'path_construction;
2333 // If we found a path back to the payee, we shouldn't try to process it again. This is
2334 // the equivalent of the `elem.was_processed` check in
2335 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2336 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2338 // Otherwise, since the current target node is not us,
2339 // keep "unrolling" the payment graph from payee to payer by
2340 // finding a way to reach the current target from the payer side.
2341 match network_nodes.get(&node_id) {
2344 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2345 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2346 total_cltv_delta, path_length_to_node);
2352 if !found_new_path && channel_saturation_pow_half != 0 {
2353 channel_saturation_pow_half = 0;
2354 continue 'paths_collection;
2356 // If we don't support MPP, no use trying to gather more value ever.
2357 break 'paths_collection;
2361 // Stop either when the recommended value is reached or if no new path was found in this
2363 // In the latter case, making another path finding attempt won't help,
2364 // because we deterministically terminated the search due to low liquidity.
2365 if !found_new_path && channel_saturation_pow_half != 0 {
2366 channel_saturation_pow_half = 0;
2367 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2368 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2369 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2370 break 'paths_collection;
2371 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2372 // Further, if this was our first walk of the graph, and we weren't limited by an
2373 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2374 // limited by an htlc_minimum_msat value, find another path with a higher value,
2375 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2376 // still keeping a lower total fee than this path.
2377 if !hit_minimum_limit {
2378 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2379 break 'paths_collection;
2381 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
2382 path_value_msat = recommended_value_msat;
2386 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2387 num_ignored_cltv_delta_limit + num_ignored_previously_failed;
2388 if num_ignored_total > 0 {
2389 log_trace!(logger, "Ignored {} candidate hops due to insufficient value contribution, {} due to path length limit, {} due to CLTV delta limit, {} due to previous payment failure. Total: {} ignored candidates.", num_ignored_value_contribution, num_ignored_path_length_limit, num_ignored_cltv_delta_limit, num_ignored_previously_failed, num_ignored_total);
2393 if payment_paths.len() == 0 {
2394 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2397 if already_collected_value_msat < final_value_msat {
2398 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2402 let mut selected_route = payment_paths;
2404 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2405 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2407 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2408 // the value they contribute towards the payment amount.
2409 // We sort in descending order as we will remove from the front in `retain`, next.
2410 selected_route.sort_unstable_by(|a, b|
2411 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2412 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2415 // We should make sure that at least 1 path left.
2416 let mut paths_left = selected_route.len();
2417 selected_route.retain(|path| {
2418 if paths_left == 1 {
2421 let path_value_msat = path.get_value_msat();
2422 if path_value_msat <= overpaid_value_msat {
2423 overpaid_value_msat -= path_value_msat;
2429 debug_assert!(selected_route.len() > 0);
2431 if overpaid_value_msat != 0 {
2433 // Now, subtract the remaining overpaid value from the most-expensive path.
2434 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2435 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2436 selected_route.sort_unstable_by(|a, b| {
2437 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2438 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2439 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2441 let expensive_payment_path = selected_route.first_mut().unwrap();
2443 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2444 // can't go negative.
2445 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2446 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2450 // Sort by the path itself and combine redundant paths.
2451 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2452 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2454 selected_route.sort_unstable_by_key(|path| {
2455 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2456 debug_assert!(path.hops.len() <= key.len());
2457 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id(true)).zip(key.iter_mut()) {
2462 for idx in 0..(selected_route.len() - 1) {
2463 if idx + 1 >= selected_route.len() { break; }
2464 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id)),
2465 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id))) {
2466 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2467 selected_route[idx].update_value_and_recompute_fees(new_value);
2468 selected_route.remove(idx + 1);
2472 let mut paths = Vec::new();
2473 for payment_path in selected_route {
2474 let mut hops = Vec::with_capacity(payment_path.hops.len());
2475 for (hop, node_features) in payment_path.hops.iter()
2476 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2478 hops.push(RouteHop {
2479 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)})?,
2480 node_features: node_features.clone(),
2481 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2482 channel_features: hop.candidate.features(),
2483 fee_msat: hop.fee_msat,
2484 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2487 let mut final_cltv_delta = final_cltv_expiry_delta;
2488 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2489 if let Some(blinded_path) = h.candidate.blinded_path() {
2490 final_cltv_delta = h.candidate.cltv_expiry_delta();
2492 hops: blinded_path.blinded_hops.clone(),
2493 blinding_point: blinded_path.blinding_point,
2494 excess_final_cltv_expiry_delta: 0,
2495 final_value_msat: h.fee_msat,
2499 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2500 // applicable for the previous hop.
2501 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2502 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2505 paths.push(Path { hops, blinded_tail });
2507 // Make sure we would never create a route with more paths than we allow.
2508 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2510 if let Some(node_features) = payment_params.payee.node_features() {
2511 for path in paths.iter_mut() {
2512 path.hops.last_mut().unwrap().node_features = node_features.clone();
2516 let route = Route { paths, route_params: Some(route_params.clone()) };
2517 log_info!(logger, "Got route: {}", log_route!(route));
2521 // When an adversarial intermediary node observes a payment, it may be able to infer its
2522 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2523 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2524 // payment path by adding a randomized 'shadow route' offset to the final hop.
2525 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2526 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2528 let network_channels = network_graph.channels();
2529 let network_nodes = network_graph.nodes();
2531 for path in route.paths.iter_mut() {
2532 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2534 // Remember the last three nodes of the random walk and avoid looping back on them.
2535 // Init with the last three nodes from the actual path, if possible.
2536 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2537 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2538 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2540 // Choose the last publicly known node as the starting point for the random walk.
2541 let mut cur_hop: Option<NodeId> = None;
2542 let mut path_nonce = [0u8; 12];
2543 if let Some(starting_hop) = path.hops.iter().rev()
2544 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2545 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2546 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2549 // Init PRNG with the path-dependant nonce, which is static for private paths.
2550 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2551 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2553 // Pick a random path length in [1 .. 3]
2554 prng.process_in_place(&mut random_path_bytes);
2555 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2557 for random_hop in 0..random_walk_length {
2558 // If we don't find a suitable offset in the public network graph, we default to
2559 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2560 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2562 if let Some(cur_node_id) = cur_hop {
2563 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2564 // Randomly choose the next unvisited hop.
2565 prng.process_in_place(&mut random_path_bytes);
2566 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2567 .checked_rem(cur_node.channels.len())
2568 .and_then(|index| cur_node.channels.get(index))
2569 .and_then(|id| network_channels.get(id)) {
2570 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2571 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2572 nodes_to_avoid[random_hop] = *next_id;
2573 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2574 cur_hop = Some(*next_id);
2581 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2582 .checked_add(random_hop_offset)
2583 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2586 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2587 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2588 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2590 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2591 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2592 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2593 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2594 max_path_offset = cmp::max(
2595 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2596 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2597 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2599 // Add 'shadow' CLTV offset to the final hop
2600 if let Some(tail) = path.blinded_tail.as_mut() {
2601 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2602 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2604 if let Some(last_hop) = path.hops.last_mut() {
2605 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2606 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2611 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2612 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2614 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2615 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2616 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2617 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2618 ) -> Result<Route, LightningError>
2619 where L::Target: Logger, GL::Target: Logger {
2620 let graph_lock = network_graph.read_only();
2621 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
2622 &graph_lock, logger, random_seed_bytes)?;
2623 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2627 fn build_route_from_hops_internal<L: Deref>(
2628 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2629 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
2630 ) -> Result<Route, LightningError> where L::Target: Logger {
2633 our_node_id: NodeId,
2634 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2637 impl ScoreLookUp for HopScorer {
2638 type ScoreParams = ();
2639 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2640 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2642 let mut cur_id = self.our_node_id;
2643 for i in 0..self.hop_ids.len() {
2644 if let Some(next_id) = self.hop_ids[i] {
2645 if cur_id == *source && next_id == *target {
2657 impl<'a> Writeable for HopScorer {
2659 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2664 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2665 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2668 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2669 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2670 for i in 0..hops.len() {
2671 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2674 let scorer = HopScorer { our_node_id, hop_ids };
2676 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &(), random_seed_bytes)
2681 use crate::blinded_path::{BlindedHop, BlindedPath};
2682 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2683 use crate::routing::utxo::UtxoResult;
2684 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2685 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2686 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters};
2687 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2688 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2689 use crate::chain::transaction::OutPoint;
2690 use crate::sign::EntropySource;
2691 use crate::ln::ChannelId;
2692 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2693 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2694 use crate::ln::channelmanager;
2695 use crate::offers::invoice::BlindedPayInfo;
2696 use crate::util::config::UserConfig;
2697 use crate::util::test_utils as ln_test_utils;
2698 use crate::util::chacha20::ChaCha20;
2699 use crate::util::ser::{Readable, Writeable};
2701 use crate::util::ser::Writer;
2703 use bitcoin::hashes::Hash;
2704 use bitcoin::network::constants::Network;
2705 use bitcoin::blockdata::constants::genesis_block;
2706 use bitcoin::blockdata::script::Builder;
2707 use bitcoin::blockdata::opcodes;
2708 use bitcoin::blockdata::transaction::TxOut;
2712 use bitcoin::secp256k1::{PublicKey,SecretKey};
2713 use bitcoin::secp256k1::Secp256k1;
2715 use crate::io::Cursor;
2716 use crate::prelude::*;
2717 use crate::sync::Arc;
2719 use core::convert::TryInto;
2721 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2722 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2723 channelmanager::ChannelDetails {
2724 channel_id: ChannelId::new_zero(),
2725 counterparty: channelmanager::ChannelCounterparty {
2728 unspendable_punishment_reserve: 0,
2729 forwarding_info: None,
2730 outbound_htlc_minimum_msat: None,
2731 outbound_htlc_maximum_msat: None,
2733 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2736 outbound_scid_alias: None,
2737 inbound_scid_alias: None,
2738 channel_value_satoshis: 0,
2740 outbound_capacity_msat,
2741 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2742 next_outbound_htlc_minimum_msat: 0,
2743 inbound_capacity_msat: 42,
2744 unspendable_punishment_reserve: None,
2745 confirmations_required: None,
2746 confirmations: None,
2747 force_close_spend_delay: None,
2748 is_outbound: true, is_channel_ready: true,
2749 is_usable: true, is_public: true,
2750 inbound_htlc_minimum_msat: None,
2751 inbound_htlc_maximum_msat: None,
2753 feerate_sat_per_1000_weight: None,
2754 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
2759 fn simple_route_test() {
2760 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2761 let (_, our_id, _, 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 let route_params = RouteParameters::from_payment_params_and_value(
2770 payment_params.clone(), 0);
2771 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2772 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer, &(),
2773 &random_seed_bytes) {
2774 assert_eq!(err, "Cannot send a payment of 0 msat");
2775 } else { panic!(); }
2777 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
2778 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2779 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2780 assert_eq!(route.paths[0].hops.len(), 2);
2782 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2783 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2784 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2785 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2786 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2787 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2789 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2790 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2791 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2792 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2793 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2794 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2798 fn invalid_first_hop_test() {
2799 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2800 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2801 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2802 let scorer = ln_test_utils::TestScorer::new();
2803 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2804 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2806 // Simple route to 2 via 1
2808 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2810 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
2811 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2812 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
2813 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2814 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2815 } else { panic!(); }
2817 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2818 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2819 assert_eq!(route.paths[0].hops.len(), 2);
2823 fn htlc_minimum_test() {
2824 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2825 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2826 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2827 let scorer = ln_test_utils::TestScorer::new();
2828 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2829 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2831 // Simple route to 2 via 1
2833 // Disable other paths
2834 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2835 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2836 short_channel_id: 12,
2838 flags: 2, // to disable
2839 cltv_expiry_delta: 0,
2840 htlc_minimum_msat: 0,
2841 htlc_maximum_msat: MAX_VALUE_MSAT,
2843 fee_proportional_millionths: 0,
2844 excess_data: Vec::new()
2846 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2847 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2848 short_channel_id: 3,
2850 flags: 2, // to disable
2851 cltv_expiry_delta: 0,
2852 htlc_minimum_msat: 0,
2853 htlc_maximum_msat: MAX_VALUE_MSAT,
2855 fee_proportional_millionths: 0,
2856 excess_data: Vec::new()
2858 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2859 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2860 short_channel_id: 13,
2862 flags: 2, // to disable
2863 cltv_expiry_delta: 0,
2864 htlc_minimum_msat: 0,
2865 htlc_maximum_msat: MAX_VALUE_MSAT,
2867 fee_proportional_millionths: 0,
2868 excess_data: Vec::new()
2870 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2871 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2872 short_channel_id: 6,
2874 flags: 2, // to disable
2875 cltv_expiry_delta: 0,
2876 htlc_minimum_msat: 0,
2877 htlc_maximum_msat: MAX_VALUE_MSAT,
2879 fee_proportional_millionths: 0,
2880 excess_data: Vec::new()
2882 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2883 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2884 short_channel_id: 7,
2886 flags: 2, // to disable
2887 cltv_expiry_delta: 0,
2888 htlc_minimum_msat: 0,
2889 htlc_maximum_msat: MAX_VALUE_MSAT,
2891 fee_proportional_millionths: 0,
2892 excess_data: Vec::new()
2895 // Check against amount_to_transfer_over_msat.
2896 // Set minimal HTLC of 200_000_000 msat.
2897 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2898 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2899 short_channel_id: 2,
2902 cltv_expiry_delta: 0,
2903 htlc_minimum_msat: 200_000_000,
2904 htlc_maximum_msat: MAX_VALUE_MSAT,
2906 fee_proportional_millionths: 0,
2907 excess_data: Vec::new()
2910 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2912 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2913 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2914 short_channel_id: 4,
2917 cltv_expiry_delta: 0,
2918 htlc_minimum_msat: 0,
2919 htlc_maximum_msat: 199_999_999,
2921 fee_proportional_millionths: 0,
2922 excess_data: Vec::new()
2925 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2926 let route_params = RouteParameters::from_payment_params_and_value(
2927 payment_params, 199_999_999);
2928 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2929 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer, &(),
2930 &random_seed_bytes) {
2931 assert_eq!(err, "Failed to find a path to the given destination");
2932 } else { panic!(); }
2934 // Lift the restriction on the first hop.
2935 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2936 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2937 short_channel_id: 2,
2940 cltv_expiry_delta: 0,
2941 htlc_minimum_msat: 0,
2942 htlc_maximum_msat: MAX_VALUE_MSAT,
2944 fee_proportional_millionths: 0,
2945 excess_data: Vec::new()
2948 // A payment above the minimum should pass
2949 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2950 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2951 assert_eq!(route.paths[0].hops.len(), 2);
2955 fn htlc_minimum_overpay_test() {
2956 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2957 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2958 let config = UserConfig::default();
2959 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
2960 let scorer = ln_test_utils::TestScorer::new();
2961 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2962 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2964 // A route to node#2 via two paths.
2965 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2966 // Thus, they can't send 60 without overpaying.
2967 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2968 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2969 short_channel_id: 2,
2972 cltv_expiry_delta: 0,
2973 htlc_minimum_msat: 35_000,
2974 htlc_maximum_msat: 40_000,
2976 fee_proportional_millionths: 0,
2977 excess_data: Vec::new()
2979 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2980 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2981 short_channel_id: 12,
2984 cltv_expiry_delta: 0,
2985 htlc_minimum_msat: 35_000,
2986 htlc_maximum_msat: 40_000,
2988 fee_proportional_millionths: 0,
2989 excess_data: Vec::new()
2993 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2994 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2995 short_channel_id: 13,
2998 cltv_expiry_delta: 0,
2999 htlc_minimum_msat: 0,
3000 htlc_maximum_msat: MAX_VALUE_MSAT,
3002 fee_proportional_millionths: 0,
3003 excess_data: Vec::new()
3005 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3006 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3007 short_channel_id: 4,
3010 cltv_expiry_delta: 0,
3011 htlc_minimum_msat: 0,
3012 htlc_maximum_msat: MAX_VALUE_MSAT,
3014 fee_proportional_millionths: 0,
3015 excess_data: Vec::new()
3018 // Disable other paths
3019 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3020 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3021 short_channel_id: 1,
3023 flags: 2, // to disable
3024 cltv_expiry_delta: 0,
3025 htlc_minimum_msat: 0,
3026 htlc_maximum_msat: MAX_VALUE_MSAT,
3028 fee_proportional_millionths: 0,
3029 excess_data: Vec::new()
3032 let route_params = RouteParameters::from_payment_params_and_value(
3033 payment_params.clone(), 60_000);
3034 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3035 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3036 // Overpay fees to hit htlc_minimum_msat.
3037 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3038 // TODO: this could be better balanced to overpay 10k and not 15k.
3039 assert_eq!(overpaid_fees, 15_000);
3041 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3042 // while taking even more fee to match htlc_minimum_msat.
3043 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3044 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3045 short_channel_id: 12,
3048 cltv_expiry_delta: 0,
3049 htlc_minimum_msat: 65_000,
3050 htlc_maximum_msat: 80_000,
3052 fee_proportional_millionths: 0,
3053 excess_data: Vec::new()
3055 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3056 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3057 short_channel_id: 2,
3060 cltv_expiry_delta: 0,
3061 htlc_minimum_msat: 0,
3062 htlc_maximum_msat: MAX_VALUE_MSAT,
3064 fee_proportional_millionths: 0,
3065 excess_data: Vec::new()
3067 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3068 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3069 short_channel_id: 4,
3072 cltv_expiry_delta: 0,
3073 htlc_minimum_msat: 0,
3074 htlc_maximum_msat: MAX_VALUE_MSAT,
3076 fee_proportional_millionths: 100_000,
3077 excess_data: Vec::new()
3080 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3081 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3082 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3083 assert_eq!(route.paths.len(), 1);
3084 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3085 let fees = route.paths[0].hops[0].fee_msat;
3086 assert_eq!(fees, 5_000);
3088 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3089 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3090 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3091 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3092 // the other channel.
3093 assert_eq!(route.paths.len(), 1);
3094 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3095 let fees = route.paths[0].hops[0].fee_msat;
3096 assert_eq!(fees, 5_000);
3100 fn disable_channels_test() {
3101 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3102 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3103 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3104 let scorer = ln_test_utils::TestScorer::new();
3105 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3106 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3108 // // Disable channels 4 and 12 by flags=2
3109 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3110 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3111 short_channel_id: 4,
3113 flags: 2, // to disable
3114 cltv_expiry_delta: 0,
3115 htlc_minimum_msat: 0,
3116 htlc_maximum_msat: MAX_VALUE_MSAT,
3118 fee_proportional_millionths: 0,
3119 excess_data: Vec::new()
3121 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3122 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3123 short_channel_id: 12,
3125 flags: 2, // to disable
3126 cltv_expiry_delta: 0,
3127 htlc_minimum_msat: 0,
3128 htlc_maximum_msat: MAX_VALUE_MSAT,
3130 fee_proportional_millionths: 0,
3131 excess_data: Vec::new()
3134 // If all the channels require some features we don't understand, route should fail
3135 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3136 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3137 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer, &(),
3138 &random_seed_bytes) {
3139 assert_eq!(err, "Failed to find a path to the given destination");
3140 } else { panic!(); }
3142 // If we specify a channel to node7, that overrides our local channel view and that gets used
3143 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3144 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3145 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3146 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
3147 &random_seed_bytes).unwrap();
3148 assert_eq!(route.paths[0].hops.len(), 2);
3150 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3151 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3152 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3153 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3154 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3155 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3157 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3158 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3159 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3160 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3161 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3162 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3166 fn disable_node_test() {
3167 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3168 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3169 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3170 let scorer = ln_test_utils::TestScorer::new();
3171 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3172 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3174 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3175 let mut unknown_features = NodeFeatures::empty();
3176 unknown_features.set_unknown_feature_required();
3177 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3178 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3179 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3181 // If all nodes require some features we don't understand, route should fail
3182 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3183 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3184 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer, &(),
3185 &random_seed_bytes) {
3186 assert_eq!(err, "Failed to find a path to the given destination");
3187 } else { panic!(); }
3189 // If we specify a channel to node7, that overrides our local channel view and that gets used
3190 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3191 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3192 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3193 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
3194 &random_seed_bytes).unwrap();
3195 assert_eq!(route.paths[0].hops.len(), 2);
3197 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3198 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3199 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3200 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3201 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3202 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3204 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3205 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3206 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3207 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3208 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3209 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3211 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3212 // naively) assume that the user checked the feature bits on the invoice, which override
3213 // the node_announcement.
3217 fn our_chans_test() {
3218 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3219 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3220 let scorer = ln_test_utils::TestScorer::new();
3221 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3222 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3224 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3225 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3226 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3227 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3228 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3229 assert_eq!(route.paths[0].hops.len(), 3);
3231 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3232 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3233 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3234 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3235 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3236 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3238 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3239 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3240 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3241 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3242 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3243 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3245 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3246 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3247 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3248 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3249 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3250 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3252 // If we specify a channel to node7, that overrides our local channel view and that gets used
3253 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3254 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3255 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3256 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3257 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3258 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
3259 &random_seed_bytes).unwrap();
3260 assert_eq!(route.paths[0].hops.len(), 2);
3262 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3263 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3264 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3265 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3266 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3267 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3269 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3270 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3271 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3272 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3273 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3274 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3277 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3278 let zero_fees = RoutingFees {
3280 proportional_millionths: 0,
3282 vec![RouteHint(vec![RouteHintHop {
3283 src_node_id: nodes[3],
3284 short_channel_id: 8,
3286 cltv_expiry_delta: (8 << 4) | 1,
3287 htlc_minimum_msat: None,
3288 htlc_maximum_msat: None,
3290 ]), RouteHint(vec![RouteHintHop {
3291 src_node_id: nodes[4],
3292 short_channel_id: 9,
3295 proportional_millionths: 0,
3297 cltv_expiry_delta: (9 << 4) | 1,
3298 htlc_minimum_msat: None,
3299 htlc_maximum_msat: None,
3300 }]), RouteHint(vec![RouteHintHop {
3301 src_node_id: nodes[5],
3302 short_channel_id: 10,
3304 cltv_expiry_delta: (10 << 4) | 1,
3305 htlc_minimum_msat: None,
3306 htlc_maximum_msat: None,
3310 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3311 let zero_fees = RoutingFees {
3313 proportional_millionths: 0,
3315 vec![RouteHint(vec![RouteHintHop {
3316 src_node_id: nodes[2],
3317 short_channel_id: 5,
3320 proportional_millionths: 0,
3322 cltv_expiry_delta: (5 << 4) | 1,
3323 htlc_minimum_msat: None,
3324 htlc_maximum_msat: None,
3326 src_node_id: nodes[3],
3327 short_channel_id: 8,
3329 cltv_expiry_delta: (8 << 4) | 1,
3330 htlc_minimum_msat: None,
3331 htlc_maximum_msat: None,
3333 ]), RouteHint(vec![RouteHintHop {
3334 src_node_id: nodes[4],
3335 short_channel_id: 9,
3338 proportional_millionths: 0,
3340 cltv_expiry_delta: (9 << 4) | 1,
3341 htlc_minimum_msat: None,
3342 htlc_maximum_msat: None,
3343 }]), RouteHint(vec![RouteHintHop {
3344 src_node_id: nodes[5],
3345 short_channel_id: 10,
3347 cltv_expiry_delta: (10 << 4) | 1,
3348 htlc_minimum_msat: None,
3349 htlc_maximum_msat: None,
3354 fn partial_route_hint_test() {
3355 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3356 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3357 let scorer = ln_test_utils::TestScorer::new();
3358 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3359 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3361 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3362 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3363 // RouteHint may be partially used by the algo to build the best path.
3365 // First check that last hop can't have its source as the payee.
3366 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3367 src_node_id: nodes[6],
3368 short_channel_id: 8,
3371 proportional_millionths: 0,
3373 cltv_expiry_delta: (8 << 4) | 1,
3374 htlc_minimum_msat: None,
3375 htlc_maximum_msat: None,
3378 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3379 invalid_last_hops.push(invalid_last_hop);
3381 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3382 .with_route_hints(invalid_last_hops).unwrap();
3383 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3384 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3385 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer, &(),
3386 &random_seed_bytes) {
3387 assert_eq!(err, "Route hint cannot have the payee as the source.");
3388 } else { panic!(); }
3391 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3392 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3393 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3394 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3395 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3396 assert_eq!(route.paths[0].hops.len(), 5);
3398 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3399 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3400 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3401 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3402 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3403 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3405 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3406 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3407 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3408 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3409 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3410 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3412 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3413 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3414 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3415 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3416 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3417 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3419 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3420 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3421 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3422 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3423 // If we have a peer in the node map, we'll use their features here since we don't have
3424 // a way of figuring out their features from the invoice:
3425 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3426 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3428 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3429 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3430 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3431 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3432 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3433 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3436 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3437 let zero_fees = RoutingFees {
3439 proportional_millionths: 0,
3441 vec![RouteHint(vec![RouteHintHop {
3442 src_node_id: nodes[3],
3443 short_channel_id: 8,
3445 cltv_expiry_delta: (8 << 4) | 1,
3446 htlc_minimum_msat: None,
3447 htlc_maximum_msat: None,
3448 }]), RouteHint(vec![
3450 ]), RouteHint(vec![RouteHintHop {
3451 src_node_id: nodes[5],
3452 short_channel_id: 10,
3454 cltv_expiry_delta: (10 << 4) | 1,
3455 htlc_minimum_msat: None,
3456 htlc_maximum_msat: None,
3461 fn ignores_empty_last_hops_test() {
3462 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3463 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3464 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3465 let scorer = ln_test_utils::TestScorer::new();
3466 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3467 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3469 // Test handling of an empty RouteHint passed in Invoice.
3470 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3471 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3472 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3473 assert_eq!(route.paths[0].hops.len(), 5);
3475 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3476 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3477 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3478 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3479 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3480 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3482 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3483 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3484 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3485 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3486 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3487 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3489 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3490 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3491 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3492 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3493 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3494 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3496 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3497 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3498 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3499 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3500 // If we have a peer in the node map, we'll use their features here since we don't have
3501 // a way of figuring out their features from the invoice:
3502 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3503 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3505 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3506 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3507 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3508 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3509 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3510 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3513 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3515 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3516 let zero_fees = RoutingFees {
3518 proportional_millionths: 0,
3520 vec![RouteHint(vec![RouteHintHop {
3521 src_node_id: hint_hops[0],
3522 short_channel_id: 0xff00,
3525 proportional_millionths: 0,
3527 cltv_expiry_delta: (5 << 4) | 1,
3528 htlc_minimum_msat: None,
3529 htlc_maximum_msat: None,
3531 src_node_id: hint_hops[1],
3532 short_channel_id: 0xff01,
3534 cltv_expiry_delta: (8 << 4) | 1,
3535 htlc_minimum_msat: None,
3536 htlc_maximum_msat: None,
3541 fn multi_hint_last_hops_test() {
3542 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3543 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3544 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3545 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3546 let scorer = ln_test_utils::TestScorer::new();
3547 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3548 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3549 // Test through channels 2, 3, 0xff00, 0xff01.
3550 // Test shows that multiple hop hints are considered.
3552 // Disabling channels 6 & 7 by flags=2
3553 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3554 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3555 short_channel_id: 6,
3557 flags: 2, // to disable
3558 cltv_expiry_delta: 0,
3559 htlc_minimum_msat: 0,
3560 htlc_maximum_msat: MAX_VALUE_MSAT,
3562 fee_proportional_millionths: 0,
3563 excess_data: Vec::new()
3565 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3566 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3567 short_channel_id: 7,
3569 flags: 2, // to disable
3570 cltv_expiry_delta: 0,
3571 htlc_minimum_msat: 0,
3572 htlc_maximum_msat: MAX_VALUE_MSAT,
3574 fee_proportional_millionths: 0,
3575 excess_data: Vec::new()
3578 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3579 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3580 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3581 assert_eq!(route.paths[0].hops.len(), 4);
3583 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3584 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3585 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3586 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3587 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3588 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3590 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3591 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3592 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3593 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3594 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3595 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3597 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3598 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3599 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3600 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3601 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3602 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3604 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3605 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3606 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3607 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3608 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3609 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3613 fn private_multi_hint_last_hops_test() {
3614 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3615 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3617 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3618 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3620 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3621 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3622 let scorer = ln_test_utils::TestScorer::new();
3623 // Test through channels 2, 3, 0xff00, 0xff01.
3624 // Test shows that multiple hop hints are considered.
3626 // Disabling channels 6 & 7 by flags=2
3627 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3628 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3629 short_channel_id: 6,
3631 flags: 2, // to disable
3632 cltv_expiry_delta: 0,
3633 htlc_minimum_msat: 0,
3634 htlc_maximum_msat: MAX_VALUE_MSAT,
3636 fee_proportional_millionths: 0,
3637 excess_data: Vec::new()
3639 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3640 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3641 short_channel_id: 7,
3643 flags: 2, // to disable
3644 cltv_expiry_delta: 0,
3645 htlc_minimum_msat: 0,
3646 htlc_maximum_msat: MAX_VALUE_MSAT,
3648 fee_proportional_millionths: 0,
3649 excess_data: Vec::new()
3652 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3653 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3654 Arc::clone(&logger), &scorer, &(), &[42u8; 32]).unwrap();
3655 assert_eq!(route.paths[0].hops.len(), 4);
3657 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3658 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3659 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3660 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3661 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3662 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3664 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3665 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3666 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3667 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3668 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3669 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3671 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3672 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3673 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3674 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3675 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3676 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3678 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3679 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3680 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3681 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3682 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3683 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3686 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3687 let zero_fees = RoutingFees {
3689 proportional_millionths: 0,
3691 vec![RouteHint(vec![RouteHintHop {
3692 src_node_id: nodes[4],
3693 short_channel_id: 11,
3695 cltv_expiry_delta: (11 << 4) | 1,
3696 htlc_minimum_msat: None,
3697 htlc_maximum_msat: None,
3699 src_node_id: nodes[3],
3700 short_channel_id: 8,
3702 cltv_expiry_delta: (8 << 4) | 1,
3703 htlc_minimum_msat: None,
3704 htlc_maximum_msat: None,
3705 }]), RouteHint(vec![RouteHintHop {
3706 src_node_id: nodes[4],
3707 short_channel_id: 9,
3710 proportional_millionths: 0,
3712 cltv_expiry_delta: (9 << 4) | 1,
3713 htlc_minimum_msat: None,
3714 htlc_maximum_msat: None,
3715 }]), RouteHint(vec![RouteHintHop {
3716 src_node_id: nodes[5],
3717 short_channel_id: 10,
3719 cltv_expiry_delta: (10 << 4) | 1,
3720 htlc_minimum_msat: None,
3721 htlc_maximum_msat: None,
3726 fn last_hops_with_public_channel_test() {
3727 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3728 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3729 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
3730 let scorer = ln_test_utils::TestScorer::new();
3731 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3732 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3733 // This test shows that public routes can be present in the invoice
3734 // which would be handled in the same manner.
3736 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3737 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3738 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3739 assert_eq!(route.paths[0].hops.len(), 5);
3741 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3742 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3743 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3744 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3745 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3746 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3748 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3749 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3750 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3751 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3752 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3753 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3755 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3756 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3757 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3758 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3759 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3760 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3762 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3763 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3764 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3765 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3766 // If we have a peer in the node map, we'll use their features here since we don't have
3767 // a way of figuring out their features from the invoice:
3768 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3769 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3771 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3772 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3773 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3774 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3775 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3776 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 our_chans_last_hop_connect_test() {
3781 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3782 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3783 let scorer = ln_test_utils::TestScorer::new();
3784 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3785 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3787 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3788 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3789 let mut last_hops = last_hops(&nodes);
3790 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3791 .with_route_hints(last_hops.clone()).unwrap();
3792 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3793 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3794 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
3795 &random_seed_bytes).unwrap();
3796 assert_eq!(route.paths[0].hops.len(), 2);
3798 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3799 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3800 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3801 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3802 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3803 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3805 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3806 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3807 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3808 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3809 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3810 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3812 last_hops[0].0[0].fees.base_msat = 1000;
3814 // Revert to via 6 as the fee on 8 goes up
3815 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3816 .with_route_hints(last_hops).unwrap();
3817 let route_params = RouteParameters::from_payment_params_and_value(
3818 payment_params.clone(), 100);
3819 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3820 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3821 assert_eq!(route.paths[0].hops.len(), 4);
3823 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3824 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3825 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
3826 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3827 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3828 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3830 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3831 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3832 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3833 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
3834 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3835 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3837 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
3838 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3839 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3840 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3841 // If we have a peer in the node map, we'll use their features here since we don't have
3842 // a way of figuring out their features from the invoice:
3843 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3844 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3846 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3847 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3848 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3849 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3850 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3851 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3853 // ...but still use 8 for larger payments as 6 has a variable feerate
3854 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
3855 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3856 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3857 assert_eq!(route.paths[0].hops.len(), 5);
3859 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3860 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3861 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3862 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3863 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3864 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3866 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3867 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3868 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3869 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3870 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3871 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3873 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3874 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3875 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3876 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3877 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3878 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3880 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3881 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3882 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
3883 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3884 // If we have a peer in the node map, we'll use their features here since we don't have
3885 // a way of figuring out their features from the invoice:
3886 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3887 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3889 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3890 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3891 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
3892 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3893 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3894 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3897 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> {
3898 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3899 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3900 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3902 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3903 let last_hops = RouteHint(vec![RouteHintHop {
3904 src_node_id: middle_node_id,
3905 short_channel_id: 8,
3908 proportional_millionths: last_hop_fee_prop,
3910 cltv_expiry_delta: (8 << 4) | 1,
3911 htlc_minimum_msat: None,
3912 htlc_maximum_msat: last_hop_htlc_max,
3914 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
3915 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3916 let scorer = ln_test_utils::TestScorer::new();
3917 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3918 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3919 let logger = ln_test_utils::TestLogger::new();
3920 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3921 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
3922 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
3923 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &(),
3924 &random_seed_bytes);
3929 fn unannounced_path_test() {
3930 // We should be able to send a payment to a destination without any help of a routing graph
3931 // if we have a channel with a common counterparty that appears in the first and last hop
3933 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3935 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3936 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3937 assert_eq!(route.paths[0].hops.len(), 2);
3939 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
3940 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3941 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
3942 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3943 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
3944 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3946 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
3947 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3948 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
3949 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3950 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3951 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3955 fn overflow_unannounced_path_test_liquidity_underflow() {
3956 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3957 // the last-hop had a fee which overflowed a u64, we'd panic.
3958 // This was due to us adding the first-hop from us unconditionally, causing us to think
3959 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3960 // In this test, we previously hit a subtraction underflow due to having less available
3961 // liquidity at the last hop than 0.
3962 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());
3966 fn overflow_unannounced_path_test_feerate_overflow() {
3967 // This tests for the same case as above, except instead of hitting a subtraction
3968 // underflow, we hit a case where the fee charged at a hop overflowed.
3969 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());
3973 fn available_amount_while_routing_test() {
3974 // Tests whether we choose the correct available channel amount while routing.
3976 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
3977 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3978 let scorer = ln_test_utils::TestScorer::new();
3979 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3980 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3981 let config = UserConfig::default();
3982 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3984 // We will use a simple single-path route from
3985 // our node to node2 via node0: channels {1, 3}.
3987 // First disable all other paths.
3988 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3989 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3990 short_channel_id: 2,
3993 cltv_expiry_delta: 0,
3994 htlc_minimum_msat: 0,
3995 htlc_maximum_msat: 100_000,
3997 fee_proportional_millionths: 0,
3998 excess_data: Vec::new()
4000 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4001 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4002 short_channel_id: 12,
4005 cltv_expiry_delta: 0,
4006 htlc_minimum_msat: 0,
4007 htlc_maximum_msat: 100_000,
4009 fee_proportional_millionths: 0,
4010 excess_data: Vec::new()
4013 // Make the first channel (#1) very permissive,
4014 // and we will be testing all limits on the second channel.
4015 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4016 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4017 short_channel_id: 1,
4020 cltv_expiry_delta: 0,
4021 htlc_minimum_msat: 0,
4022 htlc_maximum_msat: 1_000_000_000,
4024 fee_proportional_millionths: 0,
4025 excess_data: Vec::new()
4028 // First, let's see if routing works if we have absolutely no idea about the available amount.
4029 // In this case, it should be set to 250_000 sats.
4030 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4031 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4032 short_channel_id: 3,
4035 cltv_expiry_delta: 0,
4036 htlc_minimum_msat: 0,
4037 htlc_maximum_msat: 250_000_000,
4039 fee_proportional_millionths: 0,
4040 excess_data: Vec::new()
4044 // Attempt to route more than available results in a failure.
4045 let route_params = RouteParameters::from_payment_params_and_value(
4046 payment_params.clone(), 250_000_001);
4047 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4048 &our_id, &route_params, &network_graph.read_only(), None,
4049 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4050 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4051 } else { panic!(); }
4055 // Now, attempt to route an exact amount we have should be fine.
4056 let route_params = RouteParameters::from_payment_params_and_value(
4057 payment_params.clone(), 250_000_000);
4058 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4059 Arc::clone(&logger), &scorer, &(),&random_seed_bytes).unwrap();
4060 assert_eq!(route.paths.len(), 1);
4061 let path = route.paths.last().unwrap();
4062 assert_eq!(path.hops.len(), 2);
4063 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4064 assert_eq!(path.final_value_msat(), 250_000_000);
4067 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4068 // Disable channel #1 and use another first hop.
4069 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4070 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4071 short_channel_id: 1,
4074 cltv_expiry_delta: 0,
4075 htlc_minimum_msat: 0,
4076 htlc_maximum_msat: 1_000_000_000,
4078 fee_proportional_millionths: 0,
4079 excess_data: Vec::new()
4082 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4083 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4086 // Attempt to route more than available results in a failure.
4087 let route_params = RouteParameters::from_payment_params_and_value(
4088 payment_params.clone(), 200_000_001);
4089 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4090 &our_id, &route_params, &network_graph.read_only(),
4091 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4092 &(), &random_seed_bytes) {
4093 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4094 } else { panic!(); }
4098 // Now, attempt to route an exact amount we have should be fine.
4099 let route_params = RouteParameters::from_payment_params_and_value(
4100 payment_params.clone(), 200_000_000);
4101 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4102 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
4103 &random_seed_bytes).unwrap();
4104 assert_eq!(route.paths.len(), 1);
4105 let path = route.paths.last().unwrap();
4106 assert_eq!(path.hops.len(), 2);
4107 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4108 assert_eq!(path.final_value_msat(), 200_000_000);
4111 // Enable channel #1 back.
4112 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4113 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4114 short_channel_id: 1,
4117 cltv_expiry_delta: 0,
4118 htlc_minimum_msat: 0,
4119 htlc_maximum_msat: 1_000_000_000,
4121 fee_proportional_millionths: 0,
4122 excess_data: Vec::new()
4126 // Now let's see if routing works if we know only htlc_maximum_msat.
4127 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4128 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4129 short_channel_id: 3,
4132 cltv_expiry_delta: 0,
4133 htlc_minimum_msat: 0,
4134 htlc_maximum_msat: 15_000,
4136 fee_proportional_millionths: 0,
4137 excess_data: Vec::new()
4141 // Attempt to route more than available results in a failure.
4142 let route_params = RouteParameters::from_payment_params_and_value(
4143 payment_params.clone(), 15_001);
4144 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4145 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4146 &scorer, &(), &random_seed_bytes) {
4147 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4148 } else { panic!(); }
4152 // Now, attempt to route an exact amount we have should be fine.
4153 let route_params = RouteParameters::from_payment_params_and_value(
4154 payment_params.clone(), 15_000);
4155 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4156 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4157 assert_eq!(route.paths.len(), 1);
4158 let path = route.paths.last().unwrap();
4159 assert_eq!(path.hops.len(), 2);
4160 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4161 assert_eq!(path.final_value_msat(), 15_000);
4164 // Now let's see if routing works if we know only capacity from the UTXO.
4166 // We can't change UTXO capacity on the fly, so we'll disable
4167 // the existing channel and add another one with the capacity we need.
4168 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4169 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4170 short_channel_id: 3,
4173 cltv_expiry_delta: 0,
4174 htlc_minimum_msat: 0,
4175 htlc_maximum_msat: MAX_VALUE_MSAT,
4177 fee_proportional_millionths: 0,
4178 excess_data: Vec::new()
4181 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4182 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4183 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4184 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4185 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4187 *chain_monitor.utxo_ret.lock().unwrap() =
4188 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4189 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4191 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4192 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4193 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4194 short_channel_id: 333,
4197 cltv_expiry_delta: (3 << 4) | 1,
4198 htlc_minimum_msat: 0,
4199 htlc_maximum_msat: 15_000,
4201 fee_proportional_millionths: 0,
4202 excess_data: Vec::new()
4204 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4205 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4206 short_channel_id: 333,
4209 cltv_expiry_delta: (3 << 4) | 2,
4210 htlc_minimum_msat: 0,
4211 htlc_maximum_msat: 15_000,
4213 fee_proportional_millionths: 0,
4214 excess_data: Vec::new()
4218 // Attempt to route more than available results in a failure.
4219 let route_params = RouteParameters::from_payment_params_and_value(
4220 payment_params.clone(), 15_001);
4221 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4222 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4223 &scorer, &(), &random_seed_bytes) {
4224 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4225 } else { panic!(); }
4229 // Now, attempt to route an exact amount we have should be fine.
4230 let route_params = RouteParameters::from_payment_params_and_value(
4231 payment_params.clone(), 15_000);
4232 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4233 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4234 assert_eq!(route.paths.len(), 1);
4235 let path = route.paths.last().unwrap();
4236 assert_eq!(path.hops.len(), 2);
4237 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4238 assert_eq!(path.final_value_msat(), 15_000);
4241 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4242 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4243 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4244 short_channel_id: 333,
4247 cltv_expiry_delta: 0,
4248 htlc_minimum_msat: 0,
4249 htlc_maximum_msat: 10_000,
4251 fee_proportional_millionths: 0,
4252 excess_data: Vec::new()
4256 // Attempt to route more than available results in a failure.
4257 let route_params = RouteParameters::from_payment_params_and_value(
4258 payment_params.clone(), 10_001);
4259 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4260 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4261 &scorer, &(), &random_seed_bytes) {
4262 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4263 } else { panic!(); }
4267 // Now, attempt to route an exact amount we have should be fine.
4268 let route_params = RouteParameters::from_payment_params_and_value(
4269 payment_params.clone(), 10_000);
4270 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4271 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4272 assert_eq!(route.paths.len(), 1);
4273 let path = route.paths.last().unwrap();
4274 assert_eq!(path.hops.len(), 2);
4275 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4276 assert_eq!(path.final_value_msat(), 10_000);
4281 fn available_liquidity_last_hop_test() {
4282 // Check that available liquidity properly limits the path even when only
4283 // one of the latter hops is limited.
4284 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4285 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4286 let scorer = ln_test_utils::TestScorer::new();
4287 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4288 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4289 let config = UserConfig::default();
4290 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4292 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4293 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4294 // Total capacity: 50 sats.
4296 // Disable other potential paths.
4297 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4298 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4299 short_channel_id: 2,
4302 cltv_expiry_delta: 0,
4303 htlc_minimum_msat: 0,
4304 htlc_maximum_msat: 100_000,
4306 fee_proportional_millionths: 0,
4307 excess_data: Vec::new()
4309 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4310 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4311 short_channel_id: 7,
4314 cltv_expiry_delta: 0,
4315 htlc_minimum_msat: 0,
4316 htlc_maximum_msat: 100_000,
4318 fee_proportional_millionths: 0,
4319 excess_data: Vec::new()
4324 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4325 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4326 short_channel_id: 12,
4329 cltv_expiry_delta: 0,
4330 htlc_minimum_msat: 0,
4331 htlc_maximum_msat: 100_000,
4333 fee_proportional_millionths: 0,
4334 excess_data: Vec::new()
4336 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4337 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4338 short_channel_id: 13,
4341 cltv_expiry_delta: 0,
4342 htlc_minimum_msat: 0,
4343 htlc_maximum_msat: 100_000,
4345 fee_proportional_millionths: 0,
4346 excess_data: Vec::new()
4349 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4350 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4351 short_channel_id: 6,
4354 cltv_expiry_delta: 0,
4355 htlc_minimum_msat: 0,
4356 htlc_maximum_msat: 50_000,
4358 fee_proportional_millionths: 0,
4359 excess_data: Vec::new()
4361 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4362 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4363 short_channel_id: 11,
4366 cltv_expiry_delta: 0,
4367 htlc_minimum_msat: 0,
4368 htlc_maximum_msat: 100_000,
4370 fee_proportional_millionths: 0,
4371 excess_data: Vec::new()
4374 // Attempt to route more than available results in a failure.
4375 let route_params = RouteParameters::from_payment_params_and_value(
4376 payment_params.clone(), 60_000);
4377 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4378 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4379 &scorer, &(), &random_seed_bytes) {
4380 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4381 } else { panic!(); }
4385 // Now, attempt to route 49 sats (just a bit below the capacity).
4386 let route_params = RouteParameters::from_payment_params_and_value(
4387 payment_params.clone(), 49_000);
4388 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4389 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4390 assert_eq!(route.paths.len(), 1);
4391 let mut total_amount_paid_msat = 0;
4392 for path in &route.paths {
4393 assert_eq!(path.hops.len(), 4);
4394 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4395 total_amount_paid_msat += path.final_value_msat();
4397 assert_eq!(total_amount_paid_msat, 49_000);
4401 // Attempt to route an exact amount is also fine
4402 let route_params = RouteParameters::from_payment_params_and_value(
4403 payment_params, 50_000);
4404 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4405 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4406 assert_eq!(route.paths.len(), 1);
4407 let mut total_amount_paid_msat = 0;
4408 for path in &route.paths {
4409 assert_eq!(path.hops.len(), 4);
4410 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4411 total_amount_paid_msat += path.final_value_msat();
4413 assert_eq!(total_amount_paid_msat, 50_000);
4418 fn ignore_fee_first_hop_test() {
4419 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4420 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4421 let scorer = ln_test_utils::TestScorer::new();
4422 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4423 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4424 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4426 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4427 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4428 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4429 short_channel_id: 1,
4432 cltv_expiry_delta: 0,
4433 htlc_minimum_msat: 0,
4434 htlc_maximum_msat: 100_000,
4435 fee_base_msat: 1_000_000,
4436 fee_proportional_millionths: 0,
4437 excess_data: Vec::new()
4439 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4440 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4441 short_channel_id: 3,
4444 cltv_expiry_delta: 0,
4445 htlc_minimum_msat: 0,
4446 htlc_maximum_msat: 50_000,
4448 fee_proportional_millionths: 0,
4449 excess_data: Vec::new()
4453 let route_params = RouteParameters::from_payment_params_and_value(
4454 payment_params, 50_000);
4455 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4456 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4457 assert_eq!(route.paths.len(), 1);
4458 let mut total_amount_paid_msat = 0;
4459 for path in &route.paths {
4460 assert_eq!(path.hops.len(), 2);
4461 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4462 total_amount_paid_msat += path.final_value_msat();
4464 assert_eq!(total_amount_paid_msat, 50_000);
4469 fn simple_mpp_route_test() {
4470 let (secp_ctx, _, _, _, _) = build_graph();
4471 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4472 let config = UserConfig::default();
4473 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4474 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4475 do_simple_mpp_route_test(clear_payment_params);
4477 // MPP to a 1-hop blinded path for nodes[2]
4478 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
4479 let blinded_path = BlindedPath {
4480 introduction_node_id: nodes[2],
4481 blinding_point: ln_test_utils::pubkey(42),
4482 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4484 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4486 fee_proportional_millionths: 0,
4487 htlc_minimum_msat: 0,
4488 htlc_maximum_msat: 0,
4489 cltv_expiry_delta: 0,
4490 features: BlindedHopFeatures::empty(),
4492 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4493 .with_bolt12_features(bolt12_features.clone()).unwrap();
4494 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4496 // MPP to 3 2-hop blinded paths
4497 let mut blinded_path_node_0 = blinded_path.clone();
4498 blinded_path_node_0.introduction_node_id = nodes[0];
4499 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4500 let mut node_0_payinfo = blinded_payinfo.clone();
4501 node_0_payinfo.htlc_maximum_msat = 50_000;
4503 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4504 blinded_path_node_7.introduction_node_id = nodes[7];
4505 let mut node_7_payinfo = blinded_payinfo.clone();
4506 node_7_payinfo.htlc_maximum_msat = 60_000;
4508 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4509 blinded_path_node_1.introduction_node_id = nodes[1];
4510 let mut node_1_payinfo = blinded_payinfo.clone();
4511 node_1_payinfo.htlc_maximum_msat = 180_000;
4513 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4515 (node_0_payinfo, blinded_path_node_0),
4516 (node_7_payinfo, blinded_path_node_7),
4517 (node_1_payinfo, blinded_path_node_1)
4519 .with_bolt12_features(bolt12_features).unwrap();
4520 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4524 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4525 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4526 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4527 let scorer = ln_test_utils::TestScorer::new();
4528 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4529 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4531 // We need a route consisting of 3 paths:
4532 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4533 // To achieve this, the amount being transferred should be around
4534 // the total capacity of these 3 paths.
4536 // First, we set limits on these (previously unlimited) channels.
4537 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4539 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4540 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4541 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4542 short_channel_id: 1,
4545 cltv_expiry_delta: 0,
4546 htlc_minimum_msat: 0,
4547 htlc_maximum_msat: 100_000,
4549 fee_proportional_millionths: 0,
4550 excess_data: Vec::new()
4552 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4553 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4554 short_channel_id: 3,
4557 cltv_expiry_delta: 0,
4558 htlc_minimum_msat: 0,
4559 htlc_maximum_msat: 50_000,
4561 fee_proportional_millionths: 0,
4562 excess_data: Vec::new()
4565 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4566 // (total limit 60).
4567 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4568 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4569 short_channel_id: 12,
4572 cltv_expiry_delta: 0,
4573 htlc_minimum_msat: 0,
4574 htlc_maximum_msat: 60_000,
4576 fee_proportional_millionths: 0,
4577 excess_data: Vec::new()
4579 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4580 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4581 short_channel_id: 13,
4584 cltv_expiry_delta: 0,
4585 htlc_minimum_msat: 0,
4586 htlc_maximum_msat: 60_000,
4588 fee_proportional_millionths: 0,
4589 excess_data: Vec::new()
4592 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4593 // (total capacity 180 sats).
4594 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4595 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4596 short_channel_id: 2,
4599 cltv_expiry_delta: 0,
4600 htlc_minimum_msat: 0,
4601 htlc_maximum_msat: 200_000,
4603 fee_proportional_millionths: 0,
4604 excess_data: Vec::new()
4606 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4607 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4608 short_channel_id: 4,
4611 cltv_expiry_delta: 0,
4612 htlc_minimum_msat: 0,
4613 htlc_maximum_msat: 180_000,
4615 fee_proportional_millionths: 0,
4616 excess_data: Vec::new()
4620 // Attempt to route more than available results in a failure.
4621 let route_params = RouteParameters::from_payment_params_and_value(
4622 payment_params.clone(), 300_000);
4623 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4624 &our_id, &route_params, &network_graph.read_only(), None,
4625 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4626 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4627 } else { panic!(); }
4631 // Attempt to route while setting max_path_count to 0 results in a failure.
4632 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4633 let route_params = RouteParameters::from_payment_params_and_value(
4634 zero_payment_params, 100);
4635 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4636 &our_id, &route_params, &network_graph.read_only(), None,
4637 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4638 assert_eq!(err, "Can't find a route with no paths allowed.");
4639 } else { panic!(); }
4643 // Attempt to route while setting max_path_count to 3 results in a failure.
4644 // This is the case because the minimal_value_contribution_msat would require each path
4645 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4646 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4647 let route_params = RouteParameters::from_payment_params_and_value(
4648 fail_payment_params, 250_000);
4649 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4650 &our_id, &route_params, &network_graph.read_only(), None,
4651 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4652 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4653 } else { panic!(); }
4657 // Now, attempt to route 250 sats (just a bit below the capacity).
4658 // Our algorithm should provide us with these 3 paths.
4659 let route_params = RouteParameters::from_payment_params_and_value(
4660 payment_params.clone(), 250_000);
4661 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4662 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4663 assert_eq!(route.paths.len(), 3);
4664 let mut total_amount_paid_msat = 0;
4665 for path in &route.paths {
4666 if let Some(bt) = &path.blinded_tail {
4667 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4669 assert_eq!(path.hops.len(), 2);
4670 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4672 total_amount_paid_msat += path.final_value_msat();
4674 assert_eq!(total_amount_paid_msat, 250_000);
4678 // Attempt to route an exact amount is also fine
4679 let route_params = RouteParameters::from_payment_params_and_value(
4680 payment_params.clone(), 290_000);
4681 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4682 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4683 assert_eq!(route.paths.len(), 3);
4684 let mut total_amount_paid_msat = 0;
4685 for path in &route.paths {
4686 if payment_params.payee.blinded_route_hints().len() != 0 {
4687 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
4688 if let Some(bt) = &path.blinded_tail {
4689 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4690 if bt.hops.len() > 1 {
4691 assert_eq!(path.hops.last().unwrap().pubkey,
4692 payment_params.payee.blinded_route_hints().iter()
4693 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
4694 .map(|(_, p)| p.introduction_node_id).unwrap());
4696 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4699 assert_eq!(path.hops.len(), 2);
4700 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4702 total_amount_paid_msat += path.final_value_msat();
4704 assert_eq!(total_amount_paid_msat, 290_000);
4709 fn long_mpp_route_test() {
4710 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4711 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4712 let scorer = ln_test_utils::TestScorer::new();
4713 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4714 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4715 let config = UserConfig::default();
4716 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4717 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4719 // We need a route consisting of 3 paths:
4720 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4721 // Note that these paths overlap (channels 5, 12, 13).
4722 // We will route 300 sats.
4723 // Each path will have 100 sats capacity, those channels which
4724 // are used twice will have 200 sats capacity.
4726 // Disable other potential paths.
4727 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4728 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4729 short_channel_id: 2,
4732 cltv_expiry_delta: 0,
4733 htlc_minimum_msat: 0,
4734 htlc_maximum_msat: 100_000,
4736 fee_proportional_millionths: 0,
4737 excess_data: Vec::new()
4739 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4740 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4741 short_channel_id: 7,
4744 cltv_expiry_delta: 0,
4745 htlc_minimum_msat: 0,
4746 htlc_maximum_msat: 100_000,
4748 fee_proportional_millionths: 0,
4749 excess_data: Vec::new()
4752 // Path via {node0, node2} is channels {1, 3, 5}.
4753 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4754 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4755 short_channel_id: 1,
4758 cltv_expiry_delta: 0,
4759 htlc_minimum_msat: 0,
4760 htlc_maximum_msat: 100_000,
4762 fee_proportional_millionths: 0,
4763 excess_data: Vec::new()
4765 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4766 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4767 short_channel_id: 3,
4770 cltv_expiry_delta: 0,
4771 htlc_minimum_msat: 0,
4772 htlc_maximum_msat: 100_000,
4774 fee_proportional_millionths: 0,
4775 excess_data: Vec::new()
4778 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4779 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4780 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4781 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4782 short_channel_id: 5,
4785 cltv_expiry_delta: 0,
4786 htlc_minimum_msat: 0,
4787 htlc_maximum_msat: 200_000,
4789 fee_proportional_millionths: 0,
4790 excess_data: Vec::new()
4793 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4794 // Add 100 sats to the capacities of {12, 13}, because these channels
4795 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4796 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4797 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4798 short_channel_id: 12,
4801 cltv_expiry_delta: 0,
4802 htlc_minimum_msat: 0,
4803 htlc_maximum_msat: 200_000,
4805 fee_proportional_millionths: 0,
4806 excess_data: Vec::new()
4808 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4809 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4810 short_channel_id: 13,
4813 cltv_expiry_delta: 0,
4814 htlc_minimum_msat: 0,
4815 htlc_maximum_msat: 200_000,
4817 fee_proportional_millionths: 0,
4818 excess_data: Vec::new()
4821 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4822 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4823 short_channel_id: 6,
4826 cltv_expiry_delta: 0,
4827 htlc_minimum_msat: 0,
4828 htlc_maximum_msat: 100_000,
4830 fee_proportional_millionths: 0,
4831 excess_data: Vec::new()
4833 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4834 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4835 short_channel_id: 11,
4838 cltv_expiry_delta: 0,
4839 htlc_minimum_msat: 0,
4840 htlc_maximum_msat: 100_000,
4842 fee_proportional_millionths: 0,
4843 excess_data: Vec::new()
4846 // Path via {node7, node2} is channels {12, 13, 5}.
4847 // We already limited them to 200 sats (they are used twice for 100 sats).
4848 // Nothing to do here.
4851 // Attempt to route more than available results in a failure.
4852 let route_params = RouteParameters::from_payment_params_and_value(
4853 payment_params.clone(), 350_000);
4854 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4855 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4856 &scorer, &(), &random_seed_bytes) {
4857 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4858 } else { panic!(); }
4862 // Now, attempt to route 300 sats (exact amount we can route).
4863 // Our algorithm should provide us with these 3 paths, 100 sats each.
4864 let route_params = RouteParameters::from_payment_params_and_value(
4865 payment_params, 300_000);
4866 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4867 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4868 assert_eq!(route.paths.len(), 3);
4870 let mut total_amount_paid_msat = 0;
4871 for path in &route.paths {
4872 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4873 total_amount_paid_msat += path.final_value_msat();
4875 assert_eq!(total_amount_paid_msat, 300_000);
4881 fn mpp_cheaper_route_test() {
4882 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4883 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4884 let scorer = ln_test_utils::TestScorer::new();
4885 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4886 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4887 let config = UserConfig::default();
4888 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4890 // This test checks that if we have two cheaper paths and one more expensive path,
4891 // so that liquidity-wise any 2 of 3 combination is sufficient,
4892 // two cheaper paths will be taken.
4893 // These paths have equal available liquidity.
4895 // We need a combination of 3 paths:
4896 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4897 // Note that these paths overlap (channels 5, 12, 13).
4898 // Each path will have 100 sats capacity, those channels which
4899 // are used twice will have 200 sats capacity.
4901 // Disable other potential paths.
4902 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4903 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4904 short_channel_id: 2,
4907 cltv_expiry_delta: 0,
4908 htlc_minimum_msat: 0,
4909 htlc_maximum_msat: 100_000,
4911 fee_proportional_millionths: 0,
4912 excess_data: Vec::new()
4914 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4915 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4916 short_channel_id: 7,
4919 cltv_expiry_delta: 0,
4920 htlc_minimum_msat: 0,
4921 htlc_maximum_msat: 100_000,
4923 fee_proportional_millionths: 0,
4924 excess_data: Vec::new()
4927 // Path via {node0, node2} is channels {1, 3, 5}.
4928 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4929 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4930 short_channel_id: 1,
4933 cltv_expiry_delta: 0,
4934 htlc_minimum_msat: 0,
4935 htlc_maximum_msat: 100_000,
4937 fee_proportional_millionths: 0,
4938 excess_data: Vec::new()
4940 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4941 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4942 short_channel_id: 3,
4945 cltv_expiry_delta: 0,
4946 htlc_minimum_msat: 0,
4947 htlc_maximum_msat: 100_000,
4949 fee_proportional_millionths: 0,
4950 excess_data: Vec::new()
4953 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4954 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4955 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4956 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4957 short_channel_id: 5,
4960 cltv_expiry_delta: 0,
4961 htlc_minimum_msat: 0,
4962 htlc_maximum_msat: 200_000,
4964 fee_proportional_millionths: 0,
4965 excess_data: Vec::new()
4968 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4969 // Add 100 sats to the capacities of {12, 13}, because these channels
4970 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4971 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4972 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4973 short_channel_id: 12,
4976 cltv_expiry_delta: 0,
4977 htlc_minimum_msat: 0,
4978 htlc_maximum_msat: 200_000,
4980 fee_proportional_millionths: 0,
4981 excess_data: Vec::new()
4983 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4984 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4985 short_channel_id: 13,
4988 cltv_expiry_delta: 0,
4989 htlc_minimum_msat: 0,
4990 htlc_maximum_msat: 200_000,
4992 fee_proportional_millionths: 0,
4993 excess_data: Vec::new()
4996 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4997 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4998 short_channel_id: 6,
5001 cltv_expiry_delta: 0,
5002 htlc_minimum_msat: 0,
5003 htlc_maximum_msat: 100_000,
5004 fee_base_msat: 1_000,
5005 fee_proportional_millionths: 0,
5006 excess_data: Vec::new()
5008 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5009 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5010 short_channel_id: 11,
5013 cltv_expiry_delta: 0,
5014 htlc_minimum_msat: 0,
5015 htlc_maximum_msat: 100_000,
5017 fee_proportional_millionths: 0,
5018 excess_data: Vec::new()
5021 // Path via {node7, node2} is channels {12, 13, 5}.
5022 // We already limited them to 200 sats (they are used twice for 100 sats).
5023 // Nothing to do here.
5026 // Now, attempt to route 180 sats.
5027 // Our algorithm should provide us with these 2 paths.
5028 let route_params = RouteParameters::from_payment_params_and_value(
5029 payment_params, 180_000);
5030 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5031 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5032 assert_eq!(route.paths.len(), 2);
5034 let mut total_value_transferred_msat = 0;
5035 let mut total_paid_msat = 0;
5036 for path in &route.paths {
5037 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5038 total_value_transferred_msat += path.final_value_msat();
5039 for hop in &path.hops {
5040 total_paid_msat += hop.fee_msat;
5043 // If we paid fee, this would be higher.
5044 assert_eq!(total_value_transferred_msat, 180_000);
5045 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5046 assert_eq!(total_fees_paid, 0);
5051 fn fees_on_mpp_route_test() {
5052 // This test makes sure that MPP algorithm properly takes into account
5053 // fees charged on the channels, by making the fees impactful:
5054 // if the fee is not properly accounted for, the behavior is different.
5055 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5056 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5057 let scorer = ln_test_utils::TestScorer::new();
5058 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5059 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5060 let config = UserConfig::default();
5061 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5063 // We need a route consisting of 2 paths:
5064 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5065 // We will route 200 sats, Each path will have 100 sats capacity.
5067 // This test is not particularly stable: e.g.,
5068 // there's a way to route via {node0, node2, node4}.
5069 // It works while pathfinding is deterministic, but can be broken otherwise.
5070 // It's fine to ignore this concern for now.
5072 // Disable other potential paths.
5073 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5074 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5075 short_channel_id: 2,
5078 cltv_expiry_delta: 0,
5079 htlc_minimum_msat: 0,
5080 htlc_maximum_msat: 100_000,
5082 fee_proportional_millionths: 0,
5083 excess_data: Vec::new()
5086 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5087 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5088 short_channel_id: 7,
5091 cltv_expiry_delta: 0,
5092 htlc_minimum_msat: 0,
5093 htlc_maximum_msat: 100_000,
5095 fee_proportional_millionths: 0,
5096 excess_data: Vec::new()
5099 // Path via {node0, node2} is channels {1, 3, 5}.
5100 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5101 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5102 short_channel_id: 1,
5105 cltv_expiry_delta: 0,
5106 htlc_minimum_msat: 0,
5107 htlc_maximum_msat: 100_000,
5109 fee_proportional_millionths: 0,
5110 excess_data: Vec::new()
5112 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5113 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5114 short_channel_id: 3,
5117 cltv_expiry_delta: 0,
5118 htlc_minimum_msat: 0,
5119 htlc_maximum_msat: 100_000,
5121 fee_proportional_millionths: 0,
5122 excess_data: Vec::new()
5125 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5126 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5127 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5128 short_channel_id: 5,
5131 cltv_expiry_delta: 0,
5132 htlc_minimum_msat: 0,
5133 htlc_maximum_msat: 100_000,
5135 fee_proportional_millionths: 0,
5136 excess_data: Vec::new()
5139 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5140 // All channels should be 100 sats capacity. But for the fee experiment,
5141 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5142 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5143 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5144 // so no matter how large are other channels,
5145 // the whole path will be limited by 100 sats with just these 2 conditions:
5146 // - channel 12 capacity is 250 sats
5147 // - fee for channel 6 is 150 sats
5148 // Let's test this by enforcing these 2 conditions and removing other limits.
5149 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5150 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5151 short_channel_id: 12,
5154 cltv_expiry_delta: 0,
5155 htlc_minimum_msat: 0,
5156 htlc_maximum_msat: 250_000,
5158 fee_proportional_millionths: 0,
5159 excess_data: Vec::new()
5161 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5162 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5163 short_channel_id: 13,
5166 cltv_expiry_delta: 0,
5167 htlc_minimum_msat: 0,
5168 htlc_maximum_msat: MAX_VALUE_MSAT,
5170 fee_proportional_millionths: 0,
5171 excess_data: Vec::new()
5174 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5175 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5176 short_channel_id: 6,
5179 cltv_expiry_delta: 0,
5180 htlc_minimum_msat: 0,
5181 htlc_maximum_msat: MAX_VALUE_MSAT,
5182 fee_base_msat: 150_000,
5183 fee_proportional_millionths: 0,
5184 excess_data: Vec::new()
5186 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5187 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5188 short_channel_id: 11,
5191 cltv_expiry_delta: 0,
5192 htlc_minimum_msat: 0,
5193 htlc_maximum_msat: MAX_VALUE_MSAT,
5195 fee_proportional_millionths: 0,
5196 excess_data: Vec::new()
5200 // Attempt to route more than available results in a failure.
5201 let route_params = RouteParameters::from_payment_params_and_value(
5202 payment_params.clone(), 210_000);
5203 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5204 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5205 &scorer, &(), &random_seed_bytes) {
5206 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5207 } else { panic!(); }
5211 // Now, attempt to route 200 sats (exact amount we can route).
5212 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 200_000);
5213 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5214 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5215 assert_eq!(route.paths.len(), 2);
5217 let mut total_amount_paid_msat = 0;
5218 for path in &route.paths {
5219 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5220 total_amount_paid_msat += path.final_value_msat();
5222 assert_eq!(total_amount_paid_msat, 200_000);
5223 assert_eq!(route.get_total_fees(), 150_000);
5228 fn mpp_with_last_hops() {
5229 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5230 // via a single last-hop route hint, we'd fail to route if we first collected routes
5231 // totaling close but not quite enough to fund the full payment.
5233 // This was because we considered last-hop hints to have exactly the sought payment amount
5234 // instead of the amount we were trying to collect, needlessly limiting our path searching
5235 // at the very first hop.
5237 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5238 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5239 // to only have the remaining to-collect amount in available liquidity.
5241 // This bug appeared in production in some specific channel configurations.
5242 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5243 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5244 let scorer = ln_test_utils::TestScorer::new();
5245 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5246 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5247 let config = UserConfig::default();
5248 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5249 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5250 src_node_id: nodes[2],
5251 short_channel_id: 42,
5252 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5253 cltv_expiry_delta: 42,
5254 htlc_minimum_msat: None,
5255 htlc_maximum_msat: None,
5256 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5258 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5259 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5260 // would first use the no-fee route and then fail to find a path along the second route as
5261 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5262 // under 5% of our payment amount.
5263 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5264 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5265 short_channel_id: 1,
5268 cltv_expiry_delta: (5 << 4) | 5,
5269 htlc_minimum_msat: 0,
5270 htlc_maximum_msat: 99_000,
5271 fee_base_msat: u32::max_value(),
5272 fee_proportional_millionths: u32::max_value(),
5273 excess_data: Vec::new()
5275 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5276 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5277 short_channel_id: 2,
5280 cltv_expiry_delta: (5 << 4) | 3,
5281 htlc_minimum_msat: 0,
5282 htlc_maximum_msat: 99_000,
5283 fee_base_msat: u32::max_value(),
5284 fee_proportional_millionths: u32::max_value(),
5285 excess_data: Vec::new()
5287 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5288 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5289 short_channel_id: 4,
5292 cltv_expiry_delta: (4 << 4) | 1,
5293 htlc_minimum_msat: 0,
5294 htlc_maximum_msat: MAX_VALUE_MSAT,
5296 fee_proportional_millionths: 0,
5297 excess_data: Vec::new()
5299 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5300 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5301 short_channel_id: 13,
5303 flags: 0|2, // Channel disabled
5304 cltv_expiry_delta: (13 << 4) | 1,
5305 htlc_minimum_msat: 0,
5306 htlc_maximum_msat: MAX_VALUE_MSAT,
5308 fee_proportional_millionths: 2000000,
5309 excess_data: Vec::new()
5312 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5314 let route_params = RouteParameters::from_payment_params_and_value(
5315 payment_params, 100_000);
5316 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5317 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5318 assert_eq!(route.paths.len(), 2);
5319 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5320 // Paths are manually ordered ordered by SCID, so:
5321 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5322 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5323 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5324 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5325 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5326 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5327 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5328 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5329 assert_eq!(route.get_total_fees(), 1);
5330 assert_eq!(route.get_total_amount(), 100_000);
5334 fn drop_lowest_channel_mpp_route_test() {
5335 // This test checks that low-capacity channel is dropped when after
5336 // path finding we realize that we found more capacity than we need.
5337 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5338 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5339 let scorer = ln_test_utils::TestScorer::new();
5340 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5341 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5342 let config = UserConfig::default();
5343 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5344 .with_max_channel_saturation_power_of_half(0);
5346 // We need a route consisting of 3 paths:
5347 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5349 // The first and the second paths should be sufficient, but the third should be
5350 // cheaper, so that we select it but drop later.
5352 // First, we set limits on these (previously unlimited) channels.
5353 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5355 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5356 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5357 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5358 short_channel_id: 1,
5361 cltv_expiry_delta: 0,
5362 htlc_minimum_msat: 0,
5363 htlc_maximum_msat: 100_000,
5365 fee_proportional_millionths: 0,
5366 excess_data: Vec::new()
5368 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5370 short_channel_id: 3,
5373 cltv_expiry_delta: 0,
5374 htlc_minimum_msat: 0,
5375 htlc_maximum_msat: 50_000,
5377 fee_proportional_millionths: 0,
5378 excess_data: Vec::new()
5381 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5382 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5383 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5384 short_channel_id: 12,
5387 cltv_expiry_delta: 0,
5388 htlc_minimum_msat: 0,
5389 htlc_maximum_msat: 60_000,
5391 fee_proportional_millionths: 0,
5392 excess_data: Vec::new()
5394 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5395 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5396 short_channel_id: 13,
5399 cltv_expiry_delta: 0,
5400 htlc_minimum_msat: 0,
5401 htlc_maximum_msat: 60_000,
5403 fee_proportional_millionths: 0,
5404 excess_data: Vec::new()
5407 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5408 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5409 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5410 short_channel_id: 2,
5413 cltv_expiry_delta: 0,
5414 htlc_minimum_msat: 0,
5415 htlc_maximum_msat: 20_000,
5417 fee_proportional_millionths: 0,
5418 excess_data: Vec::new()
5420 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5421 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5422 short_channel_id: 4,
5425 cltv_expiry_delta: 0,
5426 htlc_minimum_msat: 0,
5427 htlc_maximum_msat: 20_000,
5429 fee_proportional_millionths: 0,
5430 excess_data: Vec::new()
5434 // Attempt to route more than available results in a failure.
5435 let route_params = RouteParameters::from_payment_params_and_value(
5436 payment_params.clone(), 150_000);
5437 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5438 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5439 &scorer, &(), &random_seed_bytes) {
5440 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5441 } else { panic!(); }
5445 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5446 // Our algorithm should provide us with these 3 paths.
5447 let route_params = RouteParameters::from_payment_params_and_value(
5448 payment_params.clone(), 125_000);
5449 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5450 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5451 assert_eq!(route.paths.len(), 3);
5452 let mut total_amount_paid_msat = 0;
5453 for path in &route.paths {
5454 assert_eq!(path.hops.len(), 2);
5455 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5456 total_amount_paid_msat += path.final_value_msat();
5458 assert_eq!(total_amount_paid_msat, 125_000);
5462 // Attempt to route without the last small cheap channel
5463 let route_params = RouteParameters::from_payment_params_and_value(
5464 payment_params, 90_000);
5465 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5466 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5467 assert_eq!(route.paths.len(), 2);
5468 let mut total_amount_paid_msat = 0;
5469 for path in &route.paths {
5470 assert_eq!(path.hops.len(), 2);
5471 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5472 total_amount_paid_msat += path.final_value_msat();
5474 assert_eq!(total_amount_paid_msat, 90_000);
5479 fn min_criteria_consistency() {
5480 // Test that we don't use an inconsistent metric between updating and walking nodes during
5481 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5482 // was updated with a different criterion from the heap sorting, resulting in loops in
5483 // calculated paths. We test for that specific case here.
5485 // We construct a network that looks like this:
5487 // node2 -1(3)2- node3
5491 // node1 -1(5)2- node4 -1(1)2- node6
5497 // We create a loop on the side of our real path - our destination is node 6, with a
5498 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5499 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5500 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5501 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5502 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5503 // "previous hop" being set to node 3, creating a loop in the path.
5504 let secp_ctx = Secp256k1::new();
5505 let logger = Arc::new(ln_test_utils::TestLogger::new());
5506 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5507 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5508 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5509 let scorer = ln_test_utils::TestScorer::new();
5510 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5511 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5512 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5514 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5515 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5516 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5517 short_channel_id: 6,
5520 cltv_expiry_delta: (6 << 4) | 0,
5521 htlc_minimum_msat: 0,
5522 htlc_maximum_msat: MAX_VALUE_MSAT,
5524 fee_proportional_millionths: 0,
5525 excess_data: Vec::new()
5527 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5529 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5530 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5531 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5532 short_channel_id: 5,
5535 cltv_expiry_delta: (5 << 4) | 0,
5536 htlc_minimum_msat: 0,
5537 htlc_maximum_msat: MAX_VALUE_MSAT,
5539 fee_proportional_millionths: 0,
5540 excess_data: Vec::new()
5542 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5544 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5545 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5546 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5547 short_channel_id: 4,
5550 cltv_expiry_delta: (4 << 4) | 0,
5551 htlc_minimum_msat: 0,
5552 htlc_maximum_msat: MAX_VALUE_MSAT,
5554 fee_proportional_millionths: 0,
5555 excess_data: Vec::new()
5557 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5559 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5560 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5561 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5562 short_channel_id: 3,
5565 cltv_expiry_delta: (3 << 4) | 0,
5566 htlc_minimum_msat: 0,
5567 htlc_maximum_msat: MAX_VALUE_MSAT,
5569 fee_proportional_millionths: 0,
5570 excess_data: Vec::new()
5572 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5574 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5575 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5576 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5577 short_channel_id: 2,
5580 cltv_expiry_delta: (2 << 4) | 0,
5581 htlc_minimum_msat: 0,
5582 htlc_maximum_msat: MAX_VALUE_MSAT,
5584 fee_proportional_millionths: 0,
5585 excess_data: Vec::new()
5588 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5589 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5590 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5591 short_channel_id: 1,
5594 cltv_expiry_delta: (1 << 4) | 0,
5595 htlc_minimum_msat: 100,
5596 htlc_maximum_msat: MAX_VALUE_MSAT,
5598 fee_proportional_millionths: 0,
5599 excess_data: Vec::new()
5601 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5604 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5605 let route_params = RouteParameters::from_payment_params_and_value(
5606 payment_params, 10_000);
5607 let route = get_route(&our_id, &route_params, &network.read_only(), None,
5608 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5609 assert_eq!(route.paths.len(), 1);
5610 assert_eq!(route.paths[0].hops.len(), 3);
5612 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5613 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5614 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5615 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5616 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5617 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5619 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5620 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5621 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5622 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5623 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5624 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5626 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5627 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5628 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5629 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5630 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5631 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5637 fn exact_fee_liquidity_limit() {
5638 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5639 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5640 // we calculated fees on a higher value, resulting in us ignoring such paths.
5641 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5642 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5643 let scorer = ln_test_utils::TestScorer::new();
5644 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5645 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5646 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5648 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5650 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5651 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5652 short_channel_id: 2,
5655 cltv_expiry_delta: 0,
5656 htlc_minimum_msat: 0,
5657 htlc_maximum_msat: 85_000,
5659 fee_proportional_millionths: 0,
5660 excess_data: Vec::new()
5663 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5664 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5665 short_channel_id: 12,
5668 cltv_expiry_delta: (4 << 4) | 1,
5669 htlc_minimum_msat: 0,
5670 htlc_maximum_msat: 270_000,
5672 fee_proportional_millionths: 1000000,
5673 excess_data: Vec::new()
5677 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5678 // 200% fee charged channel 13 in the 1-to-2 direction.
5679 let route_params = RouteParameters::from_payment_params_and_value(
5680 payment_params, 90_000);
5681 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5682 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5683 assert_eq!(route.paths.len(), 1);
5684 assert_eq!(route.paths[0].hops.len(), 2);
5686 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5687 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5688 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5689 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5690 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5691 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5693 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5694 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5695 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5696 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5697 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5698 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5703 fn htlc_max_reduction_below_min() {
5704 // Test that if, while walking the graph, we reduce the value being sent to meet an
5705 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5706 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5707 // resulting in us thinking there is no possible path, even if other paths exist.
5708 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5709 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5710 let scorer = ln_test_utils::TestScorer::new();
5711 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5712 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5713 let config = UserConfig::default();
5714 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5716 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5717 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5718 // then try to send 90_000.
5719 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5720 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5721 short_channel_id: 2,
5724 cltv_expiry_delta: 0,
5725 htlc_minimum_msat: 0,
5726 htlc_maximum_msat: 80_000,
5728 fee_proportional_millionths: 0,
5729 excess_data: Vec::new()
5731 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5732 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5733 short_channel_id: 4,
5736 cltv_expiry_delta: (4 << 4) | 1,
5737 htlc_minimum_msat: 90_000,
5738 htlc_maximum_msat: MAX_VALUE_MSAT,
5740 fee_proportional_millionths: 0,
5741 excess_data: Vec::new()
5745 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5746 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5747 // expensive) channels 12-13 path.
5748 let route_params = RouteParameters::from_payment_params_and_value(
5749 payment_params, 90_000);
5750 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5751 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5752 assert_eq!(route.paths.len(), 1);
5753 assert_eq!(route.paths[0].hops.len(), 2);
5755 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5756 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5757 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5758 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5759 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5760 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5762 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5763 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5764 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5765 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5766 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5767 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5772 fn multiple_direct_first_hops() {
5773 // Previously we'd only ever considered one first hop path per counterparty.
5774 // However, as we don't restrict users to one channel per peer, we really need to support
5775 // looking at all first hop paths.
5776 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5777 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5778 // route over multiple channels with the same first hop.
5779 let secp_ctx = Secp256k1::new();
5780 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5781 let logger = Arc::new(ln_test_utils::TestLogger::new());
5782 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5783 let scorer = ln_test_utils::TestScorer::new();
5784 let config = UserConfig::default();
5785 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5786 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5787 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5790 let route_params = RouteParameters::from_payment_params_and_value(
5791 payment_params.clone(), 100_000);
5792 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5793 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5794 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5795 ]), Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5796 assert_eq!(route.paths.len(), 1);
5797 assert_eq!(route.paths[0].hops.len(), 1);
5799 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5800 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5801 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5804 let route_params = RouteParameters::from_payment_params_and_value(
5805 payment_params.clone(), 100_000);
5806 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5807 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5808 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5809 ]), Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5810 assert_eq!(route.paths.len(), 2);
5811 assert_eq!(route.paths[0].hops.len(), 1);
5812 assert_eq!(route.paths[1].hops.len(), 1);
5814 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5815 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5817 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5818 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5820 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5821 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5825 // If we have a bunch of outbound channels to the same node, where most are not
5826 // sufficient to pay the full payment, but one is, we should default to just using the
5827 // one single channel that has sufficient balance, avoiding MPP.
5829 // If we have several options above the 3xpayment value threshold, we should pick the
5830 // smallest of them, avoiding further fragmenting our available outbound balance to
5832 let route_params = RouteParameters::from_payment_params_and_value(
5833 payment_params, 100_000);
5834 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5835 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5836 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5837 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5838 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5839 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5840 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5841 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5842 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5843 ]), Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5844 assert_eq!(route.paths.len(), 1);
5845 assert_eq!(route.paths[0].hops.len(), 1);
5847 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5848 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5849 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5854 fn prefers_shorter_route_with_higher_fees() {
5855 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5856 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5857 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5859 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5860 let scorer = ln_test_utils::TestScorer::new();
5861 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5862 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5863 let route_params = RouteParameters::from_payment_params_and_value(
5864 payment_params.clone(), 100);
5865 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
5866 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5867 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5869 assert_eq!(route.get_total_fees(), 100);
5870 assert_eq!(route.get_total_amount(), 100);
5871 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5873 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5874 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5875 let scorer = FixedPenaltyScorer::with_penalty(100);
5876 let route_params = RouteParameters::from_payment_params_and_value(
5877 payment_params, 100);
5878 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
5879 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5880 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5882 assert_eq!(route.get_total_fees(), 300);
5883 assert_eq!(route.get_total_amount(), 100);
5884 assert_eq!(path, vec![2, 4, 7, 10]);
5887 struct BadChannelScorer {
5888 short_channel_id: u64,
5892 impl Writeable for BadChannelScorer {
5893 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5895 impl ScoreLookUp for BadChannelScorer {
5896 type ScoreParams = ();
5897 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5898 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5902 struct BadNodeScorer {
5907 impl Writeable for BadNodeScorer {
5908 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5911 impl ScoreLookUp for BadNodeScorer {
5912 type ScoreParams = ();
5913 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5914 if *target == self.node_id { u64::max_value() } else { 0 }
5919 fn avoids_routing_through_bad_channels_and_nodes() {
5920 let (secp_ctx, network, _, _, logger) = build_graph();
5921 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5922 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5923 let network_graph = network.read_only();
5925 // A path to nodes[6] exists when no penalties are applied to any channel.
5926 let scorer = ln_test_utils::TestScorer::new();
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_params = RouteParameters::from_payment_params_and_value(
5930 payment_params, 100);
5931 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
5932 &scorer, &(), &random_seed_bytes).unwrap();
5933 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5935 assert_eq!(route.get_total_fees(), 100);
5936 assert_eq!(route.get_total_amount(), 100);
5937 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5939 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5940 let scorer = BadChannelScorer { short_channel_id: 6 };
5941 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
5942 &scorer, &(), &random_seed_bytes).unwrap();
5943 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5945 assert_eq!(route.get_total_fees(), 300);
5946 assert_eq!(route.get_total_amount(), 100);
5947 assert_eq!(path, vec![2, 4, 7, 10]);
5949 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5950 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5951 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
5952 &scorer, &(), &random_seed_bytes) {
5953 Err(LightningError { err, .. } ) => {
5954 assert_eq!(err, "Failed to find a path to the given destination");
5956 Ok(_) => panic!("Expected error"),
5961 fn total_fees_single_path() {
5963 paths: vec![Path { hops: vec![
5965 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5966 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5967 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5970 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5971 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5972 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5975 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5976 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5977 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5979 ], blinded_tail: None }],
5983 assert_eq!(route.get_total_fees(), 250);
5984 assert_eq!(route.get_total_amount(), 225);
5988 fn total_fees_multi_path() {
5990 paths: vec![Path { hops: vec![
5992 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5993 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5994 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5997 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5998 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5999 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
6001 ], blinded_tail: None }, Path { hops: vec![
6003 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6004 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6005 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
6008 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6009 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6010 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
6012 ], blinded_tail: None }],
6016 assert_eq!(route.get_total_fees(), 200);
6017 assert_eq!(route.get_total_amount(), 300);
6021 fn total_empty_route_no_panic() {
6022 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6023 // would both panic if the route was completely empty. We test to ensure they return 0
6024 // here, even though its somewhat nonsensical as a route.
6025 let route = Route { paths: Vec::new(), route_params: None };
6027 assert_eq!(route.get_total_fees(), 0);
6028 assert_eq!(route.get_total_amount(), 0);
6032 fn limits_total_cltv_delta() {
6033 let (secp_ctx, network, _, _, logger) = build_graph();
6034 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6035 let network_graph = network.read_only();
6037 let scorer = ln_test_utils::TestScorer::new();
6039 // Make sure that generally there is at least one route available
6040 let feasible_max_total_cltv_delta = 1008;
6041 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6042 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6043 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6044 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6045 let route_params = RouteParameters::from_payment_params_and_value(
6046 feasible_payment_params, 100);
6047 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6048 &scorer, &(), &random_seed_bytes).unwrap();
6049 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6050 assert_ne!(path.len(), 0);
6052 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6053 let fail_max_total_cltv_delta = 23;
6054 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6055 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6056 let route_params = RouteParameters::from_payment_params_and_value(
6057 fail_payment_params, 100);
6058 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6059 &(), &random_seed_bytes)
6061 Err(LightningError { err, .. } ) => {
6062 assert_eq!(err, "Failed to find a path to the given destination");
6064 Ok(_) => panic!("Expected error"),
6069 fn avoids_recently_failed_paths() {
6070 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6071 // randomly inserting channels into it until we can't find a route anymore.
6072 let (secp_ctx, network, _, _, logger) = build_graph();
6073 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6074 let network_graph = network.read_only();
6076 let scorer = ln_test_utils::TestScorer::new();
6077 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6078 .with_max_path_count(1);
6079 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6080 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6082 // We should be able to find a route initially, and then after we fail a few random
6083 // channels eventually we won't be able to any longer.
6084 let route_params = RouteParameters::from_payment_params_and_value(
6085 payment_params.clone(), 100);
6086 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6087 &scorer, &(), &random_seed_bytes).is_ok());
6089 let route_params = RouteParameters::from_payment_params_and_value(
6090 payment_params.clone(), 100);
6091 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6092 Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
6094 for chan in route.paths[0].hops.iter() {
6095 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6097 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6098 % route.paths[0].hops.len();
6099 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6105 fn limits_path_length() {
6106 let (secp_ctx, network, _, _, logger) = build_line_graph();
6107 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6108 let network_graph = network.read_only();
6110 let scorer = ln_test_utils::TestScorer::new();
6111 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6112 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6114 // First check we can actually create a long route on this graph.
6115 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6116 let route_params = RouteParameters::from_payment_params_and_value(
6117 feasible_payment_params, 100);
6118 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6119 &scorer, &(), &random_seed_bytes).unwrap();
6120 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6121 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6123 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6124 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6125 let route_params = RouteParameters::from_payment_params_and_value(
6126 fail_payment_params, 100);
6127 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6128 &(), &random_seed_bytes)
6130 Err(LightningError { err, .. } ) => {
6131 assert_eq!(err, "Failed to find a path to the given destination");
6133 Ok(_) => panic!("Expected error"),
6138 fn adds_and_limits_cltv_offset() {
6139 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6140 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6142 let scorer = ln_test_utils::TestScorer::new();
6144 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6145 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6146 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6147 let route_params = RouteParameters::from_payment_params_and_value(
6148 payment_params.clone(), 100);
6149 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6150 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6151 assert_eq!(route.paths.len(), 1);
6153 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6155 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6156 let mut route_default = route.clone();
6157 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6158 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6159 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6160 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6161 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6163 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6164 let mut route_limited = route.clone();
6165 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6166 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6167 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6168 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6169 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6173 fn adds_plausible_cltv_offset() {
6174 let (secp_ctx, network, _, _, logger) = build_graph();
6175 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6176 let network_graph = network.read_only();
6177 let network_nodes = network_graph.nodes();
6178 let network_channels = network_graph.channels();
6179 let scorer = ln_test_utils::TestScorer::new();
6180 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6181 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6182 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6184 let route_params = RouteParameters::from_payment_params_and_value(
6185 payment_params.clone(), 100);
6186 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6187 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6188 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6190 let mut path_plausibility = vec![];
6192 for p in route.paths {
6193 // 1. Select random observation point
6194 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6195 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6197 prng.process_in_place(&mut random_bytes);
6198 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6199 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6201 // 2. Calculate what CLTV expiry delta we would observe there
6202 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6204 // 3. Starting from the observation point, find candidate paths
6205 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6206 candidates.push_back((observation_point, vec![]));
6208 let mut found_plausible_candidate = false;
6210 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6211 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6212 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6213 found_plausible_candidate = true;
6214 break 'candidate_loop;
6218 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6219 for channel_id in &cur_node.channels {
6220 if let Some(channel_info) = network_channels.get(&channel_id) {
6221 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6222 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6223 if cur_path_cltv_deltas.iter().sum::<u32>()
6224 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6225 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6226 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6227 candidates.push_back((*next_id, new_path_cltv_deltas));
6235 path_plausibility.push(found_plausible_candidate);
6237 assert!(path_plausibility.iter().all(|x| *x));
6241 fn builds_correct_path_from_hops() {
6242 let (secp_ctx, network, _, _, logger) = build_graph();
6243 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6244 let network_graph = network.read_only();
6246 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6247 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6249 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6250 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6251 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6252 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6253 Arc::clone(&logger), &random_seed_bytes).unwrap();
6254 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6255 assert_eq!(hops.len(), route.paths[0].hops.len());
6256 for (idx, hop_pubkey) in hops.iter().enumerate() {
6257 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6262 fn avoids_saturating_channels() {
6263 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6264 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6265 let decay_params = ProbabilisticScoringDecayParameters::default();
6266 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6268 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6269 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6270 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6271 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6272 short_channel_id: 4,
6275 cltv_expiry_delta: (4 << 4) | 1,
6276 htlc_minimum_msat: 0,
6277 htlc_maximum_msat: 250_000_000,
6279 fee_proportional_millionths: 0,
6280 excess_data: Vec::new()
6282 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6283 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6284 short_channel_id: 13,
6287 cltv_expiry_delta: (13 << 4) | 1,
6288 htlc_minimum_msat: 0,
6289 htlc_maximum_msat: 250_000_000,
6291 fee_proportional_millionths: 0,
6292 excess_data: Vec::new()
6295 let config = UserConfig::default();
6296 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6297 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6298 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6299 // 100,000 sats is less than the available liquidity on each channel, set above.
6300 let route_params = RouteParameters::from_payment_params_and_value(
6301 payment_params, 100_000_000);
6302 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6303 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6304 assert_eq!(route.paths.len(), 2);
6305 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6306 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6309 #[cfg(not(feature = "no-std"))]
6310 pub(super) fn random_init_seed() -> u64 {
6311 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6312 use core::hash::{BuildHasher, Hasher};
6313 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6314 println!("Using seed of {}", seed);
6319 #[cfg(not(feature = "no-std"))]
6320 fn generate_routes() {
6321 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6323 let logger = ln_test_utils::TestLogger::new();
6324 let graph = match super::bench_utils::read_network_graph(&logger) {
6332 let params = ProbabilisticScoringFeeParameters::default();
6333 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6334 let features = super::Bolt11InvoiceFeatures::empty();
6336 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6340 #[cfg(not(feature = "no-std"))]
6341 fn generate_routes_mpp() {
6342 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6344 let logger = ln_test_utils::TestLogger::new();
6345 let graph = match super::bench_utils::read_network_graph(&logger) {
6353 let params = ProbabilisticScoringFeeParameters::default();
6354 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6355 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6357 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6361 #[cfg(not(feature = "no-std"))]
6362 fn generate_large_mpp_routes() {
6363 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6365 let logger = ln_test_utils::TestLogger::new();
6366 let graph = match super::bench_utils::read_network_graph(&logger) {
6374 let params = ProbabilisticScoringFeeParameters::default();
6375 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6376 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6378 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6382 fn honors_manual_penalties() {
6383 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6384 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6386 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6387 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6389 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6390 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6392 // First check set manual penalties are returned by the scorer.
6393 let usage = ChannelUsage {
6395 inflight_htlc_msat: 0,
6396 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6398 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6399 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6400 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
6402 // Then check we can get a normal route
6403 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6404 let route_params = RouteParameters::from_payment_params_and_value(
6405 payment_params, 100);
6406 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6407 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6408 assert!(route.is_ok());
6410 // Then check that we can't get a route if we ban an intermediate node.
6411 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6412 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6413 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6414 assert!(route.is_err());
6416 // Finally make sure we can route again, when we remove the ban.
6417 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6418 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6419 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6420 assert!(route.is_ok());
6424 fn abide_by_route_hint_max_htlc() {
6425 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6426 // params in the final route.
6427 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6428 let netgraph = network_graph.read_only();
6429 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6430 let scorer = ln_test_utils::TestScorer::new();
6431 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6432 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6433 let config = UserConfig::default();
6435 let max_htlc_msat = 50_000;
6436 let route_hint_1 = RouteHint(vec![RouteHintHop {
6437 src_node_id: nodes[2],
6438 short_channel_id: 42,
6441 proportional_millionths: 0,
6443 cltv_expiry_delta: 10,
6444 htlc_minimum_msat: None,
6445 htlc_maximum_msat: Some(max_htlc_msat),
6447 let dest_node_id = ln_test_utils::pubkey(42);
6448 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6449 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6450 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6452 // Make sure we'll error if our route hints don't have enough liquidity according to their
6453 // htlc_maximum_msat.
6454 let route_params = RouteParameters::from_payment_params_and_value(
6455 payment_params, max_htlc_msat + 1);
6456 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6457 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &(),
6460 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6461 } else { panic!(); }
6463 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6464 let mut route_hint_2 = route_hint_1.clone();
6465 route_hint_2.0[0].short_channel_id = 43;
6466 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6467 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6468 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6469 let route_params = RouteParameters::from_payment_params_and_value(
6470 payment_params, max_htlc_msat + 1);
6471 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
6472 &scorer, &(), &random_seed_bytes).unwrap();
6473 assert_eq!(route.paths.len(), 2);
6474 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6475 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6479 fn direct_channel_to_hints_with_max_htlc() {
6480 // Check that if we have a first hop channel peer that's connected to multiple provided route
6481 // hints, that we properly split the payment between the route hints if needed.
6482 let logger = Arc::new(ln_test_utils::TestLogger::new());
6483 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6484 let scorer = ln_test_utils::TestScorer::new();
6485 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6486 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6487 let config = UserConfig::default();
6489 let our_node_id = ln_test_utils::pubkey(42);
6490 let intermed_node_id = ln_test_utils::pubkey(43);
6491 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6493 let amt_msat = 900_000;
6494 let max_htlc_msat = 500_000;
6495 let route_hint_1 = RouteHint(vec![RouteHintHop {
6496 src_node_id: intermed_node_id,
6497 short_channel_id: 44,
6500 proportional_millionths: 0,
6502 cltv_expiry_delta: 10,
6503 htlc_minimum_msat: None,
6504 htlc_maximum_msat: Some(max_htlc_msat),
6506 src_node_id: intermed_node_id,
6507 short_channel_id: 45,
6510 proportional_millionths: 0,
6512 cltv_expiry_delta: 10,
6513 htlc_minimum_msat: None,
6514 // Check that later route hint max htlcs don't override earlier ones
6515 htlc_maximum_msat: Some(max_htlc_msat - 50),
6517 let mut route_hint_2 = route_hint_1.clone();
6518 route_hint_2.0[0].short_channel_id = 46;
6519 route_hint_2.0[1].short_channel_id = 47;
6520 let dest_node_id = ln_test_utils::pubkey(44);
6521 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6522 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6523 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6525 let route_params = RouteParameters::from_payment_params_and_value(
6526 payment_params, amt_msat);
6527 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6528 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
6529 &random_seed_bytes).unwrap();
6530 assert_eq!(route.paths.len(), 2);
6531 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6532 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6533 assert_eq!(route.get_total_amount(), amt_msat);
6535 // Re-run but with two first hop channels connected to the same route hint peers that must be
6537 let first_hops = vec![
6538 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6539 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6541 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6542 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
6543 &random_seed_bytes).unwrap();
6544 assert_eq!(route.paths.len(), 2);
6545 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6546 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6547 assert_eq!(route.get_total_amount(), amt_msat);
6549 // Make sure this works for blinded route hints.
6550 let blinded_path = BlindedPath {
6551 introduction_node_id: intermed_node_id,
6552 blinding_point: ln_test_utils::pubkey(42),
6554 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6555 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6558 let blinded_payinfo = BlindedPayInfo {
6560 fee_proportional_millionths: 0,
6561 htlc_minimum_msat: 1,
6562 htlc_maximum_msat: max_htlc_msat,
6563 cltv_expiry_delta: 10,
6564 features: BlindedHopFeatures::empty(),
6566 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6567 let payment_params = PaymentParameters::blinded(vec![
6568 (blinded_payinfo.clone(), blinded_path.clone()),
6569 (blinded_payinfo.clone(), blinded_path.clone())])
6570 .with_bolt12_features(bolt12_features).unwrap();
6571 let route_params = RouteParameters::from_payment_params_and_value(
6572 payment_params, amt_msat);
6573 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6574 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
6575 &random_seed_bytes).unwrap();
6576 assert_eq!(route.paths.len(), 2);
6577 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6578 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6579 assert_eq!(route.get_total_amount(), amt_msat);
6583 fn blinded_route_ser() {
6584 let blinded_path_1 = BlindedPath {
6585 introduction_node_id: ln_test_utils::pubkey(42),
6586 blinding_point: ln_test_utils::pubkey(43),
6588 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6589 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6592 let blinded_path_2 = BlindedPath {
6593 introduction_node_id: ln_test_utils::pubkey(46),
6594 blinding_point: ln_test_utils::pubkey(47),
6596 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6597 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6600 // (De)serialize a Route with 1 blinded path out of two total paths.
6601 let mut route = Route { paths: vec![Path {
6602 hops: vec![RouteHop {
6603 pubkey: ln_test_utils::pubkey(50),
6604 node_features: NodeFeatures::empty(),
6605 short_channel_id: 42,
6606 channel_features: ChannelFeatures::empty(),
6608 cltv_expiry_delta: 0,
6610 blinded_tail: Some(BlindedTail {
6611 hops: blinded_path_1.blinded_hops,
6612 blinding_point: blinded_path_1.blinding_point,
6613 excess_final_cltv_expiry_delta: 40,
6614 final_value_msat: 100,
6616 hops: vec![RouteHop {
6617 pubkey: ln_test_utils::pubkey(51),
6618 node_features: NodeFeatures::empty(),
6619 short_channel_id: 43,
6620 channel_features: ChannelFeatures::empty(),
6622 cltv_expiry_delta: 0,
6623 }], blinded_tail: None }],
6626 let encoded_route = route.encode();
6627 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6628 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6629 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6631 // (De)serialize a Route with two paths, each containing a blinded tail.
6632 route.paths[1].blinded_tail = Some(BlindedTail {
6633 hops: blinded_path_2.blinded_hops,
6634 blinding_point: blinded_path_2.blinding_point,
6635 excess_final_cltv_expiry_delta: 41,
6636 final_value_msat: 101,
6638 let encoded_route = route.encode();
6639 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6640 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6641 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6645 fn blinded_path_inflight_processing() {
6646 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6647 // account for the blinded tail's final amount_msat.
6648 let mut inflight_htlcs = InFlightHtlcs::new();
6649 let blinded_path = BlindedPath {
6650 introduction_node_id: ln_test_utils::pubkey(43),
6651 blinding_point: ln_test_utils::pubkey(48),
6652 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
6655 hops: vec![RouteHop {
6656 pubkey: ln_test_utils::pubkey(42),
6657 node_features: NodeFeatures::empty(),
6658 short_channel_id: 42,
6659 channel_features: ChannelFeatures::empty(),
6661 cltv_expiry_delta: 0,
6664 pubkey: blinded_path.introduction_node_id,
6665 node_features: NodeFeatures::empty(),
6666 short_channel_id: 43,
6667 channel_features: ChannelFeatures::empty(),
6669 cltv_expiry_delta: 0,
6671 blinded_tail: Some(BlindedTail {
6672 hops: blinded_path.blinded_hops,
6673 blinding_point: blinded_path.blinding_point,
6674 excess_final_cltv_expiry_delta: 0,
6675 final_value_msat: 200,
6678 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
6679 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
6680 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
6684 fn blinded_path_cltv_shadow_offset() {
6685 // Make sure we add a shadow offset when sending to blinded paths.
6686 let blinded_path = BlindedPath {
6687 introduction_node_id: ln_test_utils::pubkey(43),
6688 blinding_point: ln_test_utils::pubkey(44),
6690 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
6691 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
6694 let mut route = Route { paths: vec![Path {
6695 hops: vec![RouteHop {
6696 pubkey: ln_test_utils::pubkey(42),
6697 node_features: NodeFeatures::empty(),
6698 short_channel_id: 42,
6699 channel_features: ChannelFeatures::empty(),
6701 cltv_expiry_delta: 0,
6704 pubkey: blinded_path.introduction_node_id,
6705 node_features: NodeFeatures::empty(),
6706 short_channel_id: 43,
6707 channel_features: ChannelFeatures::empty(),
6709 cltv_expiry_delta: 0,
6712 blinded_tail: Some(BlindedTail {
6713 hops: blinded_path.blinded_hops,
6714 blinding_point: blinded_path.blinding_point,
6715 excess_final_cltv_expiry_delta: 0,
6716 final_value_msat: 200,
6718 }], route_params: None};
6720 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
6721 let (_, network_graph, _, _, _) = build_line_graph();
6722 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
6723 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
6724 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
6728 fn simple_blinded_route_hints() {
6729 do_simple_blinded_route_hints(1);
6730 do_simple_blinded_route_hints(2);
6731 do_simple_blinded_route_hints(3);
6734 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
6735 // Check that we can generate a route to a blinded path with the expected hops.
6736 let (secp_ctx, network, _, _, logger) = build_graph();
6737 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6738 let network_graph = network.read_only();
6740 let scorer = ln_test_utils::TestScorer::new();
6741 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6742 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6744 let mut blinded_path = BlindedPath {
6745 introduction_node_id: nodes[2],
6746 blinding_point: ln_test_utils::pubkey(42),
6747 blinded_hops: Vec::with_capacity(num_blinded_hops),
6749 for i in 0..num_blinded_hops {
6750 blinded_path.blinded_hops.push(
6751 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
6754 let blinded_payinfo = BlindedPayInfo {
6756 fee_proportional_millionths: 500,
6757 htlc_minimum_msat: 1000,
6758 htlc_maximum_msat: 100_000_000,
6759 cltv_expiry_delta: 15,
6760 features: BlindedHopFeatures::empty(),
6763 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
6764 let route_params = RouteParameters::from_payment_params_and_value(
6765 payment_params, 1001);
6766 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6767 &scorer, &(), &random_seed_bytes).unwrap();
6768 assert_eq!(route.paths.len(), 1);
6769 assert_eq!(route.paths[0].hops.len(), 2);
6771 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
6772 assert_eq!(tail.hops, blinded_path.blinded_hops);
6773 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
6774 assert_eq!(tail.final_value_msat, 1001);
6776 let final_hop = route.paths[0].hops.last().unwrap();
6777 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
6778 if tail.hops.len() > 1 {
6779 assert_eq!(final_hop.fee_msat,
6780 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
6781 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
6783 assert_eq!(final_hop.fee_msat, 0);
6784 assert_eq!(final_hop.cltv_expiry_delta, 0);
6789 fn blinded_path_routing_errors() {
6790 // Check that we can generate a route to a blinded path with the expected hops.
6791 let (secp_ctx, network, _, _, logger) = build_graph();
6792 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6793 let network_graph = network.read_only();
6795 let scorer = ln_test_utils::TestScorer::new();
6796 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6797 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6799 let mut invalid_blinded_path = BlindedPath {
6800 introduction_node_id: nodes[2],
6801 blinding_point: ln_test_utils::pubkey(42),
6803 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
6806 let blinded_payinfo = BlindedPayInfo {
6808 fee_proportional_millionths: 500,
6809 htlc_minimum_msat: 1000,
6810 htlc_maximum_msat: 100_000_000,
6811 cltv_expiry_delta: 15,
6812 features: BlindedHopFeatures::empty(),
6815 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
6816 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
6817 let payment_params = PaymentParameters::blinded(vec![
6818 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
6819 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
6820 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6821 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6822 &scorer, &(), &random_seed_bytes)
6824 Err(LightningError { err, .. }) => {
6825 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
6827 _ => panic!("Expected error")
6830 invalid_blinded_path.introduction_node_id = our_id;
6831 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
6832 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6833 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6834 &(), &random_seed_bytes)
6836 Err(LightningError { err, .. }) => {
6837 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
6839 _ => panic!("Expected error")
6842 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
6843 invalid_blinded_path.blinded_hops.clear();
6844 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
6845 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6846 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6847 &(), &random_seed_bytes)
6849 Err(LightningError { err, .. }) => {
6850 assert_eq!(err, "0-hop blinded path provided");
6852 _ => panic!("Expected error")
6857 fn matching_intro_node_paths_provided() {
6858 // Check that if multiple blinded paths with the same intro node are provided in payment
6859 // parameters, we'll return the correct paths in the resulting MPP route.
6860 let (secp_ctx, network, _, _, logger) = build_graph();
6861 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6862 let network_graph = network.read_only();
6864 let scorer = ln_test_utils::TestScorer::new();
6865 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6866 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6867 let config = UserConfig::default();
6869 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6870 let blinded_path_1 = BlindedPath {
6871 introduction_node_id: nodes[2],
6872 blinding_point: ln_test_utils::pubkey(42),
6874 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6875 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6878 let blinded_payinfo_1 = BlindedPayInfo {
6880 fee_proportional_millionths: 0,
6881 htlc_minimum_msat: 0,
6882 htlc_maximum_msat: 30_000,
6883 cltv_expiry_delta: 0,
6884 features: BlindedHopFeatures::empty(),
6887 let mut blinded_path_2 = blinded_path_1.clone();
6888 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
6889 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
6890 blinded_payinfo_2.htlc_maximum_msat = 70_000;
6892 let blinded_hints = vec![
6893 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
6894 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
6896 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
6897 .with_bolt12_features(bolt12_features.clone()).unwrap();
6899 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
6900 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6901 &scorer, &(), &random_seed_bytes).unwrap();
6902 assert_eq!(route.paths.len(), 2);
6903 let mut total_amount_paid_msat = 0;
6904 for path in route.paths.into_iter() {
6905 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6906 if let Some(bt) = &path.blinded_tail {
6907 assert_eq!(bt.blinding_point,
6908 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
6909 .map(|(_, bp)| bp.blinding_point).unwrap());
6910 } else { panic!(); }
6911 total_amount_paid_msat += path.final_value_msat();
6913 assert_eq!(total_amount_paid_msat, 100_000);
6917 fn direct_to_intro_node() {
6918 // This previously caused a debug panic in the router when asserting
6919 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
6920 // direct channels we failed to account for the fee charged for use of the blinded path.
6923 // node0 -1(1)2 - node1
6924 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
6925 // doesn't account for the blinded path fee.
6927 let secp_ctx = Secp256k1::new();
6928 let logger = Arc::new(ln_test_utils::TestLogger::new());
6929 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6930 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
6931 let scorer = ln_test_utils::TestScorer::new();
6932 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6933 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6935 let amt_msat = 10_000_000;
6936 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
6937 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
6938 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6939 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6940 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6941 short_channel_id: 1,
6944 cltv_expiry_delta: 42,
6945 htlc_minimum_msat: 1_000,
6946 htlc_maximum_msat: 10_000_000,
6948 fee_proportional_millionths: 0,
6949 excess_data: Vec::new()
6951 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6952 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6953 short_channel_id: 1,
6956 cltv_expiry_delta: 42,
6957 htlc_minimum_msat: 1_000,
6958 htlc_maximum_msat: 10_000_000,
6960 fee_proportional_millionths: 0,
6961 excess_data: Vec::new()
6963 let first_hops = vec![
6964 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6966 let blinded_path = BlindedPath {
6967 introduction_node_id: nodes[1],
6968 blinding_point: ln_test_utils::pubkey(42),
6970 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6971 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6974 let blinded_payinfo = BlindedPayInfo {
6975 fee_base_msat: 1000,
6976 fee_proportional_millionths: 0,
6977 htlc_minimum_msat: 1000,
6978 htlc_maximum_msat: MAX_VALUE_MSAT,
6979 cltv_expiry_delta: 0,
6980 features: BlindedHopFeatures::empty(),
6982 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
6984 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
6986 let netgraph = network_graph.read_only();
6987 let route_params = RouteParameters::from_payment_params_and_value(
6988 payment_params.clone(), amt_msat);
6989 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
6990 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
6991 &random_seed_bytes) {
6992 assert_eq!(err, "Failed to find a path to the given destination");
6993 } else { panic!("Expected error") }
6995 // Sending an exact amount accounting for the blinded path fee works.
6996 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
6997 let route_params = RouteParameters::from_payment_params_and_value(
6998 payment_params, amt_minus_blinded_path_fee);
6999 let route = get_route(&nodes[0], &route_params, &netgraph,
7000 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
7001 &random_seed_bytes).unwrap();
7002 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7003 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7007 fn direct_to_matching_intro_nodes() {
7008 // This previously caused us to enter `unreachable` code in the following situation:
7009 // 1. We add a route candidate for intro_node contributing a high amount
7010 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7011 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7012 // amount, and update our route candidate for intro_node for the lower amount
7013 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7014 // lower contribution amount, but fail (this was previously caused by failure to account for
7015 // blinded path fees when adding first_hop<>intro_node candidates)
7016 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7017 // candidate still thinks its path is contributing the original higher amount. This caused us
7018 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7020 let secp_ctx = Secp256k1::new();
7021 let logger = Arc::new(ln_test_utils::TestLogger::new());
7022 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7023 let scorer = ln_test_utils::TestScorer::new();
7024 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7025 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7026 let config = UserConfig::default();
7028 // Values are taken from the fuzz input that uncovered this panic.
7029 let amt_msat = 21_7020_5185_1403_2640;
7030 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7031 let first_hops = vec![
7032 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7033 18446744073709551615)];
7035 let blinded_path = BlindedPath {
7036 introduction_node_id: nodes[1],
7037 blinding_point: ln_test_utils::pubkey(42),
7039 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7040 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7043 let blinded_payinfo = BlindedPayInfo {
7044 fee_base_msat: 5046_2720,
7045 fee_proportional_millionths: 0,
7046 htlc_minimum_msat: 4503_5996_2737_0496,
7047 htlc_maximum_msat: 45_0359_9627_3704_9600,
7048 cltv_expiry_delta: 0,
7049 features: BlindedHopFeatures::empty(),
7051 let mut blinded_hints = vec![
7052 (blinded_payinfo.clone(), blinded_path.clone()),
7053 (blinded_payinfo.clone(), blinded_path.clone()),
7055 blinded_hints[1].0.fee_base_msat = 419_4304;
7056 blinded_hints[1].0.fee_proportional_millionths = 257;
7057 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7058 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7059 blinded_hints[1].0.cltv_expiry_delta = 0;
7061 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7062 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7063 .with_bolt12_features(bolt12_features.clone()).unwrap();
7065 let netgraph = network_graph.read_only();
7066 let route_params = RouteParameters::from_payment_params_and_value(
7067 payment_params, amt_msat);
7068 let route = get_route(&nodes[0], &route_params, &netgraph,
7069 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
7070 &random_seed_bytes).unwrap();
7071 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7072 assert_eq!(route.get_total_amount(), amt_msat);
7076 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
7077 pub(crate) mod bench_utils {
7081 use bitcoin::hashes::Hash;
7082 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
7084 use crate::chain::transaction::OutPoint;
7085 use crate::routing::scoring::ScoreUpdate;
7086 use crate::sign::{EntropySource, KeysManager};
7087 use crate::ln::ChannelId;
7088 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
7089 use crate::ln::features::Bolt11InvoiceFeatures;
7090 use crate::routing::gossip::NetworkGraph;
7091 use crate::util::config::UserConfig;
7092 use crate::util::ser::ReadableArgs;
7093 use crate::util::test_utils::TestLogger;
7095 /// Tries to open a network graph file, or panics with a URL to fetch it.
7096 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
7097 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
7098 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
7099 .or_else(|_| { // Fall back to guessing based on the binary location
7100 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
7101 let mut path = std::env::current_exe().unwrap();
7102 path.pop(); // lightning-...
7104 path.pop(); // debug
7105 path.pop(); // target
7106 path.push("lightning");
7107 path.push("net_graph-2023-01-18.bin");
7110 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
7111 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
7112 let mut path = std::env::current_exe().unwrap();
7113 path.pop(); // bench...
7115 path.pop(); // debug
7116 path.pop(); // target
7117 path.pop(); // bench
7118 path.push("lightning");
7119 path.push("net_graph-2023-01-18.bin");
7122 .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");
7123 #[cfg(require_route_graph_test)]
7124 return Ok(res.unwrap());
7125 #[cfg(not(require_route_graph_test))]
7129 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
7130 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
7133 pub(crate) fn payer_pubkey() -> PublicKey {
7134 let secp_ctx = Secp256k1::new();
7135 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
7139 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
7141 channel_id: ChannelId::new_zero(),
7142 counterparty: ChannelCounterparty {
7143 features: channelmanager::provided_init_features(&UserConfig::default()),
7145 unspendable_punishment_reserve: 0,
7146 forwarding_info: None,
7147 outbound_htlc_minimum_msat: None,
7148 outbound_htlc_maximum_msat: None,
7150 funding_txo: Some(OutPoint {
7151 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
7154 short_channel_id: Some(1),
7155 inbound_scid_alias: None,
7156 outbound_scid_alias: None,
7157 channel_value_satoshis: 10_000_000_000,
7159 outbound_capacity_msat: 10_000_000_000,
7160 next_outbound_htlc_minimum_msat: 0,
7161 next_outbound_htlc_limit_msat: 10_000_000_000,
7162 inbound_capacity_msat: 0,
7163 unspendable_punishment_reserve: None,
7164 confirmations_required: None,
7165 confirmations: None,
7166 force_close_spend_delay: None,
7168 is_channel_ready: true,
7171 inbound_htlc_minimum_msat: None,
7172 inbound_htlc_maximum_msat: None,
7174 feerate_sat_per_1000_weight: None,
7175 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
7179 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
7180 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
7181 starting_amount: u64, route_count: usize,
7182 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
7183 let payer = payer_pubkey();
7184 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7185 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7187 let nodes = graph.read_only().nodes().clone();
7188 let mut route_endpoints = Vec::new();
7189 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
7190 // with some routes we picked being un-routable.
7191 for _ in 0..route_count * 3 / 2 {
7193 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7194 let src = PublicKey::from_slice(nodes.unordered_keys()
7195 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
7196 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7197 let dst = PublicKey::from_slice(nodes.unordered_keys()
7198 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
7199 let params = PaymentParameters::from_node_id(dst, 42)
7200 .with_bolt11_features(features.clone()).unwrap();
7201 let first_hop = first_hop(src);
7202 let amt_msat = starting_amount + seed % 1_000_000;
7203 let route_params = RouteParameters::from_payment_params_and_value(
7204 params.clone(), amt_msat);
7206 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
7207 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
7209 // ...and seed the scorer with success and failure data...
7210 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7211 let mut score_amt = seed % 1_000_000_000;
7213 // Generate fail/success paths for a wider range of potential amounts with
7214 // MPP enabled to give us a chance to apply penalties for more potential
7216 let mpp_features = channelmanager::provided_invoice_features(&UserConfig::default());
7217 let params = PaymentParameters::from_node_id(dst, 42)
7218 .with_bolt11_features(mpp_features).unwrap();
7219 let route_params = RouteParameters::from_payment_params_and_value(
7220 params.clone(), score_amt);
7221 let route_res = get_route(&payer, &route_params, &graph.read_only(),
7222 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
7223 &random_seed_bytes);
7224 if let Ok(route) = route_res {
7225 for path in route.paths {
7226 if seed & 0x80 == 0 {
7227 scorer.payment_path_successful(&path);
7229 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
7230 scorer.payment_path_failed(&path, short_channel_id);
7232 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7236 // If we couldn't find a path with a higer amount, reduce and try again.
7240 route_endpoints.push((first_hop, params, amt_msat));
7246 // Because we've changed channel scores, it's possible we'll take different routes to the
7247 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
7248 // requires a too-high CLTV delta.
7249 route_endpoints.retain(|(first_hop, params, amt_msat)| {
7250 let route_params = RouteParameters::from_payment_params_and_value(
7251 params.clone(), *amt_msat);
7252 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
7253 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
7255 route_endpoints.truncate(route_count);
7256 assert_eq!(route_endpoints.len(), route_count);
7264 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
7265 use crate::sign::{EntropySource, KeysManager};
7266 use crate::ln::channelmanager;
7267 use crate::ln::features::Bolt11InvoiceFeatures;
7268 use crate::routing::gossip::NetworkGraph;
7269 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
7270 use crate::util::config::UserConfig;
7271 use crate::util::logger::{Logger, Record};
7272 use crate::util::test_utils::TestLogger;
7274 use criterion::Criterion;
7276 struct DummyLogger {}
7277 impl Logger for DummyLogger {
7278 fn log(&self, _record: &Record) {}
7281 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7282 let logger = TestLogger::new();
7283 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7284 let scorer = FixedPenaltyScorer::with_penalty(0);
7285 generate_routes(bench, &network_graph, scorer, &(), Bolt11InvoiceFeatures::empty(), 0,
7286 "generate_routes_with_zero_penalty_scorer");
7289 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7290 let logger = TestLogger::new();
7291 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7292 let scorer = FixedPenaltyScorer::with_penalty(0);
7293 generate_routes(bench, &network_graph, scorer, &(),
7294 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7295 "generate_mpp_routes_with_zero_penalty_scorer");
7298 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7299 let logger = TestLogger::new();
7300 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7301 let params = ProbabilisticScoringFeeParameters::default();
7302 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7303 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
7304 "generate_routes_with_probabilistic_scorer");
7307 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7308 let logger = TestLogger::new();
7309 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7310 let params = ProbabilisticScoringFeeParameters::default();
7311 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7312 generate_routes(bench, &network_graph, scorer, ¶ms,
7313 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7314 "generate_mpp_routes_with_probabilistic_scorer");
7317 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7318 let logger = TestLogger::new();
7319 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7320 let params = ProbabilisticScoringFeeParameters::default();
7321 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7322 generate_routes(bench, &network_graph, scorer, ¶ms,
7323 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
7324 "generate_large_mpp_routes_with_probabilistic_scorer");
7327 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
7328 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
7329 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
7330 bench_name: &'static str,
7332 let payer = bench_utils::payer_pubkey();
7333 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7334 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7336 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
7337 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
7339 // ...then benchmark finding paths between the nodes we learned.
7341 bench.bench_function(bench_name, |b| b.iter(|| {
7342 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
7343 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
7344 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
7345 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());