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. Might be more than
363 /// requested if we had to reach htlc_minimum_msat.
364 pub fn get_total_amount(&self) -> u64 {
365 self.paths.iter().map(|path| path.final_value_msat()).sum()
369 const SERIALIZATION_VERSION: u8 = 1;
370 const MIN_SERIALIZATION_VERSION: u8 = 1;
372 impl Writeable for Route {
373 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
374 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
375 (self.paths.len() as u64).write(writer)?;
376 let mut blinded_tails = Vec::new();
377 for path in self.paths.iter() {
378 (path.hops.len() as u8).write(writer)?;
379 for (idx, hop) in path.hops.iter().enumerate() {
381 if let Some(blinded_tail) = &path.blinded_tail {
382 if blinded_tails.is_empty() {
383 blinded_tails = Vec::with_capacity(path.hops.len());
385 blinded_tails.push(None);
388 blinded_tails.push(Some(blinded_tail));
389 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
392 write_tlv_fields!(writer, {
393 // For compatibility with LDK versions prior to 0.0.117, we take the individual
394 // RouteParameters' fields and reconstruct them on read.
395 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
396 (2, blinded_tails, optional_vec),
397 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
403 impl Readable for Route {
404 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
405 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
406 let path_count: u64 = Readable::read(reader)?;
407 if path_count == 0 { return Err(DecodeError::InvalidValue); }
408 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
409 let mut min_final_cltv_expiry_delta = u32::max_value();
410 for _ in 0..path_count {
411 let hop_count: u8 = Readable::read(reader)?;
412 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
413 for _ in 0..hop_count {
414 hops.push(Readable::read(reader)?);
416 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
417 min_final_cltv_expiry_delta =
418 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
419 paths.push(Path { hops, blinded_tail: None });
421 _init_and_read_len_prefixed_tlv_fields!(reader, {
422 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
423 (2, blinded_tails, optional_vec),
424 (3, final_value_msat, option),
426 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
427 if blinded_tails.len() != 0 {
428 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
429 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
430 path.blinded_tail = blinded_tail_opt;
434 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
435 let route_params = match (payment_params, final_value_msat) {
436 (Some(payment_params), Some(final_value_msat)) => {
437 Some(RouteParameters { payment_params, final_value_msat })
442 Ok(Route { paths, route_params })
446 /// Parameters needed to find a [`Route`].
448 /// Passed to [`find_route`] and [`build_route_from_hops`].
449 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
450 pub struct RouteParameters {
451 /// The parameters of the failed payment path.
452 pub payment_params: PaymentParameters,
454 /// The amount in msats sent on the failed payment path.
455 pub final_value_msat: u64,
458 impl RouteParameters {
459 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
460 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
461 Self { payment_params, final_value_msat }
465 impl Writeable for RouteParameters {
466 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
467 write_tlv_fields!(writer, {
468 (0, self.payment_params, required),
469 (2, self.final_value_msat, required),
470 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
471 // `RouteParameters` directly. For compatibility, we write it here.
472 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
478 impl Readable for RouteParameters {
479 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
480 _init_and_read_len_prefixed_tlv_fields!(reader, {
481 (0, payment_params, (required: ReadableArgs, 0)),
482 (2, final_value_msat, required),
483 (4, final_cltv_delta, option),
485 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
486 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
487 if final_cltv_expiry_delta == &0 {
488 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
493 final_value_msat: final_value_msat.0.unwrap(),
498 /// Maximum total CTLV difference we allow for a full payment path.
499 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
501 /// Maximum number of paths we allow an (MPP) payment to have.
502 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
503 // limits, but for now more than 10 paths likely carries too much one-path failure.
504 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
506 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
508 // The median hop CLTV expiry delta currently seen in the network.
509 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
511 // During routing, we only consider paths shorter than our maximum length estimate.
512 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
513 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
514 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
516 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
517 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
518 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
519 // (payment_secret and total_msat) = 93 bytes for the final hop.
520 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
521 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
522 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
524 /// Information used to route a payment.
525 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
526 pub struct PaymentParameters {
527 /// Information about the payee, such as their features and route hints for their channels.
530 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
531 pub expiry_time: Option<u64>,
533 /// The maximum total CLTV delta we accept for the route.
534 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
535 pub max_total_cltv_expiry_delta: u32,
537 /// The maximum number of paths that may be used by (MPP) payments.
538 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
539 pub max_path_count: u8,
541 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
542 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
543 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
544 /// increasing failure probability for those paths.
546 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
547 /// restriction have been found. While paths which meet this criteria will be searched for, it
548 /// is ultimately up to the scorer to select them over other paths.
550 /// A value of 0 will allow payments up to and including a channel's total announced usable
551 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
554 pub max_channel_saturation_power_of_half: u8,
556 /// A list of SCIDs which this payment was previously attempted over and which caused the
557 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
559 pub previously_failed_channels: Vec<u64>,
562 impl Writeable for PaymentParameters {
563 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
564 let mut clear_hints = &vec![];
565 let mut blinded_hints = &vec![];
567 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
568 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
570 write_tlv_fields!(writer, {
571 (0, self.payee.node_id(), option),
572 (1, self.max_total_cltv_expiry_delta, required),
573 (2, self.payee.features(), option),
574 (3, self.max_path_count, required),
575 (4, *clear_hints, required_vec),
576 (5, self.max_channel_saturation_power_of_half, required),
577 (6, self.expiry_time, option),
578 (7, self.previously_failed_channels, required_vec),
579 (8, *blinded_hints, optional_vec),
580 (9, self.payee.final_cltv_expiry_delta(), option),
586 impl ReadableArgs<u32> for PaymentParameters {
587 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
588 _init_and_read_len_prefixed_tlv_fields!(reader, {
589 (0, payee_pubkey, option),
590 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
591 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
592 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
593 (4, clear_route_hints, required_vec),
594 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
595 (6, expiry_time, option),
596 (7, previously_failed_channels, optional_vec),
597 (8, blinded_route_hints, optional_vec),
598 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
600 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
601 let payee = if blinded_route_hints.len() != 0 {
602 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
604 route_hints: blinded_route_hints,
605 features: features.and_then(|f: Features| f.bolt12()),
609 route_hints: clear_route_hints,
610 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
611 features: features.and_then(|f| f.bolt11()),
612 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
616 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
617 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
619 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
621 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
627 impl PaymentParameters {
628 /// Creates a payee with the node id of the given `pubkey`.
630 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
632 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
634 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
636 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
637 max_path_count: DEFAULT_MAX_PATH_COUNT,
638 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
639 previously_failed_channels: Vec::new(),
643 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
645 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
648 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
649 /// whether your router will be allowed to find a multi-part route for this payment. If you
650 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
651 /// [`RecipientOnionFields::secret_only`].
653 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
654 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
655 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
656 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
657 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
660 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
661 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
662 /// [`PaymentParameters::expiry_time`].
663 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
664 Self::blinded(invoice.payment_paths().to_vec())
665 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
666 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
669 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
670 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
672 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
674 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
675 max_path_count: DEFAULT_MAX_PATH_COUNT,
676 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
677 previously_failed_channels: Vec::new(),
681 /// Includes the payee's features. Errors if the parameters were not initialized with
682 /// [`PaymentParameters::from_bolt12_invoice`].
684 /// This is not exported to bindings users since bindings don't support move semantics
685 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
687 Payee::Clear { .. } => Err(()),
688 Payee::Blinded { route_hints, .. } =>
689 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
693 /// Includes the payee's features. Errors if the parameters were initialized with
694 /// [`PaymentParameters::from_bolt12_invoice`].
696 /// This is not exported to bindings users since bindings don't support move semantics
697 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
699 Payee::Blinded { .. } => Err(()),
700 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
702 payee: Payee::Clear {
703 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
709 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
710 /// [`PaymentParameters::from_bolt12_invoice`].
712 /// This is not exported to bindings users since bindings don't support move semantics
713 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
715 Payee::Blinded { .. } => Err(()),
716 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
718 payee: Payee::Clear {
719 route_hints, node_id, features, final_cltv_expiry_delta,
725 /// Includes a payment expiration in seconds relative to the UNIX epoch.
727 /// This is not exported to bindings users since bindings don't support move semantics
728 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
729 Self { expiry_time: Some(expiry_time), ..self }
732 /// Includes a limit for the total CLTV expiry delta which is considered during routing
734 /// This is not exported to bindings users since bindings don't support move semantics
735 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
736 Self { max_total_cltv_expiry_delta, ..self }
739 /// Includes a limit for the maximum number of payment paths that may be used.
741 /// This is not exported to bindings users since bindings don't support move semantics
742 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
743 Self { max_path_count, ..self }
746 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
747 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
749 /// This is not exported to bindings users since bindings don't support move semantics
750 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
751 Self { max_channel_saturation_power_of_half, ..self }
755 /// The recipient of a payment, differing based on whether they've hidden their identity with route
757 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
759 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
760 /// will be included in the final [`Route`].
762 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
764 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
765 /// Features supported by the payee.
767 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
769 features: Option<Bolt12InvoiceFeatures>,
771 /// The recipient included these route hints in their BOLT11 invoice.
773 /// The node id of the payee.
775 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
776 route_hints: Vec<RouteHint>,
777 /// Features supported by the payee.
779 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
780 /// does not contain any features.
782 /// [`for_keysend`]: PaymentParameters::for_keysend
783 features: Option<Bolt11InvoiceFeatures>,
784 /// The minimum CLTV delta at the end of the route. This value must not be zero.
785 final_cltv_expiry_delta: u32,
790 fn node_id(&self) -> Option<PublicKey> {
792 Self::Clear { node_id, .. } => Some(*node_id),
796 fn node_features(&self) -> Option<NodeFeatures> {
798 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
799 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
802 fn supports_basic_mpp(&self) -> bool {
804 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
805 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
808 fn features(&self) -> Option<FeaturesRef> {
810 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
811 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
814 fn final_cltv_expiry_delta(&self) -> Option<u32> {
816 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
820 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
822 Self::Blinded { route_hints, .. } => &route_hints[..],
823 Self::Clear { .. } => &[]
827 fn unblinded_route_hints(&self) -> &[RouteHint] {
829 Self::Blinded { .. } => &[],
830 Self::Clear { route_hints, .. } => &route_hints[..]
835 enum FeaturesRef<'a> {
836 Bolt11(&'a Bolt11InvoiceFeatures),
837 Bolt12(&'a Bolt12InvoiceFeatures),
840 Bolt11(Bolt11InvoiceFeatures),
841 Bolt12(Bolt12InvoiceFeatures),
845 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
847 Self::Bolt12(f) => Some(f),
851 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
853 Self::Bolt11(f) => Some(f),
859 impl<'a> Writeable for FeaturesRef<'a> {
860 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
862 Self::Bolt11(f) => Ok(f.write(w)?),
863 Self::Bolt12(f) => Ok(f.write(w)?),
868 impl ReadableArgs<bool> for Features {
869 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
870 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
871 Ok(Self::Bolt12(Readable::read(reader)?))
875 /// A list of hops along a payment path terminating with a channel to the recipient.
876 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
877 pub struct RouteHint(pub Vec<RouteHintHop>);
879 impl Writeable for RouteHint {
880 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
881 (self.0.len() as u64).write(writer)?;
882 for hop in self.0.iter() {
889 impl Readable for RouteHint {
890 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
891 let hop_count: u64 = Readable::read(reader)?;
892 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
893 for _ in 0..hop_count {
894 hops.push(Readable::read(reader)?);
900 /// A channel descriptor for a hop along a payment path.
901 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
902 pub struct RouteHintHop {
903 /// The node_id of the non-target end of the route
904 pub src_node_id: PublicKey,
905 /// The short_channel_id of this channel
906 pub short_channel_id: u64,
907 /// The fees which must be paid to use this channel
908 pub fees: RoutingFees,
909 /// The difference in CLTV values between this node and the next node.
910 pub cltv_expiry_delta: u16,
911 /// The minimum value, in msat, which must be relayed to the next hop.
912 pub htlc_minimum_msat: Option<u64>,
913 /// The maximum value in msat available for routing with a single HTLC.
914 pub htlc_maximum_msat: Option<u64>,
917 impl_writeable_tlv_based!(RouteHintHop, {
918 (0, src_node_id, required),
919 (1, htlc_minimum_msat, option),
920 (2, short_channel_id, required),
921 (3, htlc_maximum_msat, option),
923 (6, cltv_expiry_delta, required),
926 #[derive(Eq, PartialEq)]
927 struct RouteGraphNode {
929 lowest_fee_to_node: u64,
930 total_cltv_delta: u32,
931 // The maximum value a yet-to-be-constructed payment path might flow through this node.
932 // This value is upper-bounded by us by:
933 // - how much is needed for a path being constructed
934 // - how much value can channels following this node (up to the destination) can contribute,
935 // considering their capacity and fees
936 value_contribution_msat: u64,
937 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
938 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
939 path_htlc_minimum_msat: u64,
940 /// All penalties incurred from this hop on the way to the destination, as calculated using
942 path_penalty_msat: u64,
943 /// The number of hops walked up to this node.
944 path_length_to_node: u8,
947 impl cmp::Ord for RouteGraphNode {
948 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
949 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
950 .saturating_add(other.path_penalty_msat);
951 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
952 .saturating_add(self.path_penalty_msat);
953 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
957 impl cmp::PartialOrd for RouteGraphNode {
958 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
959 Some(self.cmp(other))
963 /// A wrapper around the various hop representations.
965 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
966 #[derive(Clone, Debug)]
967 enum CandidateRouteHop<'a> {
968 /// A hop from the payer, where the outbound liquidity is known.
970 details: &'a ChannelDetails,
972 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
974 info: DirectedChannelInfo<'a>,
975 short_channel_id: u64,
977 /// A hop to the payee found in the BOLT 11 payment invoice, though not necessarily a direct
980 hint: &'a RouteHintHop,
982 /// The payee's identity is concealed behind blinded paths provided in a BOLT 12 invoice.
984 hint: &'a (BlindedPayInfo, BlindedPath),
987 /// Similar to [`Self::Blinded`], but the path here has 1 blinded hop. `BlindedPayInfo` provided
988 /// for 1-hop blinded paths is ignored because it is meant to apply to the hops *between* the
989 /// introduction node and the destination. Useful for tracking that we need to include a blinded
990 /// path at the end of our [`Route`].
992 hint: &'a (BlindedPayInfo, BlindedPath),
997 impl<'a> CandidateRouteHop<'a> {
998 fn short_channel_id(&self) -> Option<u64> {
1000 CandidateRouteHop::FirstHop { details } => Some(details.get_outbound_payment_scid().unwrap()),
1001 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
1002 CandidateRouteHop::PrivateHop { hint } => Some(hint.short_channel_id),
1003 CandidateRouteHop::Blinded { .. } => None,
1004 CandidateRouteHop::OneHopBlinded { .. } => None,
1008 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1009 fn features(&self) -> ChannelFeatures {
1011 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
1012 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
1013 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
1014 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
1015 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
1019 fn cltv_expiry_delta(&self) -> u32 {
1021 CandidateRouteHop::FirstHop { .. } => 0,
1022 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1023 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
1024 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1025 CandidateRouteHop::OneHopBlinded { .. } => 0,
1029 fn htlc_minimum_msat(&self) -> u64 {
1031 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_minimum_msat,
1032 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1033 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
1034 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1035 CandidateRouteHop::OneHopBlinded { .. } => 0,
1039 fn fees(&self) -> RoutingFees {
1041 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1042 base_msat: 0, proportional_millionths: 0,
1044 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1045 CandidateRouteHop::PrivateHop { hint } => hint.fees,
1046 CandidateRouteHop::Blinded { hint, .. } => {
1048 base_msat: hint.0.fee_base_msat,
1049 proportional_millionths: hint.0.fee_proportional_millionths
1052 CandidateRouteHop::OneHopBlinded { .. } =>
1053 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1057 fn effective_capacity(&self) -> EffectiveCapacity {
1059 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
1060 liquidity_msat: details.next_outbound_htlc_limit_msat,
1062 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1063 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }} =>
1064 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1065 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }} =>
1066 EffectiveCapacity::Infinite,
1067 CandidateRouteHop::Blinded { hint, .. } =>
1068 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1069 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1073 fn id(&self, channel_direction: bool /* src_node_id < target_node_id */) -> CandidateHopId {
1075 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1076 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1077 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), channel_direction)),
1080 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1082 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1090 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1091 enum CandidateHopId {
1092 /// Contains (scid, src_node_id < target_node_id)
1094 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1099 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1100 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1102 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1103 EffectiveCapacity::Infinite => u64::max_value(),
1104 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1105 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1106 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1107 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1108 // expected to have been generated from up-to-date capacity information.
1109 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1110 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1111 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1115 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1116 -> bool where I1::Item: PartialEq<I2::Item> {
1118 let a = iter_a.next();
1119 let b = iter_b.next();
1120 if a.is_none() && b.is_none() { return true; }
1121 if a.is_none() || b.is_none() { return false; }
1122 if a.unwrap().ne(&b.unwrap()) { return false; }
1126 /// It's useful to keep track of the hops associated with the fees required to use them,
1127 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1128 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1129 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1131 struct PathBuildingHop<'a> {
1132 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
1133 // is a larger refactor and will require careful performance analysis.
1135 candidate: CandidateRouteHop<'a>,
1138 /// All the fees paid *after* this channel on the way to the destination
1139 next_hops_fee_msat: u64,
1140 /// Fee paid for the use of the current channel (see candidate.fees()).
1141 /// The value will be actually deducted from the counterparty balance on the previous link.
1142 hop_use_fee_msat: u64,
1143 /// Used to compare channels when choosing the for routing.
1144 /// Includes paying for the use of a hop and the following hops, as well as
1145 /// an estimated cost of reaching this hop.
1146 /// Might get stale when fees are recomputed. Primarily for internal use.
1147 total_fee_msat: u64,
1148 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1149 /// walk and may be invalid thereafter.
1150 path_htlc_minimum_msat: u64,
1151 /// All penalties incurred from this channel on the way to the destination, as calculated using
1152 /// channel scoring.
1153 path_penalty_msat: u64,
1154 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1155 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1156 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1157 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1158 /// avoid processing them again.
1159 was_processed: bool,
1160 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1161 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1162 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1163 // value_contribution_msat, which requires tracking it here. See comments below where it is
1164 // used for more info.
1165 value_contribution_msat: u64,
1168 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1169 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1170 let mut debug_struct = f.debug_struct("PathBuildingHop");
1172 .field("node_id", &self.node_id)
1173 .field("short_channel_id", &self.candidate.short_channel_id())
1174 .field("total_fee_msat", &self.total_fee_msat)
1175 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1176 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1177 .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)))
1178 .field("path_penalty_msat", &self.path_penalty_msat)
1179 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1180 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1181 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1182 let debug_struct = debug_struct
1183 .field("value_contribution_msat", &self.value_contribution_msat);
1184 debug_struct.finish()
1188 // Instantiated with a list of hops with correct data in them collected during path finding,
1189 // an instance of this struct should be further modified only via given methods.
1191 struct PaymentPath<'a> {
1192 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1195 impl<'a> PaymentPath<'a> {
1196 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1197 fn get_value_msat(&self) -> u64 {
1198 self.hops.last().unwrap().0.fee_msat
1201 fn get_path_penalty_msat(&self) -> u64 {
1202 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1205 fn get_total_fee_paid_msat(&self) -> u64 {
1206 if self.hops.len() < 1 {
1210 // Can't use next_hops_fee_msat because it gets outdated.
1211 for (i, (hop, _)) in self.hops.iter().enumerate() {
1212 if i != self.hops.len() - 1 {
1213 result += hop.fee_msat;
1219 fn get_cost_msat(&self) -> u64 {
1220 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1223 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1224 // to change fees may result in an inconsistency.
1226 // Sometimes we call this function right after constructing a path which is inconsistent in
1227 // that it the value being transferred has decreased while we were doing path finding, leading
1228 // to the fees being paid not lining up with the actual limits.
1230 // Note that this function is not aware of the available_liquidity limit, and thus does not
1231 // support increasing the value being transferred beyond what was selected during the initial
1233 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
1234 let mut total_fee_paid_msat = 0 as u64;
1235 for i in (0..self.hops.len()).rev() {
1236 let last_hop = i == self.hops.len() - 1;
1238 // For non-last-hop, this value will represent the fees paid on the current hop. It
1239 // will consist of the fees for the use of the next hop, and extra fees to match
1240 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1241 let mut cur_hop_fees_msat = 0;
1243 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1246 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1247 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1248 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1249 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1250 // set it too high just to maliciously take more fees by exploiting this
1251 // match htlc_minimum_msat logic.
1252 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1253 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1254 // Note that there is a risk that *previous hops* (those closer to us, as we go
1255 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1257 // This might make us end up with a broken route, although this should be super-rare
1258 // in practice, both because of how healthy channels look like, and how we pick
1259 // channels in add_entry.
1260 // Also, this can't be exploited more heavily than *announce a free path and fail
1262 cur_hop_transferred_amount_msat += extra_fees_msat;
1263 total_fee_paid_msat += extra_fees_msat;
1264 cur_hop_fees_msat += extra_fees_msat;
1268 // Final hop is a special case: it usually has just value_msat (by design), but also
1269 // it still could overpay for the htlc_minimum_msat.
1270 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1272 // Propagate updated fees for the use of the channels to one hop back, where they
1273 // will be actually paid (fee_msat). The last hop is handled above separately.
1274 cur_hop.fee_msat = cur_hop_fees_msat;
1277 // Fee for the use of the current hop which will be deducted on the previous hop.
1278 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1279 // this channel is free for us.
1281 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1282 cur_hop.hop_use_fee_msat = new_fee;
1283 total_fee_paid_msat += new_fee;
1285 // It should not be possible because this function is called only to reduce the
1286 // value. In that case, compute_fee was already called with the same fees for
1287 // larger amount and there was no overflow.
1296 /// Calculate the fees required to route the given amount over a channel with the given fees.
1297 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1298 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1299 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1303 /// Calculate the fees required to route the given amount over a channel with the given fees,
1304 /// saturating to [`u64::max_value`].
1305 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1306 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1307 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1308 .saturating_add(channel_fees.base_msat as u64)
1311 /// The default `features` we assume for a node in a route, when no `features` are known about that
1314 /// Default features are:
1315 /// * variable_length_onion_optional
1316 fn default_node_features() -> NodeFeatures {
1317 let mut features = NodeFeatures::empty();
1318 features.set_variable_length_onion_optional();
1322 struct LoggedPayeePubkey(Option<PublicKey>);
1323 impl fmt::Display for LoggedPayeePubkey {
1324 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1327 "payee node id ".fmt(f)?;
1331 "blinded payee".fmt(f)
1337 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1338 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1339 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1341 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1342 "blinded route hint with introduction node id ".fmt(f)?;
1343 hint.1.introduction_node_id.fmt(f)?;
1344 " and blinding point ".fmt(f)?;
1345 hint.1.blinding_point.fmt(f)
1347 CandidateRouteHop::FirstHop { .. } => {
1348 "first hop with SCID ".fmt(f)?;
1349 self.0.short_channel_id().unwrap().fmt(f)
1351 CandidateRouteHop::PrivateHop { .. } => {
1352 "route hint with SCID ".fmt(f)?;
1353 self.0.short_channel_id().unwrap().fmt(f)
1357 self.0.short_channel_id().unwrap().fmt(f)
1364 fn sort_first_hop_channels(
1365 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1366 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1368 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1369 // most like to use.
1371 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1372 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1375 // Second, because simply always sorting in descending order would always use our largest
1376 // available outbound capacity, needlessly fragmenting our available channel capacities,
1377 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1378 // which have enough, but not too much, capacity for the payment.
1380 // Available outbound balances factor in liquidity already reserved for previously found paths.
1381 channels.sort_unstable_by(|chan_a, chan_b| {
1382 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1383 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1384 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1385 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1386 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1387 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1388 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1389 // Sort in descending order
1390 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1392 // Sort in ascending order
1393 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1398 /// Finds a route from us (payer) to the given target node (payee).
1400 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1401 /// in the given [`RouteParameters::payment_params`].
1402 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1404 /// Private routing paths between a public node and the target may be included in the `payee` field
1405 /// of [`RouteParameters::payment_params`].
1407 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1408 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1409 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1411 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1412 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1413 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1417 /// Panics if first_hops contains channels without `short_channel_id`s;
1418 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1420 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1421 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1422 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1423 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1424 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1425 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1426 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1427 ) -> Result<Route, LightningError>
1428 where L::Target: Logger, GL::Target: Logger {
1429 let graph_lock = network_graph.read_only();
1430 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1431 scorer, score_params, random_seed_bytes)?;
1432 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1436 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1437 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1438 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1439 _random_seed_bytes: &[u8; 32]
1440 ) -> Result<Route, LightningError>
1441 where L::Target: Logger {
1443 let payment_params = &route_params.payment_params;
1444 let final_value_msat = route_params.final_value_msat;
1445 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1446 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1447 // so use a dummy id for this in the blinded case.
1448 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1449 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1450 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1451 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1452 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1454 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1455 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1458 if final_value_msat > MAX_VALUE_MSAT {
1459 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1462 if final_value_msat == 0 {
1463 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1466 match &payment_params.payee {
1467 Payee::Clear { route_hints, node_id, .. } => {
1468 for route in route_hints.iter() {
1469 for hop in &route.0 {
1470 if hop.src_node_id == *node_id {
1471 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1476 Payee::Blinded { route_hints, .. } => {
1477 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1478 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});
1480 for (_, blinded_path) in route_hints.iter() {
1481 if blinded_path.blinded_hops.len() == 0 {
1482 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1483 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1484 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1485 } else if blinded_path.blinded_hops.len() == 1 &&
1486 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1487 && p.introduction_node_id != blinded_path.introduction_node_id)
1489 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1494 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1495 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1496 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});
1499 // The general routing idea is the following:
1500 // 1. Fill first/last hops communicated by the caller.
1501 // 2. Attempt to construct a path from payer to payee for transferring
1502 // any ~sufficient (described later) value.
1503 // If succeed, remember which channels were used and how much liquidity they have available,
1504 // so that future paths don't rely on the same liquidity.
1505 // 3. Proceed to the next step if:
1506 // - we hit the recommended target value;
1507 // - OR if we could not construct a new path. Any next attempt will fail too.
1508 // Otherwise, repeat step 2.
1509 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1510 // (not recommended value).
1511 // 5. If yes, proceed. If not, fail routing.
1512 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1513 // transferred up to the transfer target value.
1514 // 7. Reduce the value of the last path until we are sending only the target value.
1515 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1516 // them so that we're not sending two HTLCs along the same path.
1518 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1519 // distance from the payee
1521 // We are not a faithful Dijkstra's implementation because we can change values which impact
1522 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1523 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1524 // the value we are currently attempting to send over a path, we simply reduce the value being
1525 // sent along the path for any hops after that channel. This may imply that later fees (which
1526 // we've already tabulated) are lower because a smaller value is passing through the channels
1527 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1528 // channels which were selected earlier (and which may still be used for other paths without a
1529 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1532 // One potentially problematic case for this algorithm would be if there are many
1533 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1534 // graph walking), we may never find a path which is not liquidity-limited and has lower
1535 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1536 // Because we only consider paths with at least 5% of the total value being sent, the damage
1537 // from such a case should be limited, however this could be further reduced in the future by
1538 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1539 // limits for the purposes of fee calculation.
1541 // Alternatively, we could store more detailed path information in the heap (targets, below)
1542 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1543 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1544 // and practically (as we would need to store dynamically-allocated path information in heap
1545 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1546 // results of such an algorithm would likely be biased towards lower-value paths.
1548 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1549 // outside of our current search value, running a path search more times to gather candidate
1550 // paths at different values. While this may be acceptable, further path searches may increase
1551 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1552 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1553 // the same time, remaining generic across different payment values.
1555 let network_channels = network_graph.channels();
1556 let network_nodes = network_graph.nodes();
1558 if payment_params.max_path_count == 0 {
1559 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1562 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1563 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1565 let allow_mpp = if payment_params.max_path_count == 1 {
1567 } else if payment_params.payee.supports_basic_mpp() {
1569 } else if let Some(payee) = payee_node_id_opt {
1570 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1571 |info| info.features.supports_basic_mpp()))
1574 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1575 LoggedPayeePubkey(payment_params.payee.node_id()), if allow_mpp { "with" } else { "without" },
1576 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1579 // Prepare the data we'll use for payee-to-payer search by
1580 // inserting first hops suggested by the caller as targets.
1581 // Our search will then attempt to reach them while traversing from the payee node.
1582 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1583 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1584 if let Some(hops) = first_hops {
1586 if chan.get_outbound_payment_scid().is_none() {
1587 panic!("first_hops should be filled in with usable channels, not pending ones");
1589 if chan.counterparty.node_id == *our_node_pubkey {
1590 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1593 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1594 .or_insert(Vec::new())
1597 if first_hop_targets.is_empty() {
1598 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1602 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1603 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1604 // adding duplicate entries when we find a better path to a given node.
1605 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1607 // Map from node_id to information about the best current path to that node, including feerate
1609 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1611 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1612 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1613 // htlc_minimum with extra fees while still finding a cheaper path.
1614 let mut hit_minimum_limit;
1616 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1617 // We start with a path_value of the exact amount we want, and if that generates a route we may
1618 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1619 // amount we want in total across paths, selecting the best subset at the end.
1620 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1621 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1622 let mut path_value_msat = final_value_msat;
1624 // Routing Fragmentation Mitigation heuristic:
1626 // Routing fragmentation across many payment paths increases the overall routing
1627 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1628 // Taking too many smaller paths also increases the chance of payment failure.
1629 // Thus to avoid this effect, we require from our collected links to provide
1630 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1631 // This requirement is currently set to be 1/max_path_count of the payment
1632 // value to ensure we only ever return routes that do not violate this limit.
1633 let minimal_value_contribution_msat: u64 = if allow_mpp {
1634 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1639 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1640 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1641 // drop the requirement by setting this to 0.
1642 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1644 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1645 // determine if the channel can be used by additional MPP paths or to inform path finding
1646 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1647 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1649 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1650 HashMap::with_capacity(network_nodes.len());
1652 // Keeping track of how much value we already collected across other paths. Helps to decide
1653 // when we want to stop looking for new paths.
1654 let mut already_collected_value_msat = 0;
1656 for (_, channels) in first_hop_targets.iter_mut() {
1657 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1661 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1662 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1664 // Remember how many candidates we ignored to allow for some logging afterwards.
1665 let mut num_ignored_value_contribution = 0;
1666 let mut num_ignored_path_length_limit = 0;
1667 let mut num_ignored_cltv_delta_limit = 0;
1668 let mut num_ignored_previously_failed = 0;
1670 macro_rules! add_entry {
1671 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1672 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1673 // since that value has to be transferred over this channel.
1674 // Returns whether this channel caused an update to `targets`.
1675 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1676 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1677 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1678 // We "return" whether we updated the path at the end, and how much we can route via
1679 // this channel, via this:
1680 let mut did_add_update_path_to_src_node = None;
1681 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1682 // practice these cases should be caught earlier:
1683 // - for regular channels at channel announcement (TODO)
1684 // - for first and last hops early in get_route
1685 if $src_node_id != $dest_node_id {
1686 let scid_opt = $candidate.short_channel_id();
1687 let effective_capacity = $candidate.effective_capacity();
1688 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1690 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1691 // It may be misleading because we might later choose to reduce the value transferred
1692 // over these channels, and the channel which was insufficient might become sufficient.
1693 // Worst case: we drop a good channel here because it can't cover the high following
1694 // fees caused by one expensive channel, but then this channel could have been used
1695 // if the amount being transferred over this path is lower.
1696 // We do this for now, but this is a subject for removal.
1697 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1698 let used_liquidity_msat = used_liquidities
1699 .get(&$candidate.id($src_node_id < $dest_node_id))
1700 .map_or(0, |used_liquidity_msat| {
1701 available_value_contribution_msat = available_value_contribution_msat
1702 .saturating_sub(*used_liquidity_msat);
1703 *used_liquidity_msat
1706 // Verify the liquidity offered by this channel complies to the minimal contribution.
1707 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1708 // Do not consider candidate hops that would exceed the maximum path length.
1709 let path_length_to_node = $next_hops_path_length + 1;
1710 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1712 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1713 // In order to already account for some of the privacy enhancing random CLTV
1714 // expiry delta offset we add on top later, we subtract a rough estimate
1715 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1716 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1717 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1718 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1719 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1720 .saturating_add($candidate.cltv_expiry_delta());
1721 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1723 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1724 // Includes paying fees for the use of the following channels.
1725 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1726 Some(result) => result,
1727 // Can't overflow due to how the values were computed right above.
1728 None => unreachable!(),
1730 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1731 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1732 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1734 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1735 let may_overpay_to_meet_path_minimum_msat =
1736 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1737 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1738 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1739 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1741 let payment_failed_on_this_channel = scid_opt.map_or(false,
1742 |scid| payment_params.previously_failed_channels.contains(&scid));
1744 let should_log_candidate = match $candidate {
1745 CandidateRouteHop::FirstHop { .. } => true,
1746 CandidateRouteHop::PrivateHop { .. } => true,
1747 CandidateRouteHop::Blinded { .. } => true,
1751 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1752 // bother considering this channel. If retrying with recommended_value_msat may
1753 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1754 // around again with a higher amount.
1755 if !contributes_sufficient_value {
1756 if should_log_candidate {
1757 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
1759 num_ignored_value_contribution += 1;
1760 } else if exceeds_max_path_length {
1761 if should_log_candidate {
1762 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
1764 num_ignored_path_length_limit += 1;
1765 } else if exceeds_cltv_delta_limit {
1766 if should_log_candidate {
1767 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
1769 num_ignored_cltv_delta_limit += 1;
1770 } else if payment_failed_on_this_channel {
1771 if should_log_candidate {
1772 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
1774 num_ignored_previously_failed += 1;
1775 } else if may_overpay_to_meet_path_minimum_msat {
1776 hit_minimum_limit = true;
1777 } else if over_path_minimum_msat {
1778 // Note that low contribution here (limited by available_liquidity_msat)
1779 // might violate htlc_minimum_msat on the hops which are next along the
1780 // payment path (upstream to the payee). To avoid that, we recompute
1781 // path fees knowing the final path contribution after constructing it.
1782 let path_htlc_minimum_msat = cmp::max(
1783 compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1784 .saturating_add($next_hops_path_htlc_minimum_msat),
1785 $candidate.htlc_minimum_msat());
1786 let hm_entry = dist.entry($src_node_id);
1787 let old_entry = hm_entry.or_insert_with(|| {
1788 // If there was previously no known way to access the source node
1789 // (recall it goes payee-to-payer) of short_channel_id, first add a
1790 // semi-dummy record just to compute the fees to reach the source node.
1791 // This will affect our decision on selecting short_channel_id
1792 // as a way to reach the $dest_node_id.
1794 node_id: $dest_node_id.clone(),
1795 candidate: $candidate.clone(),
1797 next_hops_fee_msat: u64::max_value(),
1798 hop_use_fee_msat: u64::max_value(),
1799 total_fee_msat: u64::max_value(),
1800 path_htlc_minimum_msat,
1801 path_penalty_msat: u64::max_value(),
1802 was_processed: false,
1803 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1804 value_contribution_msat,
1808 #[allow(unused_mut)] // We only use the mut in cfg(test)
1809 let mut should_process = !old_entry.was_processed;
1810 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1812 // In test/fuzzing builds, we do extra checks to make sure the skipping
1813 // of already-seen nodes only happens in cases we expect (see below).
1814 if !should_process { should_process = true; }
1818 let mut hop_use_fee_msat = 0;
1819 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1821 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1822 // will have the same effective-fee
1823 if $src_node_id != our_node_id {
1824 // Note that `u64::max_value` means we'll always fail the
1825 // `old_entry.total_fee_msat > total_fee_msat` check below
1826 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1827 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1830 let channel_usage = ChannelUsage {
1831 amount_msat: amount_to_transfer_over_msat,
1832 inflight_htlc_msat: used_liquidity_msat,
1835 let channel_penalty_msat = scid_opt.map_or(0,
1836 |scid| scorer.channel_penalty_msat(scid, &$src_node_id, &$dest_node_id,
1837 channel_usage, score_params));
1838 let path_penalty_msat = $next_hops_path_penalty_msat
1839 .saturating_add(channel_penalty_msat);
1840 let new_graph_node = RouteGraphNode {
1841 node_id: $src_node_id,
1842 lowest_fee_to_node: total_fee_msat,
1843 total_cltv_delta: hop_total_cltv_delta,
1844 value_contribution_msat,
1845 path_htlc_minimum_msat,
1847 path_length_to_node,
1850 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1851 // if this way is cheaper than the already known
1852 // (considering the cost to "reach" this channel from the route destination,
1853 // the cost of using this channel,
1854 // and the cost of routing to the source node of this channel).
1855 // Also, consider that htlc_minimum_msat_difference, because we might end up
1856 // paying it. Consider the following exploit:
1857 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1858 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1859 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1860 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1862 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1863 // but it may require additional tracking - we don't want to double-count
1864 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1865 // can't use something that may decrease on future hops.
1866 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1867 .saturating_add(old_entry.path_penalty_msat);
1868 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1869 .saturating_add(path_penalty_msat);
1871 if !old_entry.was_processed && new_cost < old_cost {
1872 targets.push(new_graph_node);
1873 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1874 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1875 old_entry.total_fee_msat = total_fee_msat;
1876 old_entry.node_id = $dest_node_id.clone();
1877 old_entry.candidate = $candidate.clone();
1878 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1879 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1880 old_entry.path_penalty_msat = path_penalty_msat;
1881 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1883 old_entry.value_contribution_msat = value_contribution_msat;
1885 did_add_update_path_to_src_node = Some(value_contribution_msat);
1886 } else if old_entry.was_processed && new_cost < old_cost {
1887 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1889 // If we're skipping processing a node which was previously
1890 // processed even though we found another path to it with a
1891 // cheaper fee, check that it was because the second path we
1892 // found (which we are processing now) has a lower value
1893 // contribution due to an HTLC minimum limit.
1895 // e.g. take a graph with two paths from node 1 to node 2, one
1896 // through channel A, and one through channel B. Channel A and
1897 // B are both in the to-process heap, with their scores set by
1898 // a higher htlc_minimum than fee.
1899 // Channel A is processed first, and the channels onwards from
1900 // node 1 are added to the to-process heap. Thereafter, we pop
1901 // Channel B off of the heap, note that it has a much more
1902 // restrictive htlc_maximum_msat, and recalculate the fees for
1903 // all of node 1's channels using the new, reduced, amount.
1905 // This would be bogus - we'd be selecting a higher-fee path
1906 // with a lower htlc_maximum_msat instead of the one we'd
1907 // already decided to use.
1908 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1910 value_contribution_msat + path_penalty_msat <
1911 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1919 did_add_update_path_to_src_node
1923 let default_node_features = default_node_features();
1925 // Find ways (channels with destination) to reach a given node and store them
1926 // in the corresponding data structures (routing graph etc).
1927 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1928 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1929 // This data can later be helpful to optimize routing (pay lower fees).
1930 macro_rules! add_entries_to_cheapest_to_target_node {
1931 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1932 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1933 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1934 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1935 let was_processed = elem.was_processed;
1936 elem.was_processed = true;
1939 // Entries are added to dist in add_entry!() when there is a channel from a node.
1940 // Because there are no channels from payee, it will not have a dist entry at this point.
1941 // If we're processing any other node, it is always be the result of a channel from it.
1942 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
1947 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1948 for details in first_channels {
1949 let candidate = CandidateRouteHop::FirstHop { details };
1950 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1951 $next_hops_value_contribution,
1952 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1953 $next_hops_cltv_delta, $next_hops_path_length);
1957 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1960 &default_node_features
1963 if !features.requires_unknown_bits() {
1964 for chan_id in $node.channels.iter() {
1965 let chan = network_channels.get(chan_id).unwrap();
1966 if !chan.features.requires_unknown_bits() {
1967 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1968 if first_hops.is_none() || *source != our_node_id {
1969 if directed_channel.direction().enabled {
1970 let candidate = CandidateRouteHop::PublicHop {
1971 info: directed_channel,
1972 short_channel_id: *chan_id,
1974 add_entry!(candidate, *source, $node_id,
1975 $fee_to_target_msat,
1976 $next_hops_value_contribution,
1977 $next_hops_path_htlc_minimum_msat,
1978 $next_hops_path_penalty_msat,
1979 $next_hops_cltv_delta, $next_hops_path_length);
1990 let mut payment_paths = Vec::<PaymentPath>::new();
1992 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1993 'paths_collection: loop {
1994 // For every new path, start from scratch, except for used_liquidities, which
1995 // helps to avoid reusing previously selected paths in future iterations.
1998 hit_minimum_limit = false;
2000 // If first hop is a private channel and the only way to reach the payee, this is the only
2001 // place where it could be added.
2002 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2003 for details in first_channels {
2004 let candidate = CandidateRouteHop::FirstHop { details };
2005 let added = add_entry!(candidate, our_node_id, payee, 0, path_value_msat,
2006 0, 0u64, 0, 0).is_some();
2007 log_trace!(logger, "{} direct route to payee via {}",
2008 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2012 // Add the payee as a target, so that the payee-to-payer
2013 // search algorithm knows what to start with.
2014 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2015 // The payee is not in our network graph, so nothing to add here.
2016 // There is still a chance of reaching them via last_hops though,
2017 // so don't yet fail the payment here.
2018 // If not, targets.pop() will not even let us enter the loop in step 2.
2021 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
2026 // If a caller provided us with last hops, add them to routing targets. Since this happens
2027 // earlier than general path finding, they will be somewhat prioritized, although currently
2028 // it matters only if the fees are exactly the same.
2029 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2030 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2031 let have_intro_node_in_graph =
2032 // Only add the hops in this route to our candidate set if either
2033 // we have a direct channel to the first hop or the first hop is
2034 // in the regular network graph.
2035 first_hop_targets.get(&intro_node_id).is_some() ||
2036 network_nodes.get(&intro_node_id).is_some();
2037 if !have_intro_node_in_graph { continue }
2038 let candidate = if hint.1.blinded_hops.len() == 1 {
2039 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
2040 } else { CandidateRouteHop::Blinded { hint, hint_idx } };
2041 let mut path_contribution_msat = path_value_msat;
2042 if let Some(hop_used_msat) = add_entry!(candidate, intro_node_id, maybe_dummy_payee_node_id,
2043 0, path_contribution_msat, 0, 0_u64, 0, 0)
2045 path_contribution_msat = hop_used_msat;
2047 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2048 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2050 for details in first_channels {
2051 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2052 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2056 add_entry!(first_hop_candidate, our_node_id, intro_node_id, blinded_path_fee,
2057 path_contribution_msat, candidate.htlc_minimum_msat(), 0_u64,
2058 candidate.cltv_expiry_delta(),
2059 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2063 for route in payment_params.payee.unblinded_route_hints().iter()
2064 .filter(|route| !route.0.is_empty())
2066 let first_hop_in_route = &(route.0)[0];
2067 let have_hop_src_in_graph =
2068 // Only add the hops in this route to our candidate set if either
2069 // we have a direct channel to the first hop or the first hop is
2070 // in the regular network graph.
2071 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
2072 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
2073 if have_hop_src_in_graph {
2074 // We start building the path from reverse, i.e., from payee
2075 // to the first RouteHintHop in the path.
2076 let hop_iter = route.0.iter().rev();
2077 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2078 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2079 let mut hop_used = true;
2080 let mut aggregate_next_hops_fee_msat: u64 = 0;
2081 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2082 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2083 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2084 let mut aggregate_next_hops_path_length: u8 = 0;
2085 let mut aggregate_path_contribution_msat = path_value_msat;
2087 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2088 let source = NodeId::from_pubkey(&hop.src_node_id);
2089 let target = NodeId::from_pubkey(&prev_hop_id);
2090 let candidate = network_channels
2091 .get(&hop.short_channel_id)
2092 .and_then(|channel| channel.as_directed_to(&target))
2093 .map(|(info, _)| CandidateRouteHop::PublicHop {
2095 short_channel_id: hop.short_channel_id,
2097 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
2099 if let Some(hop_used_msat) = add_entry!(candidate, source, target,
2100 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2101 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2102 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2104 aggregate_path_contribution_msat = hop_used_msat;
2106 // If this hop was not used then there is no use checking the preceding
2107 // hops in the RouteHint. We can break by just searching for a direct
2108 // channel between last checked hop and first_hop_targets.
2112 let used_liquidity_msat = used_liquidities
2113 .get(&candidate.id(source < target)).copied()
2115 let channel_usage = ChannelUsage {
2116 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2117 inflight_htlc_msat: used_liquidity_msat,
2118 effective_capacity: candidate.effective_capacity(),
2120 let channel_penalty_msat = scorer.channel_penalty_msat(
2121 hop.short_channel_id, &source, &target, channel_usage, score_params
2123 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2124 .saturating_add(channel_penalty_msat);
2126 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2127 .saturating_add(hop.cltv_expiry_delta as u32);
2129 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2132 // Searching for a direct channel between last checked hop and first_hop_targets
2133 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&prev_hop_id)) {
2134 sort_first_hop_channels(first_channels, &used_liquidities,
2135 recommended_value_msat, our_node_pubkey);
2136 for details in first_channels {
2137 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2138 add_entry!(first_hop_candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
2139 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2140 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2141 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2149 // In the next values of the iterator, the aggregate fees already reflects
2150 // the sum of value sent from payer (final_value_msat) and routing fees
2151 // for the last node in the RouteHint. We need to just add the fees to
2152 // route through the current node so that the preceding node (next iteration)
2154 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2155 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2156 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2158 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
2159 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
2160 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
2161 .checked_add(hop_htlc_minimum_msat_inc);
2162 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
2164 if idx == route.0.len() - 1 {
2165 // The last hop in this iterator is the first hop in
2166 // overall RouteHint.
2167 // If this hop connects to a node with which we have a direct channel,
2168 // ignore the network graph and, if the last hop was added, add our
2169 // direct channel to the candidate set.
2171 // Note that we *must* check if the last hop was added as `add_entry`
2172 // always assumes that the third argument is a node to which we have a
2174 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2175 sort_first_hop_channels(first_channels, &used_liquidities,
2176 recommended_value_msat, our_node_pubkey);
2177 for details in first_channels {
2178 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2179 add_entry!(first_hop_candidate, our_node_id,
2180 NodeId::from_pubkey(&hop.src_node_id),
2181 aggregate_next_hops_fee_msat,
2182 aggregate_path_contribution_msat,
2183 aggregate_next_hops_path_htlc_minimum_msat,
2184 aggregate_next_hops_path_penalty_msat,
2185 aggregate_next_hops_cltv_delta,
2186 aggregate_next_hops_path_length);
2194 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2196 // At this point, targets are filled with the data from first and
2197 // last hops communicated by the caller, and the payment receiver.
2198 let mut found_new_path = false;
2201 // If this loop terminates due the exhaustion of targets, two situations are possible:
2202 // - not enough outgoing liquidity:
2203 // 0 < already_collected_value_msat < final_value_msat
2204 // - enough outgoing liquidity:
2205 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2206 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2207 // paths_collection will be stopped because found_new_path==false.
2208 // This is not necessarily a routing failure.
2209 '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() {
2211 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2212 // traversing the graph and arrange the path out of what we found.
2213 if node_id == our_node_id {
2214 let mut new_entry = dist.remove(&our_node_id).unwrap();
2215 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2218 let mut features_set = false;
2219 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
2220 for details in first_channels {
2221 if let Some(scid) = ordered_hops.last().unwrap().0.candidate.short_channel_id() {
2222 if details.get_outbound_payment_scid().unwrap() == scid {
2223 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2224 features_set = true;
2231 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
2232 if let Some(node_info) = node.announcement_info.as_ref() {
2233 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2235 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2238 // We can fill in features for everything except hops which were
2239 // provided via the invoice we're paying. We could guess based on the
2240 // recipient's features but for now we simply avoid guessing at all.
2244 // Means we succesfully traversed from the payer to the payee, now
2245 // save this path for the payment route. Also, update the liquidity
2246 // remaining on the used hops, so that we take them into account
2247 // while looking for more paths.
2248 if ordered_hops.last().unwrap().0.node_id == maybe_dummy_payee_node_id {
2252 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
2253 Some(payment_hop) => payment_hop,
2254 // We can't arrive at None because, if we ever add an entry to targets,
2255 // we also fill in the entry in dist (see add_entry!).
2256 None => unreachable!(),
2258 // We "propagate" the fees one hop backward (topologically) here,
2259 // so that fees paid for a HTLC forwarding on the current channel are
2260 // associated with the previous channel (where they will be subtracted).
2261 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2262 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2264 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2265 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2267 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2268 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2270 let mut payment_path = PaymentPath {hops: ordered_hops};
2272 // We could have possibly constructed a slightly inconsistent path: since we reduce
2273 // value being transferred along the way, we could have violated htlc_minimum_msat
2274 // on some channels we already passed (assuming dest->source direction). Here, we
2275 // recompute the fees again, so that if that's the case, we match the currently
2276 // underpaid htlc_minimum_msat with fees.
2277 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2278 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
2279 payment_path.update_value_and_recompute_fees(value_contribution_msat);
2281 // Since a path allows to transfer as much value as
2282 // the smallest channel it has ("bottleneck"), we should recompute
2283 // the fees so sender HTLC don't overpay fees when traversing
2284 // larger channels than the bottleneck. This may happen because
2285 // when we were selecting those channels we were not aware how much value
2286 // this path will transfer, and the relative fee for them
2287 // might have been computed considering a larger value.
2288 // Remember that we used these channels so that we don't rely
2289 // on the same liquidity in future paths.
2290 let mut prevented_redundant_path_selection = false;
2291 let prev_hop_iter = core::iter::once(&our_node_id)
2292 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
2293 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
2294 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2295 let used_liquidity_msat = used_liquidities
2296 .entry(hop.candidate.id(*prev_hop < hop.node_id))
2297 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2298 .or_insert(spent_on_hop_msat);
2299 let hop_capacity = hop.candidate.effective_capacity();
2300 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2301 if *used_liquidity_msat == hop_max_msat {
2302 // If this path used all of this channel's available liquidity, we know
2303 // this path will not be selected again in the next loop iteration.
2304 prevented_redundant_path_selection = true;
2306 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2308 if !prevented_redundant_path_selection {
2309 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2310 // we'll probably end up picking the same path again on the next iteration.
2311 // Decrease the available liquidity of a hop in the middle of the path.
2312 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2313 let exhausted = u64::max_value();
2314 log_trace!(logger, "Disabling route candidate {} for future path building iterations to
2315 avoid duplicates.", LoggedCandidateHop(victim_candidate));
2316 *used_liquidities.entry(victim_candidate.id(false)).or_default() = exhausted;
2317 *used_liquidities.entry(victim_candidate.id(true)).or_default() = exhausted;
2320 // Track the total amount all our collected paths allow to send so that we know
2321 // when to stop looking for more paths
2322 already_collected_value_msat += value_contribution_msat;
2324 payment_paths.push(payment_path);
2325 found_new_path = true;
2326 break 'path_construction;
2329 // If we found a path back to the payee, we shouldn't try to process it again. This is
2330 // the equivalent of the `elem.was_processed` check in
2331 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2332 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2334 // Otherwise, since the current target node is not us,
2335 // keep "unrolling" the payment graph from payee to payer by
2336 // finding a way to reach the current target from the payer side.
2337 match network_nodes.get(&node_id) {
2340 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2341 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2342 total_cltv_delta, path_length_to_node);
2348 if !found_new_path && channel_saturation_pow_half != 0 {
2349 channel_saturation_pow_half = 0;
2350 continue 'paths_collection;
2352 // If we don't support MPP, no use trying to gather more value ever.
2353 break 'paths_collection;
2357 // Stop either when the recommended value is reached or if no new path was found in this
2359 // In the latter case, making another path finding attempt won't help,
2360 // because we deterministically terminated the search due to low liquidity.
2361 if !found_new_path && channel_saturation_pow_half != 0 {
2362 channel_saturation_pow_half = 0;
2363 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2364 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2365 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2366 break 'paths_collection;
2367 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2368 // Further, if this was our first walk of the graph, and we weren't limited by an
2369 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2370 // limited by an htlc_minimum_msat value, find another path with a higher value,
2371 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2372 // still keeping a lower total fee than this path.
2373 if !hit_minimum_limit {
2374 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2375 break 'paths_collection;
2377 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
2378 path_value_msat = recommended_value_msat;
2382 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2383 num_ignored_cltv_delta_limit + num_ignored_previously_failed;
2384 if num_ignored_total > 0 {
2385 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);
2389 if payment_paths.len() == 0 {
2390 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2393 if already_collected_value_msat < final_value_msat {
2394 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2398 let mut selected_route = payment_paths;
2400 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2401 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2403 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2404 // the value they contribute towards the payment amount.
2405 // We sort in descending order as we will remove from the front in `retain`, next.
2406 selected_route.sort_unstable_by(|a, b|
2407 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2408 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2411 // We should make sure that at least 1 path left.
2412 let mut paths_left = selected_route.len();
2413 selected_route.retain(|path| {
2414 if paths_left == 1 {
2417 let path_value_msat = path.get_value_msat();
2418 if path_value_msat <= overpaid_value_msat {
2419 overpaid_value_msat -= path_value_msat;
2425 debug_assert!(selected_route.len() > 0);
2427 if overpaid_value_msat != 0 {
2429 // Now, subtract the remaining overpaid value from the most-expensive path.
2430 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2431 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2432 selected_route.sort_unstable_by(|a, b| {
2433 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2434 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2435 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2437 let expensive_payment_path = selected_route.first_mut().unwrap();
2439 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2440 // can't go negative.
2441 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2442 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2446 // Sort by the path itself and combine redundant paths.
2447 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2448 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2450 selected_route.sort_unstable_by_key(|path| {
2451 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2452 debug_assert!(path.hops.len() <= key.len());
2453 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id(true)).zip(key.iter_mut()) {
2458 for idx in 0..(selected_route.len() - 1) {
2459 if idx + 1 >= selected_route.len() { break; }
2460 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id)),
2461 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id))) {
2462 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2463 selected_route[idx].update_value_and_recompute_fees(new_value);
2464 selected_route.remove(idx + 1);
2468 let mut paths = Vec::new();
2469 for payment_path in selected_route {
2470 let mut hops = Vec::with_capacity(payment_path.hops.len());
2471 for (hop, node_features) in payment_path.hops.iter()
2472 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2474 hops.push(RouteHop {
2475 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)})?,
2476 node_features: node_features.clone(),
2477 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2478 channel_features: hop.candidate.features(),
2479 fee_msat: hop.fee_msat,
2480 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2483 let mut final_cltv_delta = final_cltv_expiry_delta;
2484 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2485 if let Some(blinded_path) = h.candidate.blinded_path() {
2486 final_cltv_delta = h.candidate.cltv_expiry_delta();
2488 hops: blinded_path.blinded_hops.clone(),
2489 blinding_point: blinded_path.blinding_point,
2490 excess_final_cltv_expiry_delta: 0,
2491 final_value_msat: h.fee_msat,
2495 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2496 // applicable for the previous hop.
2497 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2498 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2501 paths.push(Path { hops, blinded_tail });
2503 // Make sure we would never create a route with more paths than we allow.
2504 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2506 if let Some(node_features) = payment_params.payee.node_features() {
2507 for path in paths.iter_mut() {
2508 path.hops.last_mut().unwrap().node_features = node_features.clone();
2512 let route = Route { paths, route_params: Some(route_params.clone()) };
2513 log_info!(logger, "Got route: {}", log_route!(route));
2517 // When an adversarial intermediary node observes a payment, it may be able to infer its
2518 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2519 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2520 // payment path by adding a randomized 'shadow route' offset to the final hop.
2521 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2522 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2524 let network_channels = network_graph.channels();
2525 let network_nodes = network_graph.nodes();
2527 for path in route.paths.iter_mut() {
2528 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2530 // Remember the last three nodes of the random walk and avoid looping back on them.
2531 // Init with the last three nodes from the actual path, if possible.
2532 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2533 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2534 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2536 // Choose the last publicly known node as the starting point for the random walk.
2537 let mut cur_hop: Option<NodeId> = None;
2538 let mut path_nonce = [0u8; 12];
2539 if let Some(starting_hop) = path.hops.iter().rev()
2540 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2541 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2542 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2545 // Init PRNG with the path-dependant nonce, which is static for private paths.
2546 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2547 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2549 // Pick a random path length in [1 .. 3]
2550 prng.process_in_place(&mut random_path_bytes);
2551 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2553 for random_hop in 0..random_walk_length {
2554 // If we don't find a suitable offset in the public network graph, we default to
2555 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2556 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2558 if let Some(cur_node_id) = cur_hop {
2559 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2560 // Randomly choose the next unvisited hop.
2561 prng.process_in_place(&mut random_path_bytes);
2562 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2563 .checked_rem(cur_node.channels.len())
2564 .and_then(|index| cur_node.channels.get(index))
2565 .and_then(|id| network_channels.get(id)) {
2566 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2567 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2568 nodes_to_avoid[random_hop] = *next_id;
2569 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2570 cur_hop = Some(*next_id);
2577 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2578 .checked_add(random_hop_offset)
2579 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2582 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2583 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2584 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2586 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2587 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2588 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2589 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2590 max_path_offset = cmp::max(
2591 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2592 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2593 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2595 // Add 'shadow' CLTV offset to the final hop
2596 if let Some(tail) = path.blinded_tail.as_mut() {
2597 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2598 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2600 if let Some(last_hop) = path.hops.last_mut() {
2601 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2602 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2607 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2608 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2610 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2611 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2612 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2613 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2614 ) -> Result<Route, LightningError>
2615 where L::Target: Logger, GL::Target: Logger {
2616 let graph_lock = network_graph.read_only();
2617 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
2618 &graph_lock, logger, random_seed_bytes)?;
2619 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2623 fn build_route_from_hops_internal<L: Deref>(
2624 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2625 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
2626 ) -> Result<Route, LightningError> where L::Target: Logger {
2629 our_node_id: NodeId,
2630 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2633 impl ScoreLookUp for HopScorer {
2634 type ScoreParams = ();
2635 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2636 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2638 let mut cur_id = self.our_node_id;
2639 for i in 0..self.hop_ids.len() {
2640 if let Some(next_id) = self.hop_ids[i] {
2641 if cur_id == *source && next_id == *target {
2653 impl<'a> Writeable for HopScorer {
2655 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2660 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2661 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2664 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2665 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2666 for i in 0..hops.len() {
2667 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2670 let scorer = HopScorer { our_node_id, hop_ids };
2672 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &(), random_seed_bytes)
2677 use crate::blinded_path::{BlindedHop, BlindedPath};
2678 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2679 use crate::routing::utxo::UtxoResult;
2680 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2681 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2682 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters};
2683 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2684 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2685 use crate::chain::transaction::OutPoint;
2686 use crate::sign::EntropySource;
2687 use crate::ln::ChannelId;
2688 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2689 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2690 use crate::ln::channelmanager;
2691 use crate::offers::invoice::BlindedPayInfo;
2692 use crate::util::config::UserConfig;
2693 use crate::util::test_utils as ln_test_utils;
2694 use crate::util::chacha20::ChaCha20;
2695 use crate::util::ser::{Readable, Writeable};
2697 use crate::util::ser::Writer;
2699 use bitcoin::hashes::Hash;
2700 use bitcoin::network::constants::Network;
2701 use bitcoin::blockdata::constants::genesis_block;
2702 use bitcoin::blockdata::script::Builder;
2703 use bitcoin::blockdata::opcodes;
2704 use bitcoin::blockdata::transaction::TxOut;
2708 use bitcoin::secp256k1::{PublicKey,SecretKey};
2709 use bitcoin::secp256k1::Secp256k1;
2711 use crate::io::Cursor;
2712 use crate::prelude::*;
2713 use crate::sync::Arc;
2715 use core::convert::TryInto;
2717 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2718 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2719 channelmanager::ChannelDetails {
2720 channel_id: ChannelId::new_zero(),
2721 counterparty: channelmanager::ChannelCounterparty {
2724 unspendable_punishment_reserve: 0,
2725 forwarding_info: None,
2726 outbound_htlc_minimum_msat: None,
2727 outbound_htlc_maximum_msat: None,
2729 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2732 outbound_scid_alias: None,
2733 inbound_scid_alias: None,
2734 channel_value_satoshis: 0,
2736 outbound_capacity_msat,
2737 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2738 next_outbound_htlc_minimum_msat: 0,
2739 inbound_capacity_msat: 42,
2740 unspendable_punishment_reserve: None,
2741 confirmations_required: None,
2742 confirmations: None,
2743 force_close_spend_delay: None,
2744 is_outbound: true, is_channel_ready: true,
2745 is_usable: true, is_public: true,
2746 inbound_htlc_minimum_msat: None,
2747 inbound_htlc_maximum_msat: None,
2749 feerate_sat_per_1000_weight: None,
2750 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
2755 fn simple_route_test() {
2756 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2757 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2758 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2759 let scorer = ln_test_utils::TestScorer::new();
2760 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2761 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2763 // Simple route to 2 via 1
2765 let route_params = RouteParameters::from_payment_params_and_value(
2766 payment_params.clone(), 0);
2767 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2768 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer, &(),
2769 &random_seed_bytes) {
2770 assert_eq!(err, "Cannot send a payment of 0 msat");
2771 } else { panic!(); }
2773 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
2774 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2775 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2776 assert_eq!(route.paths[0].hops.len(), 2);
2778 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2779 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2780 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2781 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2782 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2783 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2785 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2786 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2787 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2788 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2789 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2790 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2794 fn invalid_first_hop_test() {
2795 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2796 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2797 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2798 let scorer = ln_test_utils::TestScorer::new();
2799 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2800 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2802 // Simple route to 2 via 1
2804 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2806 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
2807 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2808 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
2809 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2810 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2811 } else { panic!(); }
2813 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2814 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2815 assert_eq!(route.paths[0].hops.len(), 2);
2819 fn htlc_minimum_test() {
2820 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2821 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2822 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2823 let scorer = ln_test_utils::TestScorer::new();
2824 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2825 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2827 // Simple route to 2 via 1
2829 // Disable other paths
2830 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2831 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2832 short_channel_id: 12,
2834 flags: 2, // to disable
2835 cltv_expiry_delta: 0,
2836 htlc_minimum_msat: 0,
2837 htlc_maximum_msat: MAX_VALUE_MSAT,
2839 fee_proportional_millionths: 0,
2840 excess_data: Vec::new()
2842 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2843 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2844 short_channel_id: 3,
2846 flags: 2, // to disable
2847 cltv_expiry_delta: 0,
2848 htlc_minimum_msat: 0,
2849 htlc_maximum_msat: MAX_VALUE_MSAT,
2851 fee_proportional_millionths: 0,
2852 excess_data: Vec::new()
2854 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2855 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2856 short_channel_id: 13,
2858 flags: 2, // to disable
2859 cltv_expiry_delta: 0,
2860 htlc_minimum_msat: 0,
2861 htlc_maximum_msat: MAX_VALUE_MSAT,
2863 fee_proportional_millionths: 0,
2864 excess_data: Vec::new()
2866 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2867 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2868 short_channel_id: 6,
2870 flags: 2, // to disable
2871 cltv_expiry_delta: 0,
2872 htlc_minimum_msat: 0,
2873 htlc_maximum_msat: MAX_VALUE_MSAT,
2875 fee_proportional_millionths: 0,
2876 excess_data: Vec::new()
2878 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2879 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2880 short_channel_id: 7,
2882 flags: 2, // to disable
2883 cltv_expiry_delta: 0,
2884 htlc_minimum_msat: 0,
2885 htlc_maximum_msat: MAX_VALUE_MSAT,
2887 fee_proportional_millionths: 0,
2888 excess_data: Vec::new()
2891 // Check against amount_to_transfer_over_msat.
2892 // Set minimal HTLC of 200_000_000 msat.
2893 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2894 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2895 short_channel_id: 2,
2898 cltv_expiry_delta: 0,
2899 htlc_minimum_msat: 200_000_000,
2900 htlc_maximum_msat: MAX_VALUE_MSAT,
2902 fee_proportional_millionths: 0,
2903 excess_data: Vec::new()
2906 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2908 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2909 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2910 short_channel_id: 4,
2913 cltv_expiry_delta: 0,
2914 htlc_minimum_msat: 0,
2915 htlc_maximum_msat: 199_999_999,
2917 fee_proportional_millionths: 0,
2918 excess_data: Vec::new()
2921 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2922 let route_params = RouteParameters::from_payment_params_and_value(
2923 payment_params, 199_999_999);
2924 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2925 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer, &(),
2926 &random_seed_bytes) {
2927 assert_eq!(err, "Failed to find a path to the given destination");
2928 } else { panic!(); }
2930 // Lift the restriction on the first hop.
2931 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2932 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2933 short_channel_id: 2,
2936 cltv_expiry_delta: 0,
2937 htlc_minimum_msat: 0,
2938 htlc_maximum_msat: MAX_VALUE_MSAT,
2940 fee_proportional_millionths: 0,
2941 excess_data: Vec::new()
2944 // A payment above the minimum should pass
2945 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2946 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2947 assert_eq!(route.paths[0].hops.len(), 2);
2951 fn htlc_minimum_overpay_test() {
2952 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2953 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2954 let config = UserConfig::default();
2955 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
2956 let scorer = ln_test_utils::TestScorer::new();
2957 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2958 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2960 // A route to node#2 via two paths.
2961 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2962 // Thus, they can't send 60 without overpaying.
2963 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2964 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2965 short_channel_id: 2,
2968 cltv_expiry_delta: 0,
2969 htlc_minimum_msat: 35_000,
2970 htlc_maximum_msat: 40_000,
2972 fee_proportional_millionths: 0,
2973 excess_data: Vec::new()
2975 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2976 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2977 short_channel_id: 12,
2980 cltv_expiry_delta: 0,
2981 htlc_minimum_msat: 35_000,
2982 htlc_maximum_msat: 40_000,
2984 fee_proportional_millionths: 0,
2985 excess_data: Vec::new()
2989 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2990 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2991 short_channel_id: 13,
2994 cltv_expiry_delta: 0,
2995 htlc_minimum_msat: 0,
2996 htlc_maximum_msat: MAX_VALUE_MSAT,
2998 fee_proportional_millionths: 0,
2999 excess_data: Vec::new()
3001 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3002 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3003 short_channel_id: 4,
3006 cltv_expiry_delta: 0,
3007 htlc_minimum_msat: 0,
3008 htlc_maximum_msat: MAX_VALUE_MSAT,
3010 fee_proportional_millionths: 0,
3011 excess_data: Vec::new()
3014 // Disable other paths
3015 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3016 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3017 short_channel_id: 1,
3019 flags: 2, // to disable
3020 cltv_expiry_delta: 0,
3021 htlc_minimum_msat: 0,
3022 htlc_maximum_msat: MAX_VALUE_MSAT,
3024 fee_proportional_millionths: 0,
3025 excess_data: Vec::new()
3028 let route_params = RouteParameters::from_payment_params_and_value(
3029 payment_params.clone(), 60_000);
3030 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3031 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3032 // Overpay fees to hit htlc_minimum_msat.
3033 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3034 // TODO: this could be better balanced to overpay 10k and not 15k.
3035 assert_eq!(overpaid_fees, 15_000);
3037 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3038 // while taking even more fee to match htlc_minimum_msat.
3039 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3040 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3041 short_channel_id: 12,
3044 cltv_expiry_delta: 0,
3045 htlc_minimum_msat: 65_000,
3046 htlc_maximum_msat: 80_000,
3048 fee_proportional_millionths: 0,
3049 excess_data: Vec::new()
3051 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3052 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3053 short_channel_id: 2,
3056 cltv_expiry_delta: 0,
3057 htlc_minimum_msat: 0,
3058 htlc_maximum_msat: MAX_VALUE_MSAT,
3060 fee_proportional_millionths: 0,
3061 excess_data: Vec::new()
3063 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3064 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3065 short_channel_id: 4,
3068 cltv_expiry_delta: 0,
3069 htlc_minimum_msat: 0,
3070 htlc_maximum_msat: MAX_VALUE_MSAT,
3072 fee_proportional_millionths: 100_000,
3073 excess_data: Vec::new()
3076 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3077 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3078 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3079 assert_eq!(route.paths.len(), 1);
3080 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3081 let fees = route.paths[0].hops[0].fee_msat;
3082 assert_eq!(fees, 5_000);
3084 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3085 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3086 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3087 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3088 // the other channel.
3089 assert_eq!(route.paths.len(), 1);
3090 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3091 let fees = route.paths[0].hops[0].fee_msat;
3092 assert_eq!(fees, 5_000);
3096 fn disable_channels_test() {
3097 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3098 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3099 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3100 let scorer = ln_test_utils::TestScorer::new();
3101 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3102 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3104 // // Disable channels 4 and 12 by flags=2
3105 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3106 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3107 short_channel_id: 4,
3109 flags: 2, // to disable
3110 cltv_expiry_delta: 0,
3111 htlc_minimum_msat: 0,
3112 htlc_maximum_msat: MAX_VALUE_MSAT,
3114 fee_proportional_millionths: 0,
3115 excess_data: Vec::new()
3117 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3118 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3119 short_channel_id: 12,
3121 flags: 2, // to disable
3122 cltv_expiry_delta: 0,
3123 htlc_minimum_msat: 0,
3124 htlc_maximum_msat: MAX_VALUE_MSAT,
3126 fee_proportional_millionths: 0,
3127 excess_data: Vec::new()
3130 // If all the channels require some features we don't understand, route should fail
3131 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3132 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3133 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer, &(),
3134 &random_seed_bytes) {
3135 assert_eq!(err, "Failed to find a path to the given destination");
3136 } else { panic!(); }
3138 // If we specify a channel to node7, that overrides our local channel view and that gets used
3139 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3140 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3141 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3142 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
3143 &random_seed_bytes).unwrap();
3144 assert_eq!(route.paths[0].hops.len(), 2);
3146 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3147 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3148 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3149 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3150 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3151 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3153 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3154 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3155 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3156 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3157 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3158 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3162 fn disable_node_test() {
3163 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3164 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3165 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3166 let scorer = ln_test_utils::TestScorer::new();
3167 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3168 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3170 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3171 let mut unknown_features = NodeFeatures::empty();
3172 unknown_features.set_unknown_feature_required();
3173 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3174 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3175 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3177 // If all nodes require some features we don't understand, route should fail
3178 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3179 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3180 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer, &(),
3181 &random_seed_bytes) {
3182 assert_eq!(err, "Failed to find a path to the given destination");
3183 } else { panic!(); }
3185 // If we specify a channel to node7, that overrides our local channel view and that gets used
3186 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3187 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3188 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3189 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
3190 &random_seed_bytes).unwrap();
3191 assert_eq!(route.paths[0].hops.len(), 2);
3193 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3194 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3195 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3196 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3197 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3198 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3200 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3201 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3202 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3203 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3204 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3205 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3207 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3208 // naively) assume that the user checked the feature bits on the invoice, which override
3209 // the node_announcement.
3213 fn our_chans_test() {
3214 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3215 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3216 let scorer = ln_test_utils::TestScorer::new();
3217 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3218 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3220 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3221 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3222 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3223 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3224 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3225 assert_eq!(route.paths[0].hops.len(), 3);
3227 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3228 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3229 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3230 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3231 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3232 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3234 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3235 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3236 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3237 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3238 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3239 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3241 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3242 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3243 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3244 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3245 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3246 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3248 // If we specify a channel to node7, that overrides our local channel view and that gets used
3249 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3250 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3251 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3252 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3253 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3254 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
3255 &random_seed_bytes).unwrap();
3256 assert_eq!(route.paths[0].hops.len(), 2);
3258 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3259 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3260 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3261 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3262 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3263 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3265 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3266 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3267 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3268 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3269 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3270 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3273 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3274 let zero_fees = RoutingFees {
3276 proportional_millionths: 0,
3278 vec![RouteHint(vec![RouteHintHop {
3279 src_node_id: nodes[3],
3280 short_channel_id: 8,
3282 cltv_expiry_delta: (8 << 4) | 1,
3283 htlc_minimum_msat: None,
3284 htlc_maximum_msat: None,
3286 ]), RouteHint(vec![RouteHintHop {
3287 src_node_id: nodes[4],
3288 short_channel_id: 9,
3291 proportional_millionths: 0,
3293 cltv_expiry_delta: (9 << 4) | 1,
3294 htlc_minimum_msat: None,
3295 htlc_maximum_msat: None,
3296 }]), RouteHint(vec![RouteHintHop {
3297 src_node_id: nodes[5],
3298 short_channel_id: 10,
3300 cltv_expiry_delta: (10 << 4) | 1,
3301 htlc_minimum_msat: None,
3302 htlc_maximum_msat: None,
3306 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3307 let zero_fees = RoutingFees {
3309 proportional_millionths: 0,
3311 vec![RouteHint(vec![RouteHintHop {
3312 src_node_id: nodes[2],
3313 short_channel_id: 5,
3316 proportional_millionths: 0,
3318 cltv_expiry_delta: (5 << 4) | 1,
3319 htlc_minimum_msat: None,
3320 htlc_maximum_msat: None,
3322 src_node_id: nodes[3],
3323 short_channel_id: 8,
3325 cltv_expiry_delta: (8 << 4) | 1,
3326 htlc_minimum_msat: None,
3327 htlc_maximum_msat: None,
3329 ]), RouteHint(vec![RouteHintHop {
3330 src_node_id: nodes[4],
3331 short_channel_id: 9,
3334 proportional_millionths: 0,
3336 cltv_expiry_delta: (9 << 4) | 1,
3337 htlc_minimum_msat: None,
3338 htlc_maximum_msat: None,
3339 }]), RouteHint(vec![RouteHintHop {
3340 src_node_id: nodes[5],
3341 short_channel_id: 10,
3343 cltv_expiry_delta: (10 << 4) | 1,
3344 htlc_minimum_msat: None,
3345 htlc_maximum_msat: None,
3350 fn partial_route_hint_test() {
3351 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3352 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3353 let scorer = ln_test_utils::TestScorer::new();
3354 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3355 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3357 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3358 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3359 // RouteHint may be partially used by the algo to build the best path.
3361 // First check that last hop can't have its source as the payee.
3362 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3363 src_node_id: nodes[6],
3364 short_channel_id: 8,
3367 proportional_millionths: 0,
3369 cltv_expiry_delta: (8 << 4) | 1,
3370 htlc_minimum_msat: None,
3371 htlc_maximum_msat: None,
3374 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3375 invalid_last_hops.push(invalid_last_hop);
3377 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3378 .with_route_hints(invalid_last_hops).unwrap();
3379 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3380 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3381 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer, &(),
3382 &random_seed_bytes) {
3383 assert_eq!(err, "Route hint cannot have the payee as the source.");
3384 } else { panic!(); }
3387 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3388 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3389 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3390 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3391 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3392 assert_eq!(route.paths[0].hops.len(), 5);
3394 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3395 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3396 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3397 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3398 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3399 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3401 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3402 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3403 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3404 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3405 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3406 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3408 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3409 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3410 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3411 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3412 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3413 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3415 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3416 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3417 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3418 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3419 // If we have a peer in the node map, we'll use their features here since we don't have
3420 // a way of figuring out their features from the invoice:
3421 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3422 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3424 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3425 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3426 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3427 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3428 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3429 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3432 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3433 let zero_fees = RoutingFees {
3435 proportional_millionths: 0,
3437 vec![RouteHint(vec![RouteHintHop {
3438 src_node_id: nodes[3],
3439 short_channel_id: 8,
3441 cltv_expiry_delta: (8 << 4) | 1,
3442 htlc_minimum_msat: None,
3443 htlc_maximum_msat: None,
3444 }]), RouteHint(vec![
3446 ]), RouteHint(vec![RouteHintHop {
3447 src_node_id: nodes[5],
3448 short_channel_id: 10,
3450 cltv_expiry_delta: (10 << 4) | 1,
3451 htlc_minimum_msat: None,
3452 htlc_maximum_msat: None,
3457 fn ignores_empty_last_hops_test() {
3458 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3459 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3460 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3461 let scorer = ln_test_utils::TestScorer::new();
3462 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3463 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3465 // Test handling of an empty RouteHint passed in Invoice.
3466 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3467 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3468 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3469 assert_eq!(route.paths[0].hops.len(), 5);
3471 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3472 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3473 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3474 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3475 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3476 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3478 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3479 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3480 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3481 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3482 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3483 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3485 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3486 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3487 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3488 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3489 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3490 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3492 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3493 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3494 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3495 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3496 // If we have a peer in the node map, we'll use their features here since we don't have
3497 // a way of figuring out their features from the invoice:
3498 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3499 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3501 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3502 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3503 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3504 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3505 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3506 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3509 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3511 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3512 let zero_fees = RoutingFees {
3514 proportional_millionths: 0,
3516 vec![RouteHint(vec![RouteHintHop {
3517 src_node_id: hint_hops[0],
3518 short_channel_id: 0xff00,
3521 proportional_millionths: 0,
3523 cltv_expiry_delta: (5 << 4) | 1,
3524 htlc_minimum_msat: None,
3525 htlc_maximum_msat: None,
3527 src_node_id: hint_hops[1],
3528 short_channel_id: 0xff01,
3530 cltv_expiry_delta: (8 << 4) | 1,
3531 htlc_minimum_msat: None,
3532 htlc_maximum_msat: None,
3537 fn multi_hint_last_hops_test() {
3538 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3539 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3540 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3541 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3542 let scorer = ln_test_utils::TestScorer::new();
3543 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3544 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3545 // Test through channels 2, 3, 0xff00, 0xff01.
3546 // Test shows that multiple hop hints are considered.
3548 // Disabling channels 6 & 7 by flags=2
3549 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3550 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3551 short_channel_id: 6,
3553 flags: 2, // to disable
3554 cltv_expiry_delta: 0,
3555 htlc_minimum_msat: 0,
3556 htlc_maximum_msat: MAX_VALUE_MSAT,
3558 fee_proportional_millionths: 0,
3559 excess_data: Vec::new()
3561 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3562 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3563 short_channel_id: 7,
3565 flags: 2, // to disable
3566 cltv_expiry_delta: 0,
3567 htlc_minimum_msat: 0,
3568 htlc_maximum_msat: MAX_VALUE_MSAT,
3570 fee_proportional_millionths: 0,
3571 excess_data: Vec::new()
3574 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3575 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3576 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3577 assert_eq!(route.paths[0].hops.len(), 4);
3579 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3580 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3581 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3582 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3583 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3584 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3586 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3587 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3588 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3589 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3590 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3591 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3593 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3594 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3595 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3596 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3597 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3598 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3600 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3601 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3602 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3603 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3604 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3605 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3609 fn private_multi_hint_last_hops_test() {
3610 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3611 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3613 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3614 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3616 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3617 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3618 let scorer = ln_test_utils::TestScorer::new();
3619 // Test through channels 2, 3, 0xff00, 0xff01.
3620 // Test shows that multiple hop hints are considered.
3622 // Disabling channels 6 & 7 by flags=2
3623 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3624 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3625 short_channel_id: 6,
3627 flags: 2, // to disable
3628 cltv_expiry_delta: 0,
3629 htlc_minimum_msat: 0,
3630 htlc_maximum_msat: MAX_VALUE_MSAT,
3632 fee_proportional_millionths: 0,
3633 excess_data: Vec::new()
3635 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3636 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3637 short_channel_id: 7,
3639 flags: 2, // to disable
3640 cltv_expiry_delta: 0,
3641 htlc_minimum_msat: 0,
3642 htlc_maximum_msat: MAX_VALUE_MSAT,
3644 fee_proportional_millionths: 0,
3645 excess_data: Vec::new()
3648 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3649 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3650 Arc::clone(&logger), &scorer, &(), &[42u8; 32]).unwrap();
3651 assert_eq!(route.paths[0].hops.len(), 4);
3653 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3654 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3655 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3656 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3657 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3658 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3660 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3661 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3662 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3663 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3664 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3665 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3667 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3668 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3669 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3670 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3671 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3672 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3674 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3675 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3676 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3677 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3678 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3679 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3682 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3683 let zero_fees = RoutingFees {
3685 proportional_millionths: 0,
3687 vec![RouteHint(vec![RouteHintHop {
3688 src_node_id: nodes[4],
3689 short_channel_id: 11,
3691 cltv_expiry_delta: (11 << 4) | 1,
3692 htlc_minimum_msat: None,
3693 htlc_maximum_msat: None,
3695 src_node_id: nodes[3],
3696 short_channel_id: 8,
3698 cltv_expiry_delta: (8 << 4) | 1,
3699 htlc_minimum_msat: None,
3700 htlc_maximum_msat: None,
3701 }]), RouteHint(vec![RouteHintHop {
3702 src_node_id: nodes[4],
3703 short_channel_id: 9,
3706 proportional_millionths: 0,
3708 cltv_expiry_delta: (9 << 4) | 1,
3709 htlc_minimum_msat: None,
3710 htlc_maximum_msat: None,
3711 }]), RouteHint(vec![RouteHintHop {
3712 src_node_id: nodes[5],
3713 short_channel_id: 10,
3715 cltv_expiry_delta: (10 << 4) | 1,
3716 htlc_minimum_msat: None,
3717 htlc_maximum_msat: None,
3722 fn last_hops_with_public_channel_test() {
3723 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3724 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3725 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
3726 let scorer = ln_test_utils::TestScorer::new();
3727 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3728 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3729 // This test shows that public routes can be present in the invoice
3730 // which would be handled in the same manner.
3732 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3733 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3734 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3735 assert_eq!(route.paths[0].hops.len(), 5);
3737 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3738 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3739 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3740 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3741 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3742 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3744 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3745 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3746 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3747 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3748 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3749 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3751 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3752 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3753 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3754 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3755 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3756 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3758 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3759 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3760 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3761 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3762 // If we have a peer in the node map, we'll use their features here since we don't have
3763 // a way of figuring out their features from the invoice:
3764 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3765 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3767 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3768 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3769 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3770 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3771 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3772 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3776 fn our_chans_last_hop_connect_test() {
3777 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3778 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3779 let scorer = ln_test_utils::TestScorer::new();
3780 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3781 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3783 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3784 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3785 let mut last_hops = last_hops(&nodes);
3786 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3787 .with_route_hints(last_hops.clone()).unwrap();
3788 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3789 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3790 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
3791 &random_seed_bytes).unwrap();
3792 assert_eq!(route.paths[0].hops.len(), 2);
3794 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3795 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3796 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3797 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3798 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3799 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3801 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3802 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3803 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3804 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3805 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3806 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3808 last_hops[0].0[0].fees.base_msat = 1000;
3810 // Revert to via 6 as the fee on 8 goes up
3811 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3812 .with_route_hints(last_hops).unwrap();
3813 let route_params = RouteParameters::from_payment_params_and_value(
3814 payment_params.clone(), 100);
3815 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3816 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3817 assert_eq!(route.paths[0].hops.len(), 4);
3819 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3820 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3821 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
3822 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3823 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3824 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3826 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3827 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3828 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3829 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
3830 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3831 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3833 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
3834 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3835 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3836 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3837 // If we have a peer in the node map, we'll use their features here since we don't have
3838 // a way of figuring out their features from the invoice:
3839 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3840 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3842 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3843 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3844 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3845 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3846 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3847 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3849 // ...but still use 8 for larger payments as 6 has a variable feerate
3850 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
3851 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3852 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3853 assert_eq!(route.paths[0].hops.len(), 5);
3855 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3856 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3857 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3858 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3859 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3860 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3862 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3863 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3864 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3865 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3866 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3867 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3869 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3870 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3871 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3872 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3873 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3874 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3876 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3877 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3878 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
3879 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3880 // If we have a peer in the node map, we'll use their features here since we don't have
3881 // a way of figuring out their features from the invoice:
3882 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3883 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3885 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3886 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3887 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
3888 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3889 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3890 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3893 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> {
3894 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3895 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3896 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3898 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3899 let last_hops = RouteHint(vec![RouteHintHop {
3900 src_node_id: middle_node_id,
3901 short_channel_id: 8,
3904 proportional_millionths: last_hop_fee_prop,
3906 cltv_expiry_delta: (8 << 4) | 1,
3907 htlc_minimum_msat: None,
3908 htlc_maximum_msat: last_hop_htlc_max,
3910 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
3911 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3912 let scorer = ln_test_utils::TestScorer::new();
3913 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3914 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3915 let logger = ln_test_utils::TestLogger::new();
3916 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3917 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
3918 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
3919 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &(),
3920 &random_seed_bytes);
3925 fn unannounced_path_test() {
3926 // We should be able to send a payment to a destination without any help of a routing graph
3927 // if we have a channel with a common counterparty that appears in the first and last hop
3929 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3931 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3932 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3933 assert_eq!(route.paths[0].hops.len(), 2);
3935 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
3936 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3937 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
3938 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3939 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
3940 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3942 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
3943 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3944 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
3945 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3946 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3947 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3951 fn overflow_unannounced_path_test_liquidity_underflow() {
3952 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3953 // the last-hop had a fee which overflowed a u64, we'd panic.
3954 // This was due to us adding the first-hop from us unconditionally, causing us to think
3955 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3956 // In this test, we previously hit a subtraction underflow due to having less available
3957 // liquidity at the last hop than 0.
3958 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());
3962 fn overflow_unannounced_path_test_feerate_overflow() {
3963 // This tests for the same case as above, except instead of hitting a subtraction
3964 // underflow, we hit a case where the fee charged at a hop overflowed.
3965 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());
3969 fn available_amount_while_routing_test() {
3970 // Tests whether we choose the correct available channel amount while routing.
3972 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
3973 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3974 let scorer = ln_test_utils::TestScorer::new();
3975 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3976 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3977 let config = UserConfig::default();
3978 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3980 // We will use a simple single-path route from
3981 // our node to node2 via node0: channels {1, 3}.
3983 // First disable all other paths.
3984 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3985 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3986 short_channel_id: 2,
3989 cltv_expiry_delta: 0,
3990 htlc_minimum_msat: 0,
3991 htlc_maximum_msat: 100_000,
3993 fee_proportional_millionths: 0,
3994 excess_data: Vec::new()
3996 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3997 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3998 short_channel_id: 12,
4001 cltv_expiry_delta: 0,
4002 htlc_minimum_msat: 0,
4003 htlc_maximum_msat: 100_000,
4005 fee_proportional_millionths: 0,
4006 excess_data: Vec::new()
4009 // Make the first channel (#1) very permissive,
4010 // and we will be testing all limits on the second channel.
4011 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4012 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4013 short_channel_id: 1,
4016 cltv_expiry_delta: 0,
4017 htlc_minimum_msat: 0,
4018 htlc_maximum_msat: 1_000_000_000,
4020 fee_proportional_millionths: 0,
4021 excess_data: Vec::new()
4024 // First, let's see if routing works if we have absolutely no idea about the available amount.
4025 // In this case, it should be set to 250_000 sats.
4026 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4027 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4028 short_channel_id: 3,
4031 cltv_expiry_delta: 0,
4032 htlc_minimum_msat: 0,
4033 htlc_maximum_msat: 250_000_000,
4035 fee_proportional_millionths: 0,
4036 excess_data: Vec::new()
4040 // Attempt to route more than available results in a failure.
4041 let route_params = RouteParameters::from_payment_params_and_value(
4042 payment_params.clone(), 250_000_001);
4043 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4044 &our_id, &route_params, &network_graph.read_only(), None,
4045 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4046 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4047 } else { panic!(); }
4051 // Now, attempt to route an exact amount we have should be fine.
4052 let route_params = RouteParameters::from_payment_params_and_value(
4053 payment_params.clone(), 250_000_000);
4054 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4055 Arc::clone(&logger), &scorer, &(),&random_seed_bytes).unwrap();
4056 assert_eq!(route.paths.len(), 1);
4057 let path = route.paths.last().unwrap();
4058 assert_eq!(path.hops.len(), 2);
4059 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4060 assert_eq!(path.final_value_msat(), 250_000_000);
4063 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4064 // Disable channel #1 and use another first hop.
4065 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4066 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4067 short_channel_id: 1,
4070 cltv_expiry_delta: 0,
4071 htlc_minimum_msat: 0,
4072 htlc_maximum_msat: 1_000_000_000,
4074 fee_proportional_millionths: 0,
4075 excess_data: Vec::new()
4078 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4079 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4082 // Attempt to route more than available results in a failure.
4083 let route_params = RouteParameters::from_payment_params_and_value(
4084 payment_params.clone(), 200_000_001);
4085 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4086 &our_id, &route_params, &network_graph.read_only(),
4087 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4088 &(), &random_seed_bytes) {
4089 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4090 } else { panic!(); }
4094 // Now, attempt to route an exact amount we have should be fine.
4095 let route_params = RouteParameters::from_payment_params_and_value(
4096 payment_params.clone(), 200_000_000);
4097 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4098 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
4099 &random_seed_bytes).unwrap();
4100 assert_eq!(route.paths.len(), 1);
4101 let path = route.paths.last().unwrap();
4102 assert_eq!(path.hops.len(), 2);
4103 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4104 assert_eq!(path.final_value_msat(), 200_000_000);
4107 // Enable channel #1 back.
4108 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4109 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4110 short_channel_id: 1,
4113 cltv_expiry_delta: 0,
4114 htlc_minimum_msat: 0,
4115 htlc_maximum_msat: 1_000_000_000,
4117 fee_proportional_millionths: 0,
4118 excess_data: Vec::new()
4122 // Now let's see if routing works if we know only htlc_maximum_msat.
4123 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4124 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4125 short_channel_id: 3,
4128 cltv_expiry_delta: 0,
4129 htlc_minimum_msat: 0,
4130 htlc_maximum_msat: 15_000,
4132 fee_proportional_millionths: 0,
4133 excess_data: Vec::new()
4137 // Attempt to route more than available results in a failure.
4138 let route_params = RouteParameters::from_payment_params_and_value(
4139 payment_params.clone(), 15_001);
4140 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4141 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4142 &scorer, &(), &random_seed_bytes) {
4143 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4144 } else { panic!(); }
4148 // Now, attempt to route an exact amount we have should be fine.
4149 let route_params = RouteParameters::from_payment_params_and_value(
4150 payment_params.clone(), 15_000);
4151 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4152 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4153 assert_eq!(route.paths.len(), 1);
4154 let path = route.paths.last().unwrap();
4155 assert_eq!(path.hops.len(), 2);
4156 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4157 assert_eq!(path.final_value_msat(), 15_000);
4160 // Now let's see if routing works if we know only capacity from the UTXO.
4162 // We can't change UTXO capacity on the fly, so we'll disable
4163 // the existing channel and add another one with the capacity we need.
4164 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4165 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4166 short_channel_id: 3,
4169 cltv_expiry_delta: 0,
4170 htlc_minimum_msat: 0,
4171 htlc_maximum_msat: MAX_VALUE_MSAT,
4173 fee_proportional_millionths: 0,
4174 excess_data: Vec::new()
4177 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4178 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4179 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4180 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4181 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4183 *chain_monitor.utxo_ret.lock().unwrap() =
4184 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4185 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4187 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4188 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4189 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4190 short_channel_id: 333,
4193 cltv_expiry_delta: (3 << 4) | 1,
4194 htlc_minimum_msat: 0,
4195 htlc_maximum_msat: 15_000,
4197 fee_proportional_millionths: 0,
4198 excess_data: Vec::new()
4200 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4201 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4202 short_channel_id: 333,
4205 cltv_expiry_delta: (3 << 4) | 2,
4206 htlc_minimum_msat: 0,
4207 htlc_maximum_msat: 15_000,
4209 fee_proportional_millionths: 0,
4210 excess_data: Vec::new()
4214 // Attempt to route more than available results in a failure.
4215 let route_params = RouteParameters::from_payment_params_and_value(
4216 payment_params.clone(), 15_001);
4217 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4218 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4219 &scorer, &(), &random_seed_bytes) {
4220 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4221 } else { panic!(); }
4225 // Now, attempt to route an exact amount we have should be fine.
4226 let route_params = RouteParameters::from_payment_params_and_value(
4227 payment_params.clone(), 15_000);
4228 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4229 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4230 assert_eq!(route.paths.len(), 1);
4231 let path = route.paths.last().unwrap();
4232 assert_eq!(path.hops.len(), 2);
4233 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4234 assert_eq!(path.final_value_msat(), 15_000);
4237 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4238 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4239 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4240 short_channel_id: 333,
4243 cltv_expiry_delta: 0,
4244 htlc_minimum_msat: 0,
4245 htlc_maximum_msat: 10_000,
4247 fee_proportional_millionths: 0,
4248 excess_data: Vec::new()
4252 // Attempt to route more than available results in a failure.
4253 let route_params = RouteParameters::from_payment_params_and_value(
4254 payment_params.clone(), 10_001);
4255 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4256 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4257 &scorer, &(), &random_seed_bytes) {
4258 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4259 } else { panic!(); }
4263 // Now, attempt to route an exact amount we have should be fine.
4264 let route_params = RouteParameters::from_payment_params_and_value(
4265 payment_params.clone(), 10_000);
4266 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4267 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4268 assert_eq!(route.paths.len(), 1);
4269 let path = route.paths.last().unwrap();
4270 assert_eq!(path.hops.len(), 2);
4271 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4272 assert_eq!(path.final_value_msat(), 10_000);
4277 fn available_liquidity_last_hop_test() {
4278 // Check that available liquidity properly limits the path even when only
4279 // one of the latter hops is limited.
4280 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4281 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4282 let scorer = ln_test_utils::TestScorer::new();
4283 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4284 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4285 let config = UserConfig::default();
4286 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4288 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4289 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4290 // Total capacity: 50 sats.
4292 // Disable other potential paths.
4293 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4294 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4295 short_channel_id: 2,
4298 cltv_expiry_delta: 0,
4299 htlc_minimum_msat: 0,
4300 htlc_maximum_msat: 100_000,
4302 fee_proportional_millionths: 0,
4303 excess_data: Vec::new()
4305 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4306 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4307 short_channel_id: 7,
4310 cltv_expiry_delta: 0,
4311 htlc_minimum_msat: 0,
4312 htlc_maximum_msat: 100_000,
4314 fee_proportional_millionths: 0,
4315 excess_data: Vec::new()
4320 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4321 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4322 short_channel_id: 12,
4325 cltv_expiry_delta: 0,
4326 htlc_minimum_msat: 0,
4327 htlc_maximum_msat: 100_000,
4329 fee_proportional_millionths: 0,
4330 excess_data: Vec::new()
4332 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4333 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4334 short_channel_id: 13,
4337 cltv_expiry_delta: 0,
4338 htlc_minimum_msat: 0,
4339 htlc_maximum_msat: 100_000,
4341 fee_proportional_millionths: 0,
4342 excess_data: Vec::new()
4345 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4346 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4347 short_channel_id: 6,
4350 cltv_expiry_delta: 0,
4351 htlc_minimum_msat: 0,
4352 htlc_maximum_msat: 50_000,
4354 fee_proportional_millionths: 0,
4355 excess_data: Vec::new()
4357 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4358 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4359 short_channel_id: 11,
4362 cltv_expiry_delta: 0,
4363 htlc_minimum_msat: 0,
4364 htlc_maximum_msat: 100_000,
4366 fee_proportional_millionths: 0,
4367 excess_data: Vec::new()
4370 // Attempt to route more than available results in a failure.
4371 let route_params = RouteParameters::from_payment_params_and_value(
4372 payment_params.clone(), 60_000);
4373 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4374 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4375 &scorer, &(), &random_seed_bytes) {
4376 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4377 } else { panic!(); }
4381 // Now, attempt to route 49 sats (just a bit below the capacity).
4382 let route_params = RouteParameters::from_payment_params_and_value(
4383 payment_params.clone(), 49_000);
4384 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4385 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4386 assert_eq!(route.paths.len(), 1);
4387 let mut total_amount_paid_msat = 0;
4388 for path in &route.paths {
4389 assert_eq!(path.hops.len(), 4);
4390 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4391 total_amount_paid_msat += path.final_value_msat();
4393 assert_eq!(total_amount_paid_msat, 49_000);
4397 // Attempt to route an exact amount is also fine
4398 let route_params = RouteParameters::from_payment_params_and_value(
4399 payment_params, 50_000);
4400 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4401 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4402 assert_eq!(route.paths.len(), 1);
4403 let mut total_amount_paid_msat = 0;
4404 for path in &route.paths {
4405 assert_eq!(path.hops.len(), 4);
4406 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4407 total_amount_paid_msat += path.final_value_msat();
4409 assert_eq!(total_amount_paid_msat, 50_000);
4414 fn ignore_fee_first_hop_test() {
4415 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4416 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4417 let scorer = ln_test_utils::TestScorer::new();
4418 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4419 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4420 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4422 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4423 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4424 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4425 short_channel_id: 1,
4428 cltv_expiry_delta: 0,
4429 htlc_minimum_msat: 0,
4430 htlc_maximum_msat: 100_000,
4431 fee_base_msat: 1_000_000,
4432 fee_proportional_millionths: 0,
4433 excess_data: Vec::new()
4435 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4436 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4437 short_channel_id: 3,
4440 cltv_expiry_delta: 0,
4441 htlc_minimum_msat: 0,
4442 htlc_maximum_msat: 50_000,
4444 fee_proportional_millionths: 0,
4445 excess_data: Vec::new()
4449 let route_params = RouteParameters::from_payment_params_and_value(
4450 payment_params, 50_000);
4451 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4452 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4453 assert_eq!(route.paths.len(), 1);
4454 let mut total_amount_paid_msat = 0;
4455 for path in &route.paths {
4456 assert_eq!(path.hops.len(), 2);
4457 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4458 total_amount_paid_msat += path.final_value_msat();
4460 assert_eq!(total_amount_paid_msat, 50_000);
4465 fn simple_mpp_route_test() {
4466 let (secp_ctx, _, _, _, _) = build_graph();
4467 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4468 let config = UserConfig::default();
4469 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4470 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4471 do_simple_mpp_route_test(clear_payment_params);
4473 // MPP to a 1-hop blinded path for nodes[2]
4474 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
4475 let blinded_path = BlindedPath {
4476 introduction_node_id: nodes[2],
4477 blinding_point: ln_test_utils::pubkey(42),
4478 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4480 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4482 fee_proportional_millionths: 0,
4483 htlc_minimum_msat: 0,
4484 htlc_maximum_msat: 0,
4485 cltv_expiry_delta: 0,
4486 features: BlindedHopFeatures::empty(),
4488 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4489 .with_bolt12_features(bolt12_features.clone()).unwrap();
4490 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4492 // MPP to 3 2-hop blinded paths
4493 let mut blinded_path_node_0 = blinded_path.clone();
4494 blinded_path_node_0.introduction_node_id = nodes[0];
4495 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4496 let mut node_0_payinfo = blinded_payinfo.clone();
4497 node_0_payinfo.htlc_maximum_msat = 50_000;
4499 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4500 blinded_path_node_7.introduction_node_id = nodes[7];
4501 let mut node_7_payinfo = blinded_payinfo.clone();
4502 node_7_payinfo.htlc_maximum_msat = 60_000;
4504 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4505 blinded_path_node_1.introduction_node_id = nodes[1];
4506 let mut node_1_payinfo = blinded_payinfo.clone();
4507 node_1_payinfo.htlc_maximum_msat = 180_000;
4509 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4511 (node_0_payinfo, blinded_path_node_0),
4512 (node_7_payinfo, blinded_path_node_7),
4513 (node_1_payinfo, blinded_path_node_1)
4515 .with_bolt12_features(bolt12_features).unwrap();
4516 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4520 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4521 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4522 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4523 let scorer = ln_test_utils::TestScorer::new();
4524 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4525 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4527 // We need a route consisting of 3 paths:
4528 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4529 // To achieve this, the amount being transferred should be around
4530 // the total capacity of these 3 paths.
4532 // First, we set limits on these (previously unlimited) channels.
4533 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4535 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4536 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4537 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4538 short_channel_id: 1,
4541 cltv_expiry_delta: 0,
4542 htlc_minimum_msat: 0,
4543 htlc_maximum_msat: 100_000,
4545 fee_proportional_millionths: 0,
4546 excess_data: Vec::new()
4548 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4549 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4550 short_channel_id: 3,
4553 cltv_expiry_delta: 0,
4554 htlc_minimum_msat: 0,
4555 htlc_maximum_msat: 50_000,
4557 fee_proportional_millionths: 0,
4558 excess_data: Vec::new()
4561 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4562 // (total limit 60).
4563 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4564 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4565 short_channel_id: 12,
4568 cltv_expiry_delta: 0,
4569 htlc_minimum_msat: 0,
4570 htlc_maximum_msat: 60_000,
4572 fee_proportional_millionths: 0,
4573 excess_data: Vec::new()
4575 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4576 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4577 short_channel_id: 13,
4580 cltv_expiry_delta: 0,
4581 htlc_minimum_msat: 0,
4582 htlc_maximum_msat: 60_000,
4584 fee_proportional_millionths: 0,
4585 excess_data: Vec::new()
4588 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4589 // (total capacity 180 sats).
4590 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4591 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4592 short_channel_id: 2,
4595 cltv_expiry_delta: 0,
4596 htlc_minimum_msat: 0,
4597 htlc_maximum_msat: 200_000,
4599 fee_proportional_millionths: 0,
4600 excess_data: Vec::new()
4602 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4603 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4604 short_channel_id: 4,
4607 cltv_expiry_delta: 0,
4608 htlc_minimum_msat: 0,
4609 htlc_maximum_msat: 180_000,
4611 fee_proportional_millionths: 0,
4612 excess_data: Vec::new()
4616 // Attempt to route more than available results in a failure.
4617 let route_params = RouteParameters::from_payment_params_and_value(
4618 payment_params.clone(), 300_000);
4619 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4620 &our_id, &route_params, &network_graph.read_only(), None,
4621 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4622 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4623 } else { panic!(); }
4627 // Attempt to route while setting max_path_count to 0 results in a failure.
4628 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4629 let route_params = RouteParameters::from_payment_params_and_value(
4630 zero_payment_params, 100);
4631 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4632 &our_id, &route_params, &network_graph.read_only(), None,
4633 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4634 assert_eq!(err, "Can't find a route with no paths allowed.");
4635 } else { panic!(); }
4639 // Attempt to route while setting max_path_count to 3 results in a failure.
4640 // This is the case because the minimal_value_contribution_msat would require each path
4641 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4642 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4643 let route_params = RouteParameters::from_payment_params_and_value(
4644 fail_payment_params, 250_000);
4645 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4646 &our_id, &route_params, &network_graph.read_only(), None,
4647 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4648 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4649 } else { panic!(); }
4653 // Now, attempt to route 250 sats (just a bit below the capacity).
4654 // Our algorithm should provide us with these 3 paths.
4655 let route_params = RouteParameters::from_payment_params_and_value(
4656 payment_params.clone(), 250_000);
4657 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4658 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4659 assert_eq!(route.paths.len(), 3);
4660 let mut total_amount_paid_msat = 0;
4661 for path in &route.paths {
4662 if let Some(bt) = &path.blinded_tail {
4663 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4665 assert_eq!(path.hops.len(), 2);
4666 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4668 total_amount_paid_msat += path.final_value_msat();
4670 assert_eq!(total_amount_paid_msat, 250_000);
4674 // Attempt to route an exact amount is also fine
4675 let route_params = RouteParameters::from_payment_params_and_value(
4676 payment_params.clone(), 290_000);
4677 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4678 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4679 assert_eq!(route.paths.len(), 3);
4680 let mut total_amount_paid_msat = 0;
4681 for path in &route.paths {
4682 if payment_params.payee.blinded_route_hints().len() != 0 {
4683 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
4684 if let Some(bt) = &path.blinded_tail {
4685 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4686 if bt.hops.len() > 1 {
4687 assert_eq!(path.hops.last().unwrap().pubkey,
4688 payment_params.payee.blinded_route_hints().iter()
4689 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
4690 .map(|(_, p)| p.introduction_node_id).unwrap());
4692 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4695 assert_eq!(path.hops.len(), 2);
4696 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4698 total_amount_paid_msat += path.final_value_msat();
4700 assert_eq!(total_amount_paid_msat, 290_000);
4705 fn long_mpp_route_test() {
4706 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4707 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4708 let scorer = ln_test_utils::TestScorer::new();
4709 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4710 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4711 let config = UserConfig::default();
4712 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4713 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4715 // We need a route consisting of 3 paths:
4716 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4717 // Note that these paths overlap (channels 5, 12, 13).
4718 // We will route 300 sats.
4719 // Each path will have 100 sats capacity, those channels which
4720 // are used twice will have 200 sats capacity.
4722 // Disable other potential paths.
4723 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4724 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4725 short_channel_id: 2,
4728 cltv_expiry_delta: 0,
4729 htlc_minimum_msat: 0,
4730 htlc_maximum_msat: 100_000,
4732 fee_proportional_millionths: 0,
4733 excess_data: Vec::new()
4735 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4736 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4737 short_channel_id: 7,
4740 cltv_expiry_delta: 0,
4741 htlc_minimum_msat: 0,
4742 htlc_maximum_msat: 100_000,
4744 fee_proportional_millionths: 0,
4745 excess_data: Vec::new()
4748 // Path via {node0, node2} is channels {1, 3, 5}.
4749 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4750 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4751 short_channel_id: 1,
4754 cltv_expiry_delta: 0,
4755 htlc_minimum_msat: 0,
4756 htlc_maximum_msat: 100_000,
4758 fee_proportional_millionths: 0,
4759 excess_data: Vec::new()
4761 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4762 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4763 short_channel_id: 3,
4766 cltv_expiry_delta: 0,
4767 htlc_minimum_msat: 0,
4768 htlc_maximum_msat: 100_000,
4770 fee_proportional_millionths: 0,
4771 excess_data: Vec::new()
4774 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4775 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4776 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4777 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4778 short_channel_id: 5,
4781 cltv_expiry_delta: 0,
4782 htlc_minimum_msat: 0,
4783 htlc_maximum_msat: 200_000,
4785 fee_proportional_millionths: 0,
4786 excess_data: Vec::new()
4789 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4790 // Add 100 sats to the capacities of {12, 13}, because these channels
4791 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4792 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4793 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4794 short_channel_id: 12,
4797 cltv_expiry_delta: 0,
4798 htlc_minimum_msat: 0,
4799 htlc_maximum_msat: 200_000,
4801 fee_proportional_millionths: 0,
4802 excess_data: Vec::new()
4804 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4805 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4806 short_channel_id: 13,
4809 cltv_expiry_delta: 0,
4810 htlc_minimum_msat: 0,
4811 htlc_maximum_msat: 200_000,
4813 fee_proportional_millionths: 0,
4814 excess_data: Vec::new()
4817 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4818 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4819 short_channel_id: 6,
4822 cltv_expiry_delta: 0,
4823 htlc_minimum_msat: 0,
4824 htlc_maximum_msat: 100_000,
4826 fee_proportional_millionths: 0,
4827 excess_data: Vec::new()
4829 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4830 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4831 short_channel_id: 11,
4834 cltv_expiry_delta: 0,
4835 htlc_minimum_msat: 0,
4836 htlc_maximum_msat: 100_000,
4838 fee_proportional_millionths: 0,
4839 excess_data: Vec::new()
4842 // Path via {node7, node2} is channels {12, 13, 5}.
4843 // We already limited them to 200 sats (they are used twice for 100 sats).
4844 // Nothing to do here.
4847 // Attempt to route more than available results in a failure.
4848 let route_params = RouteParameters::from_payment_params_and_value(
4849 payment_params.clone(), 350_000);
4850 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4851 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4852 &scorer, &(), &random_seed_bytes) {
4853 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4854 } else { panic!(); }
4858 // Now, attempt to route 300 sats (exact amount we can route).
4859 // Our algorithm should provide us with these 3 paths, 100 sats each.
4860 let route_params = RouteParameters::from_payment_params_and_value(
4861 payment_params, 300_000);
4862 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4863 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4864 assert_eq!(route.paths.len(), 3);
4866 let mut total_amount_paid_msat = 0;
4867 for path in &route.paths {
4868 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4869 total_amount_paid_msat += path.final_value_msat();
4871 assert_eq!(total_amount_paid_msat, 300_000);
4877 fn mpp_cheaper_route_test() {
4878 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4879 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4880 let scorer = ln_test_utils::TestScorer::new();
4881 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4882 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4883 let config = UserConfig::default();
4884 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4886 // This test checks that if we have two cheaper paths and one more expensive path,
4887 // so that liquidity-wise any 2 of 3 combination is sufficient,
4888 // two cheaper paths will be taken.
4889 // These paths have equal available liquidity.
4891 // We need a combination of 3 paths:
4892 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4893 // Note that these paths overlap (channels 5, 12, 13).
4894 // Each path will have 100 sats capacity, those channels which
4895 // are used twice will have 200 sats capacity.
4897 // Disable other potential paths.
4898 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4899 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4900 short_channel_id: 2,
4903 cltv_expiry_delta: 0,
4904 htlc_minimum_msat: 0,
4905 htlc_maximum_msat: 100_000,
4907 fee_proportional_millionths: 0,
4908 excess_data: Vec::new()
4910 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4911 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4912 short_channel_id: 7,
4915 cltv_expiry_delta: 0,
4916 htlc_minimum_msat: 0,
4917 htlc_maximum_msat: 100_000,
4919 fee_proportional_millionths: 0,
4920 excess_data: Vec::new()
4923 // Path via {node0, node2} is channels {1, 3, 5}.
4924 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4925 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4926 short_channel_id: 1,
4929 cltv_expiry_delta: 0,
4930 htlc_minimum_msat: 0,
4931 htlc_maximum_msat: 100_000,
4933 fee_proportional_millionths: 0,
4934 excess_data: Vec::new()
4936 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4937 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4938 short_channel_id: 3,
4941 cltv_expiry_delta: 0,
4942 htlc_minimum_msat: 0,
4943 htlc_maximum_msat: 100_000,
4945 fee_proportional_millionths: 0,
4946 excess_data: Vec::new()
4949 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4950 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4951 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4952 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4953 short_channel_id: 5,
4956 cltv_expiry_delta: 0,
4957 htlc_minimum_msat: 0,
4958 htlc_maximum_msat: 200_000,
4960 fee_proportional_millionths: 0,
4961 excess_data: Vec::new()
4964 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4965 // Add 100 sats to the capacities of {12, 13}, because these channels
4966 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4967 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4968 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4969 short_channel_id: 12,
4972 cltv_expiry_delta: 0,
4973 htlc_minimum_msat: 0,
4974 htlc_maximum_msat: 200_000,
4976 fee_proportional_millionths: 0,
4977 excess_data: Vec::new()
4979 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4980 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4981 short_channel_id: 13,
4984 cltv_expiry_delta: 0,
4985 htlc_minimum_msat: 0,
4986 htlc_maximum_msat: 200_000,
4988 fee_proportional_millionths: 0,
4989 excess_data: Vec::new()
4992 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4993 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4994 short_channel_id: 6,
4997 cltv_expiry_delta: 0,
4998 htlc_minimum_msat: 0,
4999 htlc_maximum_msat: 100_000,
5000 fee_base_msat: 1_000,
5001 fee_proportional_millionths: 0,
5002 excess_data: Vec::new()
5004 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5005 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5006 short_channel_id: 11,
5009 cltv_expiry_delta: 0,
5010 htlc_minimum_msat: 0,
5011 htlc_maximum_msat: 100_000,
5013 fee_proportional_millionths: 0,
5014 excess_data: Vec::new()
5017 // Path via {node7, node2} is channels {12, 13, 5}.
5018 // We already limited them to 200 sats (they are used twice for 100 sats).
5019 // Nothing to do here.
5022 // Now, attempt to route 180 sats.
5023 // Our algorithm should provide us with these 2 paths.
5024 let route_params = RouteParameters::from_payment_params_and_value(
5025 payment_params, 180_000);
5026 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5027 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5028 assert_eq!(route.paths.len(), 2);
5030 let mut total_value_transferred_msat = 0;
5031 let mut total_paid_msat = 0;
5032 for path in &route.paths {
5033 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5034 total_value_transferred_msat += path.final_value_msat();
5035 for hop in &path.hops {
5036 total_paid_msat += hop.fee_msat;
5039 // If we paid fee, this would be higher.
5040 assert_eq!(total_value_transferred_msat, 180_000);
5041 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5042 assert_eq!(total_fees_paid, 0);
5047 fn fees_on_mpp_route_test() {
5048 // This test makes sure that MPP algorithm properly takes into account
5049 // fees charged on the channels, by making the fees impactful:
5050 // if the fee is not properly accounted for, the behavior is different.
5051 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5052 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5053 let scorer = ln_test_utils::TestScorer::new();
5054 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5055 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5056 let config = UserConfig::default();
5057 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5059 // We need a route consisting of 2 paths:
5060 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5061 // We will route 200 sats, Each path will have 100 sats capacity.
5063 // This test is not particularly stable: e.g.,
5064 // there's a way to route via {node0, node2, node4}.
5065 // It works while pathfinding is deterministic, but can be broken otherwise.
5066 // It's fine to ignore this concern for now.
5068 // Disable other potential paths.
5069 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5070 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5071 short_channel_id: 2,
5074 cltv_expiry_delta: 0,
5075 htlc_minimum_msat: 0,
5076 htlc_maximum_msat: 100_000,
5078 fee_proportional_millionths: 0,
5079 excess_data: Vec::new()
5082 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5083 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5084 short_channel_id: 7,
5087 cltv_expiry_delta: 0,
5088 htlc_minimum_msat: 0,
5089 htlc_maximum_msat: 100_000,
5091 fee_proportional_millionths: 0,
5092 excess_data: Vec::new()
5095 // Path via {node0, node2} is channels {1, 3, 5}.
5096 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5097 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5098 short_channel_id: 1,
5101 cltv_expiry_delta: 0,
5102 htlc_minimum_msat: 0,
5103 htlc_maximum_msat: 100_000,
5105 fee_proportional_millionths: 0,
5106 excess_data: Vec::new()
5108 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5109 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5110 short_channel_id: 3,
5113 cltv_expiry_delta: 0,
5114 htlc_minimum_msat: 0,
5115 htlc_maximum_msat: 100_000,
5117 fee_proportional_millionths: 0,
5118 excess_data: Vec::new()
5121 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5122 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5123 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5124 short_channel_id: 5,
5127 cltv_expiry_delta: 0,
5128 htlc_minimum_msat: 0,
5129 htlc_maximum_msat: 100_000,
5131 fee_proportional_millionths: 0,
5132 excess_data: Vec::new()
5135 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5136 // All channels should be 100 sats capacity. But for the fee experiment,
5137 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5138 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5139 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5140 // so no matter how large are other channels,
5141 // the whole path will be limited by 100 sats with just these 2 conditions:
5142 // - channel 12 capacity is 250 sats
5143 // - fee for channel 6 is 150 sats
5144 // Let's test this by enforcing these 2 conditions and removing other limits.
5145 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5146 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5147 short_channel_id: 12,
5150 cltv_expiry_delta: 0,
5151 htlc_minimum_msat: 0,
5152 htlc_maximum_msat: 250_000,
5154 fee_proportional_millionths: 0,
5155 excess_data: Vec::new()
5157 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5158 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5159 short_channel_id: 13,
5162 cltv_expiry_delta: 0,
5163 htlc_minimum_msat: 0,
5164 htlc_maximum_msat: MAX_VALUE_MSAT,
5166 fee_proportional_millionths: 0,
5167 excess_data: Vec::new()
5170 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5171 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5172 short_channel_id: 6,
5175 cltv_expiry_delta: 0,
5176 htlc_minimum_msat: 0,
5177 htlc_maximum_msat: MAX_VALUE_MSAT,
5178 fee_base_msat: 150_000,
5179 fee_proportional_millionths: 0,
5180 excess_data: Vec::new()
5182 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5183 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5184 short_channel_id: 11,
5187 cltv_expiry_delta: 0,
5188 htlc_minimum_msat: 0,
5189 htlc_maximum_msat: MAX_VALUE_MSAT,
5191 fee_proportional_millionths: 0,
5192 excess_data: Vec::new()
5196 // Attempt to route more than available results in a failure.
5197 let route_params = RouteParameters::from_payment_params_and_value(
5198 payment_params.clone(), 210_000);
5199 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5200 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5201 &scorer, &(), &random_seed_bytes) {
5202 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5203 } else { panic!(); }
5207 // Now, attempt to route 200 sats (exact amount we can route).
5208 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 200_000);
5209 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5210 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5211 assert_eq!(route.paths.len(), 2);
5213 let mut total_amount_paid_msat = 0;
5214 for path in &route.paths {
5215 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5216 total_amount_paid_msat += path.final_value_msat();
5218 assert_eq!(total_amount_paid_msat, 200_000);
5219 assert_eq!(route.get_total_fees(), 150_000);
5224 fn mpp_with_last_hops() {
5225 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5226 // via a single last-hop route hint, we'd fail to route if we first collected routes
5227 // totaling close but not quite enough to fund the full payment.
5229 // This was because we considered last-hop hints to have exactly the sought payment amount
5230 // instead of the amount we were trying to collect, needlessly limiting our path searching
5231 // at the very first hop.
5233 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5234 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5235 // to only have the remaining to-collect amount in available liquidity.
5237 // This bug appeared in production in some specific channel configurations.
5238 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5239 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5240 let scorer = ln_test_utils::TestScorer::new();
5241 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5242 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5243 let config = UserConfig::default();
5244 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5245 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5246 src_node_id: nodes[2],
5247 short_channel_id: 42,
5248 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5249 cltv_expiry_delta: 42,
5250 htlc_minimum_msat: None,
5251 htlc_maximum_msat: None,
5252 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5254 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5255 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5256 // would first use the no-fee route and then fail to find a path along the second route as
5257 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5258 // under 5% of our payment amount.
5259 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5260 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5261 short_channel_id: 1,
5264 cltv_expiry_delta: (5 << 4) | 5,
5265 htlc_minimum_msat: 0,
5266 htlc_maximum_msat: 99_000,
5267 fee_base_msat: u32::max_value(),
5268 fee_proportional_millionths: u32::max_value(),
5269 excess_data: Vec::new()
5271 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5272 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5273 short_channel_id: 2,
5276 cltv_expiry_delta: (5 << 4) | 3,
5277 htlc_minimum_msat: 0,
5278 htlc_maximum_msat: 99_000,
5279 fee_base_msat: u32::max_value(),
5280 fee_proportional_millionths: u32::max_value(),
5281 excess_data: Vec::new()
5283 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5284 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5285 short_channel_id: 4,
5288 cltv_expiry_delta: (4 << 4) | 1,
5289 htlc_minimum_msat: 0,
5290 htlc_maximum_msat: MAX_VALUE_MSAT,
5292 fee_proportional_millionths: 0,
5293 excess_data: Vec::new()
5295 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5296 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5297 short_channel_id: 13,
5299 flags: 0|2, // Channel disabled
5300 cltv_expiry_delta: (13 << 4) | 1,
5301 htlc_minimum_msat: 0,
5302 htlc_maximum_msat: MAX_VALUE_MSAT,
5304 fee_proportional_millionths: 2000000,
5305 excess_data: Vec::new()
5308 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5310 let route_params = RouteParameters::from_payment_params_and_value(
5311 payment_params, 100_000);
5312 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5313 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5314 assert_eq!(route.paths.len(), 2);
5315 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5316 // Paths are manually ordered ordered by SCID, so:
5317 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5318 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5319 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5320 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5321 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5322 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5323 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5324 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5325 assert_eq!(route.get_total_fees(), 1);
5326 assert_eq!(route.get_total_amount(), 100_000);
5330 fn drop_lowest_channel_mpp_route_test() {
5331 // This test checks that low-capacity channel is dropped when after
5332 // path finding we realize that we found more capacity than we need.
5333 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5334 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5335 let scorer = ln_test_utils::TestScorer::new();
5336 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5337 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5338 let config = UserConfig::default();
5339 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5340 .with_max_channel_saturation_power_of_half(0);
5342 // We need a route consisting of 3 paths:
5343 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5345 // The first and the second paths should be sufficient, but the third should be
5346 // cheaper, so that we select it but drop later.
5348 // First, we set limits on these (previously unlimited) channels.
5349 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5351 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5352 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5353 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5354 short_channel_id: 1,
5357 cltv_expiry_delta: 0,
5358 htlc_minimum_msat: 0,
5359 htlc_maximum_msat: 100_000,
5361 fee_proportional_millionths: 0,
5362 excess_data: Vec::new()
5364 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5365 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5366 short_channel_id: 3,
5369 cltv_expiry_delta: 0,
5370 htlc_minimum_msat: 0,
5371 htlc_maximum_msat: 50_000,
5373 fee_proportional_millionths: 0,
5374 excess_data: Vec::new()
5377 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5378 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5379 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5380 short_channel_id: 12,
5383 cltv_expiry_delta: 0,
5384 htlc_minimum_msat: 0,
5385 htlc_maximum_msat: 60_000,
5387 fee_proportional_millionths: 0,
5388 excess_data: Vec::new()
5390 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5391 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5392 short_channel_id: 13,
5395 cltv_expiry_delta: 0,
5396 htlc_minimum_msat: 0,
5397 htlc_maximum_msat: 60_000,
5399 fee_proportional_millionths: 0,
5400 excess_data: Vec::new()
5403 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5404 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5405 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5406 short_channel_id: 2,
5409 cltv_expiry_delta: 0,
5410 htlc_minimum_msat: 0,
5411 htlc_maximum_msat: 20_000,
5413 fee_proportional_millionths: 0,
5414 excess_data: Vec::new()
5416 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5417 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5418 short_channel_id: 4,
5421 cltv_expiry_delta: 0,
5422 htlc_minimum_msat: 0,
5423 htlc_maximum_msat: 20_000,
5425 fee_proportional_millionths: 0,
5426 excess_data: Vec::new()
5430 // Attempt to route more than available results in a failure.
5431 let route_params = RouteParameters::from_payment_params_and_value(
5432 payment_params.clone(), 150_000);
5433 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5434 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5435 &scorer, &(), &random_seed_bytes) {
5436 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5437 } else { panic!(); }
5441 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5442 // Our algorithm should provide us with these 3 paths.
5443 let route_params = RouteParameters::from_payment_params_and_value(
5444 payment_params.clone(), 125_000);
5445 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5446 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5447 assert_eq!(route.paths.len(), 3);
5448 let mut total_amount_paid_msat = 0;
5449 for path in &route.paths {
5450 assert_eq!(path.hops.len(), 2);
5451 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5452 total_amount_paid_msat += path.final_value_msat();
5454 assert_eq!(total_amount_paid_msat, 125_000);
5458 // Attempt to route without the last small cheap channel
5459 let route_params = RouteParameters::from_payment_params_and_value(
5460 payment_params, 90_000);
5461 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5462 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5463 assert_eq!(route.paths.len(), 2);
5464 let mut total_amount_paid_msat = 0;
5465 for path in &route.paths {
5466 assert_eq!(path.hops.len(), 2);
5467 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5468 total_amount_paid_msat += path.final_value_msat();
5470 assert_eq!(total_amount_paid_msat, 90_000);
5475 fn min_criteria_consistency() {
5476 // Test that we don't use an inconsistent metric between updating and walking nodes during
5477 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5478 // was updated with a different criterion from the heap sorting, resulting in loops in
5479 // calculated paths. We test for that specific case here.
5481 // We construct a network that looks like this:
5483 // node2 -1(3)2- node3
5487 // node1 -1(5)2- node4 -1(1)2- node6
5493 // We create a loop on the side of our real path - our destination is node 6, with a
5494 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5495 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5496 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5497 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5498 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5499 // "previous hop" being set to node 3, creating a loop in the path.
5500 let secp_ctx = Secp256k1::new();
5501 let logger = Arc::new(ln_test_utils::TestLogger::new());
5502 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5503 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5504 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5505 let scorer = ln_test_utils::TestScorer::new();
5506 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5507 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5508 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5510 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5511 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5512 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5513 short_channel_id: 6,
5516 cltv_expiry_delta: (6 << 4) | 0,
5517 htlc_minimum_msat: 0,
5518 htlc_maximum_msat: MAX_VALUE_MSAT,
5520 fee_proportional_millionths: 0,
5521 excess_data: Vec::new()
5523 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5525 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5526 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5527 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5528 short_channel_id: 5,
5531 cltv_expiry_delta: (5 << 4) | 0,
5532 htlc_minimum_msat: 0,
5533 htlc_maximum_msat: MAX_VALUE_MSAT,
5535 fee_proportional_millionths: 0,
5536 excess_data: Vec::new()
5538 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5540 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5541 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5542 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5543 short_channel_id: 4,
5546 cltv_expiry_delta: (4 << 4) | 0,
5547 htlc_minimum_msat: 0,
5548 htlc_maximum_msat: MAX_VALUE_MSAT,
5550 fee_proportional_millionths: 0,
5551 excess_data: Vec::new()
5553 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5555 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5556 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5557 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5558 short_channel_id: 3,
5561 cltv_expiry_delta: (3 << 4) | 0,
5562 htlc_minimum_msat: 0,
5563 htlc_maximum_msat: MAX_VALUE_MSAT,
5565 fee_proportional_millionths: 0,
5566 excess_data: Vec::new()
5568 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5570 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5571 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5572 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5573 short_channel_id: 2,
5576 cltv_expiry_delta: (2 << 4) | 0,
5577 htlc_minimum_msat: 0,
5578 htlc_maximum_msat: MAX_VALUE_MSAT,
5580 fee_proportional_millionths: 0,
5581 excess_data: Vec::new()
5584 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5585 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5586 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5587 short_channel_id: 1,
5590 cltv_expiry_delta: (1 << 4) | 0,
5591 htlc_minimum_msat: 100,
5592 htlc_maximum_msat: MAX_VALUE_MSAT,
5594 fee_proportional_millionths: 0,
5595 excess_data: Vec::new()
5597 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5600 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5601 let route_params = RouteParameters::from_payment_params_and_value(
5602 payment_params, 10_000);
5603 let route = get_route(&our_id, &route_params, &network.read_only(), None,
5604 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5605 assert_eq!(route.paths.len(), 1);
5606 assert_eq!(route.paths[0].hops.len(), 3);
5608 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5609 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5610 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5611 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5612 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5613 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5615 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5616 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5617 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5618 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5619 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5620 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5622 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5623 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5624 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5625 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5626 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5627 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5633 fn exact_fee_liquidity_limit() {
5634 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5635 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5636 // we calculated fees on a higher value, resulting in us ignoring such paths.
5637 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5638 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5639 let scorer = ln_test_utils::TestScorer::new();
5640 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5641 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5642 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5644 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5646 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5647 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5648 short_channel_id: 2,
5651 cltv_expiry_delta: 0,
5652 htlc_minimum_msat: 0,
5653 htlc_maximum_msat: 85_000,
5655 fee_proportional_millionths: 0,
5656 excess_data: Vec::new()
5659 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5660 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5661 short_channel_id: 12,
5664 cltv_expiry_delta: (4 << 4) | 1,
5665 htlc_minimum_msat: 0,
5666 htlc_maximum_msat: 270_000,
5668 fee_proportional_millionths: 1000000,
5669 excess_data: Vec::new()
5673 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5674 // 200% fee charged channel 13 in the 1-to-2 direction.
5675 let route_params = RouteParameters::from_payment_params_and_value(
5676 payment_params, 90_000);
5677 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5678 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5679 assert_eq!(route.paths.len(), 1);
5680 assert_eq!(route.paths[0].hops.len(), 2);
5682 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5683 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5684 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5685 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5686 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5687 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5689 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5690 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5691 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5692 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5693 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5694 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5699 fn htlc_max_reduction_below_min() {
5700 // Test that if, while walking the graph, we reduce the value being sent to meet an
5701 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5702 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5703 // resulting in us thinking there is no possible path, even if other paths exist.
5704 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5705 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5706 let scorer = ln_test_utils::TestScorer::new();
5707 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5708 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5709 let config = UserConfig::default();
5710 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5712 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5713 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5714 // then try to send 90_000.
5715 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5716 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5717 short_channel_id: 2,
5720 cltv_expiry_delta: 0,
5721 htlc_minimum_msat: 0,
5722 htlc_maximum_msat: 80_000,
5724 fee_proportional_millionths: 0,
5725 excess_data: Vec::new()
5727 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5728 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5729 short_channel_id: 4,
5732 cltv_expiry_delta: (4 << 4) | 1,
5733 htlc_minimum_msat: 90_000,
5734 htlc_maximum_msat: MAX_VALUE_MSAT,
5736 fee_proportional_millionths: 0,
5737 excess_data: Vec::new()
5741 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5742 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5743 // expensive) channels 12-13 path.
5744 let route_params = RouteParameters::from_payment_params_and_value(
5745 payment_params, 90_000);
5746 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5747 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5748 assert_eq!(route.paths.len(), 1);
5749 assert_eq!(route.paths[0].hops.len(), 2);
5751 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5752 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5753 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5754 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5755 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5756 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5758 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5759 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5760 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5761 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5762 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5763 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5768 fn multiple_direct_first_hops() {
5769 // Previously we'd only ever considered one first hop path per counterparty.
5770 // However, as we don't restrict users to one channel per peer, we really need to support
5771 // looking at all first hop paths.
5772 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5773 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5774 // route over multiple channels with the same first hop.
5775 let secp_ctx = Secp256k1::new();
5776 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5777 let logger = Arc::new(ln_test_utils::TestLogger::new());
5778 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5779 let scorer = ln_test_utils::TestScorer::new();
5780 let config = UserConfig::default();
5781 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5782 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5783 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5786 let route_params = RouteParameters::from_payment_params_and_value(
5787 payment_params.clone(), 100_000);
5788 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5789 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5790 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5791 ]), Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5792 assert_eq!(route.paths.len(), 1);
5793 assert_eq!(route.paths[0].hops.len(), 1);
5795 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5796 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5797 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5800 let route_params = RouteParameters::from_payment_params_and_value(
5801 payment_params.clone(), 100_000);
5802 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5803 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5804 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5805 ]), Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5806 assert_eq!(route.paths.len(), 2);
5807 assert_eq!(route.paths[0].hops.len(), 1);
5808 assert_eq!(route.paths[1].hops.len(), 1);
5810 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5811 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5813 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5814 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5816 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5817 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5821 // If we have a bunch of outbound channels to the same node, where most are not
5822 // sufficient to pay the full payment, but one is, we should default to just using the
5823 // one single channel that has sufficient balance, avoiding MPP.
5825 // If we have several options above the 3xpayment value threshold, we should pick the
5826 // smallest of them, avoiding further fragmenting our available outbound balance to
5828 let route_params = RouteParameters::from_payment_params_and_value(
5829 payment_params, 100_000);
5830 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5831 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5832 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5833 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5834 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5835 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5836 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5837 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5838 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5839 ]), Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5840 assert_eq!(route.paths.len(), 1);
5841 assert_eq!(route.paths[0].hops.len(), 1);
5843 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5844 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5845 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5850 fn prefers_shorter_route_with_higher_fees() {
5851 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5852 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5853 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5855 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5856 let scorer = ln_test_utils::TestScorer::new();
5857 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5858 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5859 let route_params = RouteParameters::from_payment_params_and_value(
5860 payment_params.clone(), 100);
5861 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
5862 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5863 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5865 assert_eq!(route.get_total_fees(), 100);
5866 assert_eq!(route.get_total_amount(), 100);
5867 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5869 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5870 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5871 let scorer = FixedPenaltyScorer::with_penalty(100);
5872 let route_params = RouteParameters::from_payment_params_and_value(
5873 payment_params, 100);
5874 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
5875 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5876 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5878 assert_eq!(route.get_total_fees(), 300);
5879 assert_eq!(route.get_total_amount(), 100);
5880 assert_eq!(path, vec![2, 4, 7, 10]);
5883 struct BadChannelScorer {
5884 short_channel_id: u64,
5888 impl Writeable for BadChannelScorer {
5889 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5891 impl ScoreLookUp for BadChannelScorer {
5892 type ScoreParams = ();
5893 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5894 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5898 struct BadNodeScorer {
5903 impl Writeable for BadNodeScorer {
5904 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5907 impl ScoreLookUp for BadNodeScorer {
5908 type ScoreParams = ();
5909 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5910 if *target == self.node_id { u64::max_value() } else { 0 }
5915 fn avoids_routing_through_bad_channels_and_nodes() {
5916 let (secp_ctx, network, _, _, logger) = build_graph();
5917 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5918 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5919 let network_graph = network.read_only();
5921 // A path to nodes[6] exists when no penalties are applied to any channel.
5922 let scorer = ln_test_utils::TestScorer::new();
5923 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5924 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5925 let route_params = RouteParameters::from_payment_params_and_value(
5926 payment_params, 100);
5927 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
5928 &scorer, &(), &random_seed_bytes).unwrap();
5929 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5931 assert_eq!(route.get_total_fees(), 100);
5932 assert_eq!(route.get_total_amount(), 100);
5933 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5935 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5936 let scorer = BadChannelScorer { short_channel_id: 6 };
5937 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
5938 &scorer, &(), &random_seed_bytes).unwrap();
5939 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5941 assert_eq!(route.get_total_fees(), 300);
5942 assert_eq!(route.get_total_amount(), 100);
5943 assert_eq!(path, vec![2, 4, 7, 10]);
5945 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5946 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5947 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
5948 &scorer, &(), &random_seed_bytes) {
5949 Err(LightningError { err, .. } ) => {
5950 assert_eq!(err, "Failed to find a path to the given destination");
5952 Ok(_) => panic!("Expected error"),
5957 fn total_fees_single_path() {
5959 paths: vec![Path { hops: vec![
5961 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5962 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5963 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5966 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5967 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5968 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5971 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5972 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5973 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5975 ], blinded_tail: None }],
5979 assert_eq!(route.get_total_fees(), 250);
5980 assert_eq!(route.get_total_amount(), 225);
5984 fn total_fees_multi_path() {
5986 paths: vec![Path { hops: vec![
5988 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5989 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5990 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5993 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5994 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5995 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5997 ], blinded_tail: None }, Path { hops: vec![
5999 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6000 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6001 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
6004 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6005 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6006 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
6008 ], blinded_tail: None }],
6012 assert_eq!(route.get_total_fees(), 200);
6013 assert_eq!(route.get_total_amount(), 300);
6017 fn total_empty_route_no_panic() {
6018 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6019 // would both panic if the route was completely empty. We test to ensure they return 0
6020 // here, even though its somewhat nonsensical as a route.
6021 let route = Route { paths: Vec::new(), route_params: None };
6023 assert_eq!(route.get_total_fees(), 0);
6024 assert_eq!(route.get_total_amount(), 0);
6028 fn limits_total_cltv_delta() {
6029 let (secp_ctx, network, _, _, logger) = build_graph();
6030 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6031 let network_graph = network.read_only();
6033 let scorer = ln_test_utils::TestScorer::new();
6035 // Make sure that generally there is at least one route available
6036 let feasible_max_total_cltv_delta = 1008;
6037 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6038 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6039 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6040 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6041 let route_params = RouteParameters::from_payment_params_and_value(
6042 feasible_payment_params, 100);
6043 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6044 &scorer, &(), &random_seed_bytes).unwrap();
6045 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6046 assert_ne!(path.len(), 0);
6048 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6049 let fail_max_total_cltv_delta = 23;
6050 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6051 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6052 let route_params = RouteParameters::from_payment_params_and_value(
6053 fail_payment_params, 100);
6054 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6055 &(), &random_seed_bytes)
6057 Err(LightningError { err, .. } ) => {
6058 assert_eq!(err, "Failed to find a path to the given destination");
6060 Ok(_) => panic!("Expected error"),
6065 fn avoids_recently_failed_paths() {
6066 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6067 // randomly inserting channels into it until we can't find a route anymore.
6068 let (secp_ctx, network, _, _, logger) = build_graph();
6069 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6070 let network_graph = network.read_only();
6072 let scorer = ln_test_utils::TestScorer::new();
6073 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6074 .with_max_path_count(1);
6075 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6076 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6078 // We should be able to find a route initially, and then after we fail a few random
6079 // channels eventually we won't be able to any longer.
6080 let route_params = RouteParameters::from_payment_params_and_value(
6081 payment_params.clone(), 100);
6082 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6083 &scorer, &(), &random_seed_bytes).is_ok());
6085 let route_params = RouteParameters::from_payment_params_and_value(
6086 payment_params.clone(), 100);
6087 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6088 Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
6090 for chan in route.paths[0].hops.iter() {
6091 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6093 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6094 % route.paths[0].hops.len();
6095 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6101 fn limits_path_length() {
6102 let (secp_ctx, network, _, _, logger) = build_line_graph();
6103 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6104 let network_graph = network.read_only();
6106 let scorer = ln_test_utils::TestScorer::new();
6107 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6108 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6110 // First check we can actually create a long route on this graph.
6111 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6112 let route_params = RouteParameters::from_payment_params_and_value(
6113 feasible_payment_params, 100);
6114 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6115 &scorer, &(), &random_seed_bytes).unwrap();
6116 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6117 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6119 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6120 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6121 let route_params = RouteParameters::from_payment_params_and_value(
6122 fail_payment_params, 100);
6123 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6124 &(), &random_seed_bytes)
6126 Err(LightningError { err, .. } ) => {
6127 assert_eq!(err, "Failed to find a path to the given destination");
6129 Ok(_) => panic!("Expected error"),
6134 fn adds_and_limits_cltv_offset() {
6135 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6136 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6138 let scorer = ln_test_utils::TestScorer::new();
6140 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6141 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6142 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6143 let route_params = RouteParameters::from_payment_params_and_value(
6144 payment_params.clone(), 100);
6145 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6146 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6147 assert_eq!(route.paths.len(), 1);
6149 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6151 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6152 let mut route_default = route.clone();
6153 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6154 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6155 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6156 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6157 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6159 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6160 let mut route_limited = route.clone();
6161 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6162 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6163 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6164 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6165 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6169 fn adds_plausible_cltv_offset() {
6170 let (secp_ctx, network, _, _, logger) = build_graph();
6171 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6172 let network_graph = network.read_only();
6173 let network_nodes = network_graph.nodes();
6174 let network_channels = network_graph.channels();
6175 let scorer = ln_test_utils::TestScorer::new();
6176 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6177 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6178 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6180 let route_params = RouteParameters::from_payment_params_and_value(
6181 payment_params.clone(), 100);
6182 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6183 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6184 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6186 let mut path_plausibility = vec![];
6188 for p in route.paths {
6189 // 1. Select random observation point
6190 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6191 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6193 prng.process_in_place(&mut random_bytes);
6194 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6195 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6197 // 2. Calculate what CLTV expiry delta we would observe there
6198 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6200 // 3. Starting from the observation point, find candidate paths
6201 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6202 candidates.push_back((observation_point, vec![]));
6204 let mut found_plausible_candidate = false;
6206 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6207 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6208 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6209 found_plausible_candidate = true;
6210 break 'candidate_loop;
6214 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6215 for channel_id in &cur_node.channels {
6216 if let Some(channel_info) = network_channels.get(&channel_id) {
6217 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6218 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6219 if cur_path_cltv_deltas.iter().sum::<u32>()
6220 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6221 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6222 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6223 candidates.push_back((*next_id, new_path_cltv_deltas));
6231 path_plausibility.push(found_plausible_candidate);
6233 assert!(path_plausibility.iter().all(|x| *x));
6237 fn builds_correct_path_from_hops() {
6238 let (secp_ctx, network, _, _, logger) = build_graph();
6239 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6240 let network_graph = network.read_only();
6242 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6243 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6245 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6246 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6247 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6248 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6249 Arc::clone(&logger), &random_seed_bytes).unwrap();
6250 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6251 assert_eq!(hops.len(), route.paths[0].hops.len());
6252 for (idx, hop_pubkey) in hops.iter().enumerate() {
6253 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6258 fn avoids_saturating_channels() {
6259 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6260 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6261 let decay_params = ProbabilisticScoringDecayParameters::default();
6262 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6264 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6265 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6266 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6267 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6268 short_channel_id: 4,
6271 cltv_expiry_delta: (4 << 4) | 1,
6272 htlc_minimum_msat: 0,
6273 htlc_maximum_msat: 250_000_000,
6275 fee_proportional_millionths: 0,
6276 excess_data: Vec::new()
6278 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6279 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6280 short_channel_id: 13,
6283 cltv_expiry_delta: (13 << 4) | 1,
6284 htlc_minimum_msat: 0,
6285 htlc_maximum_msat: 250_000_000,
6287 fee_proportional_millionths: 0,
6288 excess_data: Vec::new()
6291 let config = UserConfig::default();
6292 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6293 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6294 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6295 // 100,000 sats is less than the available liquidity on each channel, set above.
6296 let route_params = RouteParameters::from_payment_params_and_value(
6297 payment_params, 100_000_000);
6298 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6299 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6300 assert_eq!(route.paths.len(), 2);
6301 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6302 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6305 #[cfg(not(feature = "no-std"))]
6306 pub(super) fn random_init_seed() -> u64 {
6307 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6308 use core::hash::{BuildHasher, Hasher};
6309 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6310 println!("Using seed of {}", seed);
6315 #[cfg(not(feature = "no-std"))]
6316 fn generate_routes() {
6317 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6319 let logger = ln_test_utils::TestLogger::new();
6320 let graph = match super::bench_utils::read_network_graph(&logger) {
6328 let params = ProbabilisticScoringFeeParameters::default();
6329 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6330 let features = super::Bolt11InvoiceFeatures::empty();
6332 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6336 #[cfg(not(feature = "no-std"))]
6337 fn generate_routes_mpp() {
6338 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6340 let logger = ln_test_utils::TestLogger::new();
6341 let graph = match super::bench_utils::read_network_graph(&logger) {
6349 let params = ProbabilisticScoringFeeParameters::default();
6350 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6351 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6353 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6357 #[cfg(not(feature = "no-std"))]
6358 fn generate_large_mpp_routes() {
6359 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6361 let logger = ln_test_utils::TestLogger::new();
6362 let graph = match super::bench_utils::read_network_graph(&logger) {
6370 let params = ProbabilisticScoringFeeParameters::default();
6371 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6372 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6374 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6378 fn honors_manual_penalties() {
6379 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6380 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6382 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6383 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6385 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6386 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6388 // First check set manual penalties are returned by the scorer.
6389 let usage = ChannelUsage {
6391 inflight_htlc_msat: 0,
6392 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6394 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6395 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6396 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
6398 // Then check we can get a normal route
6399 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6400 let route_params = RouteParameters::from_payment_params_and_value(
6401 payment_params, 100);
6402 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6403 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6404 assert!(route.is_ok());
6406 // Then check that we can't get a route if we ban an intermediate node.
6407 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6408 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6409 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6410 assert!(route.is_err());
6412 // Finally make sure we can route again, when we remove the ban.
6413 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6414 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6415 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6416 assert!(route.is_ok());
6420 fn abide_by_route_hint_max_htlc() {
6421 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6422 // params in the final route.
6423 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6424 let netgraph = network_graph.read_only();
6425 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6426 let scorer = ln_test_utils::TestScorer::new();
6427 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6428 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6429 let config = UserConfig::default();
6431 let max_htlc_msat = 50_000;
6432 let route_hint_1 = RouteHint(vec![RouteHintHop {
6433 src_node_id: nodes[2],
6434 short_channel_id: 42,
6437 proportional_millionths: 0,
6439 cltv_expiry_delta: 10,
6440 htlc_minimum_msat: None,
6441 htlc_maximum_msat: Some(max_htlc_msat),
6443 let dest_node_id = ln_test_utils::pubkey(42);
6444 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6445 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6446 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6448 // Make sure we'll error if our route hints don't have enough liquidity according to their
6449 // htlc_maximum_msat.
6450 let route_params = RouteParameters::from_payment_params_and_value(
6451 payment_params, max_htlc_msat + 1);
6452 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6453 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &(),
6456 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6457 } else { panic!(); }
6459 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6460 let mut route_hint_2 = route_hint_1.clone();
6461 route_hint_2.0[0].short_channel_id = 43;
6462 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6463 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6464 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6465 let route_params = RouteParameters::from_payment_params_and_value(
6466 payment_params, max_htlc_msat + 1);
6467 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
6468 &scorer, &(), &random_seed_bytes).unwrap();
6469 assert_eq!(route.paths.len(), 2);
6470 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6471 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6475 fn direct_channel_to_hints_with_max_htlc() {
6476 // Check that if we have a first hop channel peer that's connected to multiple provided route
6477 // hints, that we properly split the payment between the route hints if needed.
6478 let logger = Arc::new(ln_test_utils::TestLogger::new());
6479 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6480 let scorer = ln_test_utils::TestScorer::new();
6481 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6482 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6483 let config = UserConfig::default();
6485 let our_node_id = ln_test_utils::pubkey(42);
6486 let intermed_node_id = ln_test_utils::pubkey(43);
6487 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6489 let amt_msat = 900_000;
6490 let max_htlc_msat = 500_000;
6491 let route_hint_1 = RouteHint(vec![RouteHintHop {
6492 src_node_id: intermed_node_id,
6493 short_channel_id: 44,
6496 proportional_millionths: 0,
6498 cltv_expiry_delta: 10,
6499 htlc_minimum_msat: None,
6500 htlc_maximum_msat: Some(max_htlc_msat),
6502 src_node_id: intermed_node_id,
6503 short_channel_id: 45,
6506 proportional_millionths: 0,
6508 cltv_expiry_delta: 10,
6509 htlc_minimum_msat: None,
6510 // Check that later route hint max htlcs don't override earlier ones
6511 htlc_maximum_msat: Some(max_htlc_msat - 50),
6513 let mut route_hint_2 = route_hint_1.clone();
6514 route_hint_2.0[0].short_channel_id = 46;
6515 route_hint_2.0[1].short_channel_id = 47;
6516 let dest_node_id = ln_test_utils::pubkey(44);
6517 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6518 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6519 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6521 let route_params = RouteParameters::from_payment_params_and_value(
6522 payment_params, amt_msat);
6523 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6524 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
6525 &random_seed_bytes).unwrap();
6526 assert_eq!(route.paths.len(), 2);
6527 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6528 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6529 assert_eq!(route.get_total_amount(), amt_msat);
6531 // Re-run but with two first hop channels connected to the same route hint peers that must be
6533 let first_hops = vec![
6534 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6535 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6537 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6538 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
6539 &random_seed_bytes).unwrap();
6540 assert_eq!(route.paths.len(), 2);
6541 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6542 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6543 assert_eq!(route.get_total_amount(), amt_msat);
6545 // Make sure this works for blinded route hints.
6546 let blinded_path = BlindedPath {
6547 introduction_node_id: intermed_node_id,
6548 blinding_point: ln_test_utils::pubkey(42),
6550 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6551 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6554 let blinded_payinfo = BlindedPayInfo {
6556 fee_proportional_millionths: 0,
6557 htlc_minimum_msat: 1,
6558 htlc_maximum_msat: max_htlc_msat,
6559 cltv_expiry_delta: 10,
6560 features: BlindedHopFeatures::empty(),
6562 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6563 let payment_params = PaymentParameters::blinded(vec![
6564 (blinded_payinfo.clone(), blinded_path.clone()),
6565 (blinded_payinfo.clone(), blinded_path.clone())])
6566 .with_bolt12_features(bolt12_features).unwrap();
6567 let route_params = RouteParameters::from_payment_params_and_value(
6568 payment_params, amt_msat);
6569 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6570 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
6571 &random_seed_bytes).unwrap();
6572 assert_eq!(route.paths.len(), 2);
6573 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6574 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6575 assert_eq!(route.get_total_amount(), amt_msat);
6579 fn blinded_route_ser() {
6580 let blinded_path_1 = BlindedPath {
6581 introduction_node_id: ln_test_utils::pubkey(42),
6582 blinding_point: ln_test_utils::pubkey(43),
6584 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6585 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6588 let blinded_path_2 = BlindedPath {
6589 introduction_node_id: ln_test_utils::pubkey(46),
6590 blinding_point: ln_test_utils::pubkey(47),
6592 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6593 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6596 // (De)serialize a Route with 1 blinded path out of two total paths.
6597 let mut route = Route { paths: vec![Path {
6598 hops: vec![RouteHop {
6599 pubkey: ln_test_utils::pubkey(50),
6600 node_features: NodeFeatures::empty(),
6601 short_channel_id: 42,
6602 channel_features: ChannelFeatures::empty(),
6604 cltv_expiry_delta: 0,
6606 blinded_tail: Some(BlindedTail {
6607 hops: blinded_path_1.blinded_hops,
6608 blinding_point: blinded_path_1.blinding_point,
6609 excess_final_cltv_expiry_delta: 40,
6610 final_value_msat: 100,
6612 hops: vec![RouteHop {
6613 pubkey: ln_test_utils::pubkey(51),
6614 node_features: NodeFeatures::empty(),
6615 short_channel_id: 43,
6616 channel_features: ChannelFeatures::empty(),
6618 cltv_expiry_delta: 0,
6619 }], blinded_tail: None }],
6622 let encoded_route = route.encode();
6623 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6624 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6625 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6627 // (De)serialize a Route with two paths, each containing a blinded tail.
6628 route.paths[1].blinded_tail = Some(BlindedTail {
6629 hops: blinded_path_2.blinded_hops,
6630 blinding_point: blinded_path_2.blinding_point,
6631 excess_final_cltv_expiry_delta: 41,
6632 final_value_msat: 101,
6634 let encoded_route = route.encode();
6635 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6636 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6637 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6641 fn blinded_path_inflight_processing() {
6642 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6643 // account for the blinded tail's final amount_msat.
6644 let mut inflight_htlcs = InFlightHtlcs::new();
6645 let blinded_path = BlindedPath {
6646 introduction_node_id: ln_test_utils::pubkey(43),
6647 blinding_point: ln_test_utils::pubkey(48),
6648 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
6651 hops: vec![RouteHop {
6652 pubkey: ln_test_utils::pubkey(42),
6653 node_features: NodeFeatures::empty(),
6654 short_channel_id: 42,
6655 channel_features: ChannelFeatures::empty(),
6657 cltv_expiry_delta: 0,
6660 pubkey: blinded_path.introduction_node_id,
6661 node_features: NodeFeatures::empty(),
6662 short_channel_id: 43,
6663 channel_features: ChannelFeatures::empty(),
6665 cltv_expiry_delta: 0,
6667 blinded_tail: Some(BlindedTail {
6668 hops: blinded_path.blinded_hops,
6669 blinding_point: blinded_path.blinding_point,
6670 excess_final_cltv_expiry_delta: 0,
6671 final_value_msat: 200,
6674 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
6675 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
6676 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
6680 fn blinded_path_cltv_shadow_offset() {
6681 // Make sure we add a shadow offset when sending to blinded paths.
6682 let blinded_path = BlindedPath {
6683 introduction_node_id: ln_test_utils::pubkey(43),
6684 blinding_point: ln_test_utils::pubkey(44),
6686 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
6687 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
6690 let mut route = Route { paths: vec![Path {
6691 hops: vec![RouteHop {
6692 pubkey: ln_test_utils::pubkey(42),
6693 node_features: NodeFeatures::empty(),
6694 short_channel_id: 42,
6695 channel_features: ChannelFeatures::empty(),
6697 cltv_expiry_delta: 0,
6700 pubkey: blinded_path.introduction_node_id,
6701 node_features: NodeFeatures::empty(),
6702 short_channel_id: 43,
6703 channel_features: ChannelFeatures::empty(),
6705 cltv_expiry_delta: 0,
6708 blinded_tail: Some(BlindedTail {
6709 hops: blinded_path.blinded_hops,
6710 blinding_point: blinded_path.blinding_point,
6711 excess_final_cltv_expiry_delta: 0,
6712 final_value_msat: 200,
6714 }], route_params: None};
6716 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
6717 let (_, network_graph, _, _, _) = build_line_graph();
6718 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
6719 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
6720 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
6724 fn simple_blinded_route_hints() {
6725 do_simple_blinded_route_hints(1);
6726 do_simple_blinded_route_hints(2);
6727 do_simple_blinded_route_hints(3);
6730 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
6731 // Check that we can generate a route to a blinded path with the expected hops.
6732 let (secp_ctx, network, _, _, logger) = build_graph();
6733 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6734 let network_graph = network.read_only();
6736 let scorer = ln_test_utils::TestScorer::new();
6737 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6738 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6740 let mut blinded_path = BlindedPath {
6741 introduction_node_id: nodes[2],
6742 blinding_point: ln_test_utils::pubkey(42),
6743 blinded_hops: Vec::with_capacity(num_blinded_hops),
6745 for i in 0..num_blinded_hops {
6746 blinded_path.blinded_hops.push(
6747 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
6750 let blinded_payinfo = BlindedPayInfo {
6752 fee_proportional_millionths: 500,
6753 htlc_minimum_msat: 1000,
6754 htlc_maximum_msat: 100_000_000,
6755 cltv_expiry_delta: 15,
6756 features: BlindedHopFeatures::empty(),
6759 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
6760 let route_params = RouteParameters::from_payment_params_and_value(
6761 payment_params, 1001);
6762 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6763 &scorer, &(), &random_seed_bytes).unwrap();
6764 assert_eq!(route.paths.len(), 1);
6765 assert_eq!(route.paths[0].hops.len(), 2);
6767 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
6768 assert_eq!(tail.hops, blinded_path.blinded_hops);
6769 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
6770 assert_eq!(tail.final_value_msat, 1001);
6772 let final_hop = route.paths[0].hops.last().unwrap();
6773 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
6774 if tail.hops.len() > 1 {
6775 assert_eq!(final_hop.fee_msat,
6776 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
6777 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
6779 assert_eq!(final_hop.fee_msat, 0);
6780 assert_eq!(final_hop.cltv_expiry_delta, 0);
6785 fn blinded_path_routing_errors() {
6786 // Check that we can generate a route to a blinded path with the expected hops.
6787 let (secp_ctx, network, _, _, logger) = build_graph();
6788 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6789 let network_graph = network.read_only();
6791 let scorer = ln_test_utils::TestScorer::new();
6792 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6793 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6795 let mut invalid_blinded_path = BlindedPath {
6796 introduction_node_id: nodes[2],
6797 blinding_point: ln_test_utils::pubkey(42),
6799 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
6802 let blinded_payinfo = BlindedPayInfo {
6804 fee_proportional_millionths: 500,
6805 htlc_minimum_msat: 1000,
6806 htlc_maximum_msat: 100_000_000,
6807 cltv_expiry_delta: 15,
6808 features: BlindedHopFeatures::empty(),
6811 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
6812 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
6813 let payment_params = PaymentParameters::blinded(vec![
6814 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
6815 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
6816 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6817 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6818 &scorer, &(), &random_seed_bytes)
6820 Err(LightningError { err, .. }) => {
6821 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
6823 _ => panic!("Expected error")
6826 invalid_blinded_path.introduction_node_id = our_id;
6827 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
6828 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6829 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6830 &(), &random_seed_bytes)
6832 Err(LightningError { err, .. }) => {
6833 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
6835 _ => panic!("Expected error")
6838 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
6839 invalid_blinded_path.blinded_hops.clear();
6840 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
6841 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6842 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6843 &(), &random_seed_bytes)
6845 Err(LightningError { err, .. }) => {
6846 assert_eq!(err, "0-hop blinded path provided");
6848 _ => panic!("Expected error")
6853 fn matching_intro_node_paths_provided() {
6854 // Check that if multiple blinded paths with the same intro node are provided in payment
6855 // parameters, we'll return the correct paths in the resulting MPP route.
6856 let (secp_ctx, network, _, _, logger) = build_graph();
6857 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6858 let network_graph = network.read_only();
6860 let scorer = ln_test_utils::TestScorer::new();
6861 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6862 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6863 let config = UserConfig::default();
6865 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6866 let blinded_path_1 = BlindedPath {
6867 introduction_node_id: nodes[2],
6868 blinding_point: ln_test_utils::pubkey(42),
6870 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6871 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6874 let blinded_payinfo_1 = BlindedPayInfo {
6876 fee_proportional_millionths: 0,
6877 htlc_minimum_msat: 0,
6878 htlc_maximum_msat: 30_000,
6879 cltv_expiry_delta: 0,
6880 features: BlindedHopFeatures::empty(),
6883 let mut blinded_path_2 = blinded_path_1.clone();
6884 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
6885 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
6886 blinded_payinfo_2.htlc_maximum_msat = 70_000;
6888 let blinded_hints = vec![
6889 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
6890 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
6892 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
6893 .with_bolt12_features(bolt12_features.clone()).unwrap();
6895 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
6896 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6897 &scorer, &(), &random_seed_bytes).unwrap();
6898 assert_eq!(route.paths.len(), 2);
6899 let mut total_amount_paid_msat = 0;
6900 for path in route.paths.into_iter() {
6901 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6902 if let Some(bt) = &path.blinded_tail {
6903 assert_eq!(bt.blinding_point,
6904 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
6905 .map(|(_, bp)| bp.blinding_point).unwrap());
6906 } else { panic!(); }
6907 total_amount_paid_msat += path.final_value_msat();
6909 assert_eq!(total_amount_paid_msat, 100_000);
6913 fn direct_to_intro_node() {
6914 // This previously caused a debug panic in the router when asserting
6915 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
6916 // direct channels we failed to account for the fee charged for use of the blinded path.
6919 // node0 -1(1)2 - node1
6920 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
6921 // doesn't account for the blinded path fee.
6923 let secp_ctx = Secp256k1::new();
6924 let logger = Arc::new(ln_test_utils::TestLogger::new());
6925 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6926 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
6927 let scorer = ln_test_utils::TestScorer::new();
6928 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6929 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6931 let amt_msat = 10_000_000;
6932 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
6933 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
6934 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6935 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6936 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6937 short_channel_id: 1,
6940 cltv_expiry_delta: 42,
6941 htlc_minimum_msat: 1_000,
6942 htlc_maximum_msat: 10_000_000,
6944 fee_proportional_millionths: 0,
6945 excess_data: Vec::new()
6947 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6948 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6949 short_channel_id: 1,
6952 cltv_expiry_delta: 42,
6953 htlc_minimum_msat: 1_000,
6954 htlc_maximum_msat: 10_000_000,
6956 fee_proportional_millionths: 0,
6957 excess_data: Vec::new()
6959 let first_hops = vec![
6960 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6962 let blinded_path = BlindedPath {
6963 introduction_node_id: nodes[1],
6964 blinding_point: ln_test_utils::pubkey(42),
6966 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6967 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6970 let blinded_payinfo = BlindedPayInfo {
6971 fee_base_msat: 1000,
6972 fee_proportional_millionths: 0,
6973 htlc_minimum_msat: 1000,
6974 htlc_maximum_msat: MAX_VALUE_MSAT,
6975 cltv_expiry_delta: 0,
6976 features: BlindedHopFeatures::empty(),
6978 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
6980 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
6982 let netgraph = network_graph.read_only();
6983 let route_params = RouteParameters::from_payment_params_and_value(
6984 payment_params.clone(), amt_msat);
6985 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
6986 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
6987 &random_seed_bytes) {
6988 assert_eq!(err, "Failed to find a path to the given destination");
6989 } else { panic!("Expected error") }
6991 // Sending an exact amount accounting for the blinded path fee works.
6992 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
6993 let route_params = RouteParameters::from_payment_params_and_value(
6994 payment_params, amt_minus_blinded_path_fee);
6995 let route = get_route(&nodes[0], &route_params, &netgraph,
6996 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
6997 &random_seed_bytes).unwrap();
6998 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
6999 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7003 fn direct_to_matching_intro_nodes() {
7004 // This previously caused us to enter `unreachable` code in the following situation:
7005 // 1. We add a route candidate for intro_node contributing a high amount
7006 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7007 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7008 // amount, and update our route candidate for intro_node for the lower amount
7009 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7010 // lower contribution amount, but fail (this was previously caused by failure to account for
7011 // blinded path fees when adding first_hop<>intro_node candidates)
7012 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7013 // candidate still thinks its path is contributing the original higher amount. This caused us
7014 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7016 let secp_ctx = Secp256k1::new();
7017 let logger = Arc::new(ln_test_utils::TestLogger::new());
7018 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7019 let scorer = ln_test_utils::TestScorer::new();
7020 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7021 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7022 let config = UserConfig::default();
7024 // Values are taken from the fuzz input that uncovered this panic.
7025 let amt_msat = 21_7020_5185_1403_2640;
7026 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7027 let first_hops = vec![
7028 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7029 18446744073709551615)];
7031 let blinded_path = BlindedPath {
7032 introduction_node_id: nodes[1],
7033 blinding_point: ln_test_utils::pubkey(42),
7035 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7036 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7039 let blinded_payinfo = BlindedPayInfo {
7040 fee_base_msat: 5046_2720,
7041 fee_proportional_millionths: 0,
7042 htlc_minimum_msat: 4503_5996_2737_0496,
7043 htlc_maximum_msat: 45_0359_9627_3704_9600,
7044 cltv_expiry_delta: 0,
7045 features: BlindedHopFeatures::empty(),
7047 let mut blinded_hints = vec![
7048 (blinded_payinfo.clone(), blinded_path.clone()),
7049 (blinded_payinfo.clone(), blinded_path.clone()),
7051 blinded_hints[1].0.fee_base_msat = 419_4304;
7052 blinded_hints[1].0.fee_proportional_millionths = 257;
7053 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7054 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7055 blinded_hints[1].0.cltv_expiry_delta = 0;
7057 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7058 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7059 .with_bolt12_features(bolt12_features.clone()).unwrap();
7061 let netgraph = network_graph.read_only();
7062 let route_params = RouteParameters::from_payment_params_and_value(
7063 payment_params, amt_msat);
7064 let route = get_route(&nodes[0], &route_params, &netgraph,
7065 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
7066 &random_seed_bytes).unwrap();
7067 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7068 assert_eq!(route.get_total_amount(), amt_msat);
7072 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
7073 pub(crate) mod bench_utils {
7077 use bitcoin::hashes::Hash;
7078 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
7080 use crate::chain::transaction::OutPoint;
7081 use crate::routing::scoring::ScoreUpdate;
7082 use crate::sign::{EntropySource, KeysManager};
7083 use crate::ln::ChannelId;
7084 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
7085 use crate::ln::features::Bolt11InvoiceFeatures;
7086 use crate::routing::gossip::NetworkGraph;
7087 use crate::util::config::UserConfig;
7088 use crate::util::ser::ReadableArgs;
7089 use crate::util::test_utils::TestLogger;
7091 /// Tries to open a network graph file, or panics with a URL to fetch it.
7092 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
7093 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
7094 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
7095 .or_else(|_| { // Fall back to guessing based on the binary location
7096 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
7097 let mut path = std::env::current_exe().unwrap();
7098 path.pop(); // lightning-...
7100 path.pop(); // debug
7101 path.pop(); // target
7102 path.push("lightning");
7103 path.push("net_graph-2023-01-18.bin");
7106 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
7107 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
7108 let mut path = std::env::current_exe().unwrap();
7109 path.pop(); // bench...
7111 path.pop(); // debug
7112 path.pop(); // target
7113 path.pop(); // bench
7114 path.push("lightning");
7115 path.push("net_graph-2023-01-18.bin");
7118 .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");
7119 #[cfg(require_route_graph_test)]
7120 return Ok(res.unwrap());
7121 #[cfg(not(require_route_graph_test))]
7125 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
7126 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
7129 pub(crate) fn payer_pubkey() -> PublicKey {
7130 let secp_ctx = Secp256k1::new();
7131 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
7135 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
7137 channel_id: ChannelId::new_zero(),
7138 counterparty: ChannelCounterparty {
7139 features: channelmanager::provided_init_features(&UserConfig::default()),
7141 unspendable_punishment_reserve: 0,
7142 forwarding_info: None,
7143 outbound_htlc_minimum_msat: None,
7144 outbound_htlc_maximum_msat: None,
7146 funding_txo: Some(OutPoint {
7147 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
7150 short_channel_id: Some(1),
7151 inbound_scid_alias: None,
7152 outbound_scid_alias: None,
7153 channel_value_satoshis: 10_000_000_000,
7155 outbound_capacity_msat: 10_000_000_000,
7156 next_outbound_htlc_minimum_msat: 0,
7157 next_outbound_htlc_limit_msat: 10_000_000_000,
7158 inbound_capacity_msat: 0,
7159 unspendable_punishment_reserve: None,
7160 confirmations_required: None,
7161 confirmations: None,
7162 force_close_spend_delay: None,
7164 is_channel_ready: true,
7167 inbound_htlc_minimum_msat: None,
7168 inbound_htlc_maximum_msat: None,
7170 feerate_sat_per_1000_weight: None,
7171 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
7175 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
7176 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
7177 starting_amount: u64, route_count: usize,
7178 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
7179 let payer = payer_pubkey();
7180 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7181 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7183 let nodes = graph.read_only().nodes().clone();
7184 let mut route_endpoints = Vec::new();
7185 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
7186 // with some routes we picked being un-routable.
7187 for _ in 0..route_count * 3 / 2 {
7189 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7190 let src = PublicKey::from_slice(nodes.unordered_keys()
7191 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
7192 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7193 let dst = PublicKey::from_slice(nodes.unordered_keys()
7194 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
7195 let params = PaymentParameters::from_node_id(dst, 42)
7196 .with_bolt11_features(features.clone()).unwrap();
7197 let first_hop = first_hop(src);
7198 let amt_msat = starting_amount + seed % 1_000_000;
7199 let route_params = RouteParameters::from_payment_params_and_value(
7200 params.clone(), amt_msat);
7202 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
7203 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
7205 // ...and seed the scorer with success and failure data...
7206 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7207 let mut score_amt = seed % 1_000_000_000;
7209 // Generate fail/success paths for a wider range of potential amounts with
7210 // MPP enabled to give us a chance to apply penalties for more potential
7212 let mpp_features = channelmanager::provided_invoice_features(&UserConfig::default());
7213 let params = PaymentParameters::from_node_id(dst, 42)
7214 .with_bolt11_features(mpp_features).unwrap();
7215 let route_params = RouteParameters::from_payment_params_and_value(
7216 params.clone(), score_amt);
7217 let route_res = get_route(&payer, &route_params, &graph.read_only(),
7218 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
7219 &random_seed_bytes);
7220 if let Ok(route) = route_res {
7221 for path in route.paths {
7222 if seed & 0x80 == 0 {
7223 scorer.payment_path_successful(&path);
7225 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
7226 scorer.payment_path_failed(&path, short_channel_id);
7228 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7232 // If we couldn't find a path with a higer amount, reduce and try again.
7236 route_endpoints.push((first_hop, params, amt_msat));
7242 // Because we've changed channel scores, it's possible we'll take different routes to the
7243 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
7244 // requires a too-high CLTV delta.
7245 route_endpoints.retain(|(first_hop, params, amt_msat)| {
7246 let route_params = RouteParameters::from_payment_params_and_value(
7247 params.clone(), *amt_msat);
7248 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
7249 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
7251 route_endpoints.truncate(route_count);
7252 assert_eq!(route_endpoints.len(), route_count);
7260 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
7261 use crate::sign::{EntropySource, KeysManager};
7262 use crate::ln::channelmanager;
7263 use crate::ln::features::Bolt11InvoiceFeatures;
7264 use crate::routing::gossip::NetworkGraph;
7265 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
7266 use crate::util::config::UserConfig;
7267 use crate::util::logger::{Logger, Record};
7268 use crate::util::test_utils::TestLogger;
7270 use criterion::Criterion;
7272 struct DummyLogger {}
7273 impl Logger for DummyLogger {
7274 fn log(&self, _record: &Record) {}
7277 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7278 let logger = TestLogger::new();
7279 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7280 let scorer = FixedPenaltyScorer::with_penalty(0);
7281 generate_routes(bench, &network_graph, scorer, &(), Bolt11InvoiceFeatures::empty(), 0,
7282 "generate_routes_with_zero_penalty_scorer");
7285 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7286 let logger = TestLogger::new();
7287 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7288 let scorer = FixedPenaltyScorer::with_penalty(0);
7289 generate_routes(bench, &network_graph, scorer, &(),
7290 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7291 "generate_mpp_routes_with_zero_penalty_scorer");
7294 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7295 let logger = TestLogger::new();
7296 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7297 let params = ProbabilisticScoringFeeParameters::default();
7298 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7299 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
7300 "generate_routes_with_probabilistic_scorer");
7303 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7304 let logger = TestLogger::new();
7305 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7306 let params = ProbabilisticScoringFeeParameters::default();
7307 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7308 generate_routes(bench, &network_graph, scorer, ¶ms,
7309 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7310 "generate_mpp_routes_with_probabilistic_scorer");
7313 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7314 let logger = TestLogger::new();
7315 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7316 let params = ProbabilisticScoringFeeParameters::default();
7317 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7318 generate_routes(bench, &network_graph, scorer, ¶ms,
7319 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
7320 "generate_large_mpp_routes_with_probabilistic_scorer");
7323 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
7324 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
7325 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
7326 bench_name: &'static str,
7328 let payer = bench_utils::payer_pubkey();
7329 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7330 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7332 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
7333 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
7335 // ...then benchmark finding paths between the nodes we learned.
7337 bench.bench_function(bench_name, |b| b.iter(|| {
7338 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
7339 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
7340 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
7341 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());