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,
253 /// Indicates whether this hop is possibly announced in the public network graph.
255 /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
256 /// either know for sure it's announced in the public graph, or if any public channels exist
257 /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
258 /// the channel to be unannounced.
260 /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
261 pub maybe_announced_channel: bool,
264 impl_writeable_tlv_based!(RouteHop, {
265 (0, pubkey, required),
266 (1, maybe_announced_channel, (default_value, true)),
267 (2, node_features, required),
268 (4, short_channel_id, required),
269 (6, channel_features, required),
270 (8, fee_msat, required),
271 (10, cltv_expiry_delta, required),
274 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
275 /// their [`Bolt12Invoice`].
277 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
278 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
279 pub struct BlindedTail {
280 /// The hops of the [`BlindedPath`] provided by the recipient.
282 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
283 pub hops: Vec<BlindedHop>,
284 /// The blinding point of the [`BlindedPath`] provided by the recipient.
286 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
287 pub blinding_point: PublicKey,
288 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
289 /// inferring the destination. May be 0.
290 pub excess_final_cltv_expiry_delta: u32,
291 /// The total amount paid on this [`Path`], excluding the fees.
292 pub final_value_msat: u64,
295 impl_writeable_tlv_based!(BlindedTail, {
296 (0, hops, required_vec),
297 (2, blinding_point, required),
298 (4, excess_final_cltv_expiry_delta, required),
299 (6, final_value_msat, required),
302 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
303 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
304 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
306 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
307 pub hops: Vec<RouteHop>,
308 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
309 pub blinded_tail: Option<BlindedTail>,
313 /// Gets the fees for a given path, excluding any excess paid to the recipient.
314 pub fn fee_msat(&self) -> u64 {
315 match &self.blinded_tail {
316 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
318 // Do not count last hop of each path since that's the full value of the payment
319 self.hops.split_last().map_or(0,
320 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
325 /// Gets the total amount paid on this [`Path`], excluding the fees.
326 pub fn final_value_msat(&self) -> u64 {
327 match &self.blinded_tail {
328 Some(blinded_tail) => blinded_tail.final_value_msat,
329 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
333 /// Gets the final hop's CLTV expiry delta.
334 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
335 match &self.blinded_tail {
337 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
342 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
343 /// it can take multiple paths. Each path is composed of one or more hops through the network.
344 #[derive(Clone, Hash, PartialEq, Eq)]
346 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
347 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
349 pub paths: Vec<Path>,
350 /// The `route_params` parameter passed to [`find_route`].
352 /// This is used by `ChannelManager` to track information which may be required for retries.
354 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
355 pub route_params: Option<RouteParameters>,
359 /// Returns the total amount of fees paid on this [`Route`].
361 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
362 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
363 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
365 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
366 pub fn get_total_fees(&self) -> u64 {
367 let overpaid_value_msat = self.route_params.as_ref()
368 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
369 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
372 /// Returns the total amount paid on this [`Route`], excluding the fees.
374 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
375 /// we had to reach the [`htlc_minimum_msat`] limits.
377 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
378 pub fn get_total_amount(&self) -> u64 {
379 self.paths.iter().map(|path| path.final_value_msat()).sum()
383 const SERIALIZATION_VERSION: u8 = 1;
384 const MIN_SERIALIZATION_VERSION: u8 = 1;
386 impl Writeable for Route {
387 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
388 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
389 (self.paths.len() as u64).write(writer)?;
390 let mut blinded_tails = Vec::new();
391 for path in self.paths.iter() {
392 (path.hops.len() as u8).write(writer)?;
393 for (idx, hop) in path.hops.iter().enumerate() {
395 if let Some(blinded_tail) = &path.blinded_tail {
396 if blinded_tails.is_empty() {
397 blinded_tails = Vec::with_capacity(path.hops.len());
399 blinded_tails.push(None);
402 blinded_tails.push(Some(blinded_tail));
403 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
406 write_tlv_fields!(writer, {
407 // For compatibility with LDK versions prior to 0.0.117, we take the individual
408 // RouteParameters' fields and reconstruct them on read.
409 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
410 (2, blinded_tails, optional_vec),
411 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
417 impl Readable for Route {
418 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
419 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
420 let path_count: u64 = Readable::read(reader)?;
421 if path_count == 0 { return Err(DecodeError::InvalidValue); }
422 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
423 let mut min_final_cltv_expiry_delta = u32::max_value();
424 for _ in 0..path_count {
425 let hop_count: u8 = Readable::read(reader)?;
426 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
427 for _ in 0..hop_count {
428 hops.push(Readable::read(reader)?);
430 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
431 min_final_cltv_expiry_delta =
432 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
433 paths.push(Path { hops, blinded_tail: None });
435 _init_and_read_len_prefixed_tlv_fields!(reader, {
436 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
437 (2, blinded_tails, optional_vec),
438 (3, final_value_msat, option),
440 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
441 if blinded_tails.len() != 0 {
442 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
443 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
444 path.blinded_tail = blinded_tail_opt;
448 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
449 let route_params = match (payment_params, final_value_msat) {
450 (Some(payment_params), Some(final_value_msat)) => {
451 Some(RouteParameters { payment_params, final_value_msat })
456 Ok(Route { paths, route_params })
460 /// Parameters needed to find a [`Route`].
462 /// Passed to [`find_route`] and [`build_route_from_hops`].
463 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
464 pub struct RouteParameters {
465 /// The parameters of the failed payment path.
466 pub payment_params: PaymentParameters,
468 /// The amount in msats sent on the failed payment path.
469 pub final_value_msat: u64,
472 impl RouteParameters {
473 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
474 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
475 Self { payment_params, final_value_msat }
479 impl Writeable for RouteParameters {
480 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
481 write_tlv_fields!(writer, {
482 (0, self.payment_params, required),
483 (2, self.final_value_msat, required),
484 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
485 // `RouteParameters` directly. For compatibility, we write it here.
486 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
492 impl Readable for RouteParameters {
493 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
494 _init_and_read_len_prefixed_tlv_fields!(reader, {
495 (0, payment_params, (required: ReadableArgs, 0)),
496 (2, final_value_msat, required),
497 (4, final_cltv_delta, option),
499 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
500 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
501 if final_cltv_expiry_delta == &0 {
502 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
507 final_value_msat: final_value_msat.0.unwrap(),
512 /// Maximum total CTLV difference we allow for a full payment path.
513 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
515 /// Maximum number of paths we allow an (MPP) payment to have.
516 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
517 // limits, but for now more than 10 paths likely carries too much one-path failure.
518 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
520 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
522 // The median hop CLTV expiry delta currently seen in the network.
523 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
525 // During routing, we only consider paths shorter than our maximum length estimate.
526 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
527 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
528 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
530 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
531 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
532 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
533 // (payment_secret and total_msat) = 93 bytes for the final hop.
534 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
535 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
536 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
538 /// Information used to route a payment.
539 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
540 pub struct PaymentParameters {
541 /// Information about the payee, such as their features and route hints for their channels.
544 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
545 pub expiry_time: Option<u64>,
547 /// The maximum total CLTV delta we accept for the route.
548 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
549 pub max_total_cltv_expiry_delta: u32,
551 /// The maximum number of paths that may be used by (MPP) payments.
552 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
553 pub max_path_count: u8,
555 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
556 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
557 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
558 /// increasing failure probability for those paths.
560 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
561 /// restriction have been found. While paths which meet this criteria will be searched for, it
562 /// is ultimately up to the scorer to select them over other paths.
564 /// A value of 0 will allow payments up to and including a channel's total announced usable
565 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
568 pub max_channel_saturation_power_of_half: u8,
570 /// A list of SCIDs which this payment was previously attempted over and which caused the
571 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
573 pub previously_failed_channels: Vec<u64>,
576 impl Writeable for PaymentParameters {
577 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
578 let mut clear_hints = &vec![];
579 let mut blinded_hints = &vec![];
581 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
582 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
584 write_tlv_fields!(writer, {
585 (0, self.payee.node_id(), option),
586 (1, self.max_total_cltv_expiry_delta, required),
587 (2, self.payee.features(), option),
588 (3, self.max_path_count, required),
589 (4, *clear_hints, required_vec),
590 (5, self.max_channel_saturation_power_of_half, required),
591 (6, self.expiry_time, option),
592 (7, self.previously_failed_channels, required_vec),
593 (8, *blinded_hints, optional_vec),
594 (9, self.payee.final_cltv_expiry_delta(), option),
600 impl ReadableArgs<u32> for PaymentParameters {
601 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
602 _init_and_read_len_prefixed_tlv_fields!(reader, {
603 (0, payee_pubkey, option),
604 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
605 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
606 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
607 (4, clear_route_hints, required_vec),
608 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
609 (6, expiry_time, option),
610 (7, previously_failed_channels, optional_vec),
611 (8, blinded_route_hints, optional_vec),
612 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
614 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
615 let payee = if blinded_route_hints.len() != 0 {
616 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
618 route_hints: blinded_route_hints,
619 features: features.and_then(|f: Features| f.bolt12()),
623 route_hints: clear_route_hints,
624 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
625 features: features.and_then(|f| f.bolt11()),
626 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
630 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
631 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
633 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
635 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
641 impl PaymentParameters {
642 /// Creates a payee with the node id of the given `pubkey`.
644 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
646 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
648 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
650 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
651 max_path_count: DEFAULT_MAX_PATH_COUNT,
652 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
653 previously_failed_channels: Vec::new(),
657 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
659 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
662 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
663 /// whether your router will be allowed to find a multi-part route for this payment. If you
664 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
665 /// [`RecipientOnionFields::secret_only`].
667 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
668 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
669 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
670 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
671 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
674 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
675 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
676 /// [`PaymentParameters::expiry_time`].
677 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
678 Self::blinded(invoice.payment_paths().to_vec())
679 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
680 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
683 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
684 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
686 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
688 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
689 max_path_count: DEFAULT_MAX_PATH_COUNT,
690 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
691 previously_failed_channels: Vec::new(),
695 /// Includes the payee's features. Errors if the parameters were not initialized with
696 /// [`PaymentParameters::from_bolt12_invoice`].
698 /// This is not exported to bindings users since bindings don't support move semantics
699 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
701 Payee::Clear { .. } => Err(()),
702 Payee::Blinded { route_hints, .. } =>
703 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
707 /// Includes the payee's features. Errors if the parameters were initialized with
708 /// [`PaymentParameters::from_bolt12_invoice`].
710 /// This is not exported to bindings users since bindings don't support move semantics
711 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
713 Payee::Blinded { .. } => Err(()),
714 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
716 payee: Payee::Clear {
717 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
723 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
724 /// [`PaymentParameters::from_bolt12_invoice`].
726 /// This is not exported to bindings users since bindings don't support move semantics
727 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
729 Payee::Blinded { .. } => Err(()),
730 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
732 payee: Payee::Clear {
733 route_hints, node_id, features, final_cltv_expiry_delta,
739 /// Includes a payment expiration in seconds relative to the UNIX epoch.
741 /// This is not exported to bindings users since bindings don't support move semantics
742 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
743 Self { expiry_time: Some(expiry_time), ..self }
746 /// Includes a limit for the total CLTV expiry delta which is considered during routing
748 /// This is not exported to bindings users since bindings don't support move semantics
749 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
750 Self { max_total_cltv_expiry_delta, ..self }
753 /// Includes a limit for the maximum number of payment paths that may be used.
755 /// This is not exported to bindings users since bindings don't support move semantics
756 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
757 Self { max_path_count, ..self }
760 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
761 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
763 /// This is not exported to bindings users since bindings don't support move semantics
764 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
765 Self { max_channel_saturation_power_of_half, ..self }
769 /// The recipient of a payment, differing based on whether they've hidden their identity with route
771 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
773 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
774 /// will be included in the final [`Route`].
776 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
778 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
779 /// Features supported by the payee.
781 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
783 features: Option<Bolt12InvoiceFeatures>,
785 /// The recipient included these route hints in their BOLT11 invoice.
787 /// The node id of the payee.
789 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
790 route_hints: Vec<RouteHint>,
791 /// Features supported by the payee.
793 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
794 /// does not contain any features.
796 /// [`for_keysend`]: PaymentParameters::for_keysend
797 features: Option<Bolt11InvoiceFeatures>,
798 /// The minimum CLTV delta at the end of the route. This value must not be zero.
799 final_cltv_expiry_delta: u32,
804 fn node_id(&self) -> Option<PublicKey> {
806 Self::Clear { node_id, .. } => Some(*node_id),
810 fn node_features(&self) -> Option<NodeFeatures> {
812 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
813 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
816 fn supports_basic_mpp(&self) -> bool {
818 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
819 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
822 fn features(&self) -> Option<FeaturesRef> {
824 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
825 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
828 fn final_cltv_expiry_delta(&self) -> Option<u32> {
830 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
834 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
836 Self::Blinded { route_hints, .. } => &route_hints[..],
837 Self::Clear { .. } => &[]
841 fn unblinded_route_hints(&self) -> &[RouteHint] {
843 Self::Blinded { .. } => &[],
844 Self::Clear { route_hints, .. } => &route_hints[..]
849 enum FeaturesRef<'a> {
850 Bolt11(&'a Bolt11InvoiceFeatures),
851 Bolt12(&'a Bolt12InvoiceFeatures),
854 Bolt11(Bolt11InvoiceFeatures),
855 Bolt12(Bolt12InvoiceFeatures),
859 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
861 Self::Bolt12(f) => Some(f),
865 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
867 Self::Bolt11(f) => Some(f),
873 impl<'a> Writeable for FeaturesRef<'a> {
874 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
876 Self::Bolt11(f) => Ok(f.write(w)?),
877 Self::Bolt12(f) => Ok(f.write(w)?),
882 impl ReadableArgs<bool> for Features {
883 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
884 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
885 Ok(Self::Bolt12(Readable::read(reader)?))
889 /// A list of hops along a payment path terminating with a channel to the recipient.
890 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
891 pub struct RouteHint(pub Vec<RouteHintHop>);
893 impl Writeable for RouteHint {
894 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
895 (self.0.len() as u64).write(writer)?;
896 for hop in self.0.iter() {
903 impl Readable for RouteHint {
904 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
905 let hop_count: u64 = Readable::read(reader)?;
906 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
907 for _ in 0..hop_count {
908 hops.push(Readable::read(reader)?);
914 /// A channel descriptor for a hop along a payment path.
915 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
916 pub struct RouteHintHop {
917 /// The node_id of the non-target end of the route
918 pub src_node_id: PublicKey,
919 /// The short_channel_id of this channel
920 pub short_channel_id: u64,
921 /// The fees which must be paid to use this channel
922 pub fees: RoutingFees,
923 /// The difference in CLTV values between this node and the next node.
924 pub cltv_expiry_delta: u16,
925 /// The minimum value, in msat, which must be relayed to the next hop.
926 pub htlc_minimum_msat: Option<u64>,
927 /// The maximum value in msat available for routing with a single HTLC.
928 pub htlc_maximum_msat: Option<u64>,
931 impl_writeable_tlv_based!(RouteHintHop, {
932 (0, src_node_id, required),
933 (1, htlc_minimum_msat, option),
934 (2, short_channel_id, required),
935 (3, htlc_maximum_msat, option),
937 (6, cltv_expiry_delta, required),
940 #[derive(Eq, PartialEq)]
941 struct RouteGraphNode {
943 lowest_fee_to_node: u64,
944 total_cltv_delta: u32,
945 // The maximum value a yet-to-be-constructed payment path might flow through this node.
946 // This value is upper-bounded by us by:
947 // - how much is needed for a path being constructed
948 // - how much value can channels following this node (up to the destination) can contribute,
949 // considering their capacity and fees
950 value_contribution_msat: u64,
951 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
952 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
953 path_htlc_minimum_msat: u64,
954 /// All penalties incurred from this hop on the way to the destination, as calculated using
956 path_penalty_msat: u64,
957 /// The number of hops walked up to this node.
958 path_length_to_node: u8,
961 impl cmp::Ord for RouteGraphNode {
962 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
963 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
964 .saturating_add(other.path_penalty_msat);
965 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
966 .saturating_add(self.path_penalty_msat);
967 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
971 impl cmp::PartialOrd for RouteGraphNode {
972 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
973 Some(self.cmp(other))
977 /// A wrapper around the various hop representations.
979 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
980 #[derive(Clone, Debug)]
981 enum CandidateRouteHop<'a> {
982 /// A hop from the payer, where the outbound liquidity is known.
984 details: &'a ChannelDetails,
986 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
988 info: DirectedChannelInfo<'a>,
989 short_channel_id: u64,
991 /// A hop to the payee found in the BOLT 11 payment invoice, though not necessarily a direct
994 hint: &'a RouteHintHop,
996 /// The payee's identity is concealed behind blinded paths provided in a BOLT 12 invoice.
998 hint: &'a (BlindedPayInfo, BlindedPath),
1001 /// Similar to [`Self::Blinded`], but the path here has 1 blinded hop. `BlindedPayInfo` provided
1002 /// for 1-hop blinded paths is ignored because it is meant to apply to the hops *between* the
1003 /// introduction node and the destination. Useful for tracking that we need to include a blinded
1004 /// path at the end of our [`Route`].
1006 hint: &'a (BlindedPayInfo, BlindedPath),
1011 impl<'a> CandidateRouteHop<'a> {
1012 fn short_channel_id(&self) -> Option<u64> {
1014 CandidateRouteHop::FirstHop { details } => Some(details.get_outbound_payment_scid().unwrap()),
1015 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
1016 CandidateRouteHop::PrivateHop { hint } => Some(hint.short_channel_id),
1017 CandidateRouteHop::Blinded { .. } => None,
1018 CandidateRouteHop::OneHopBlinded { .. } => None,
1022 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1023 fn features(&self) -> ChannelFeatures {
1025 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
1026 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
1027 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
1028 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
1029 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
1033 fn cltv_expiry_delta(&self) -> u32 {
1035 CandidateRouteHop::FirstHop { .. } => 0,
1036 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1037 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
1038 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1039 CandidateRouteHop::OneHopBlinded { .. } => 0,
1043 fn htlc_minimum_msat(&self) -> u64 {
1045 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_minimum_msat,
1046 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1047 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
1048 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1049 CandidateRouteHop::OneHopBlinded { .. } => 0,
1053 fn fees(&self) -> RoutingFees {
1055 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1056 base_msat: 0, proportional_millionths: 0,
1058 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1059 CandidateRouteHop::PrivateHop { hint } => hint.fees,
1060 CandidateRouteHop::Blinded { hint, .. } => {
1062 base_msat: hint.0.fee_base_msat,
1063 proportional_millionths: hint.0.fee_proportional_millionths
1066 CandidateRouteHop::OneHopBlinded { .. } =>
1067 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1071 fn effective_capacity(&self) -> EffectiveCapacity {
1073 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
1074 liquidity_msat: details.next_outbound_htlc_limit_msat,
1076 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1077 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }} =>
1078 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1079 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }} =>
1080 EffectiveCapacity::Infinite,
1081 CandidateRouteHop::Blinded { hint, .. } =>
1082 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1083 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1087 fn id(&self, channel_direction: bool /* src_node_id < target_node_id */) -> CandidateHopId {
1089 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1090 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1091 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), channel_direction)),
1094 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1096 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1104 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1105 enum CandidateHopId {
1106 /// Contains (scid, src_node_id < target_node_id)
1108 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1113 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1114 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1116 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1117 EffectiveCapacity::Infinite => u64::max_value(),
1118 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1119 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1120 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1121 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1122 // expected to have been generated from up-to-date capacity information.
1123 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1124 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1125 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1129 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1130 -> bool where I1::Item: PartialEq<I2::Item> {
1132 let a = iter_a.next();
1133 let b = iter_b.next();
1134 if a.is_none() && b.is_none() { return true; }
1135 if a.is_none() || b.is_none() { return false; }
1136 if a.unwrap().ne(&b.unwrap()) { return false; }
1140 /// It's useful to keep track of the hops associated with the fees required to use them,
1141 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1142 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1143 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1145 struct PathBuildingHop<'a> {
1146 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
1147 // is a larger refactor and will require careful performance analysis.
1149 candidate: CandidateRouteHop<'a>,
1152 /// All the fees paid *after* this channel on the way to the destination
1153 next_hops_fee_msat: u64,
1154 /// Fee paid for the use of the current channel (see candidate.fees()).
1155 /// The value will be actually deducted from the counterparty balance on the previous link.
1156 hop_use_fee_msat: u64,
1157 /// Used to compare channels when choosing the for routing.
1158 /// Includes paying for the use of a hop and the following hops, as well as
1159 /// an estimated cost of reaching this hop.
1160 /// Might get stale when fees are recomputed. Primarily for internal use.
1161 total_fee_msat: u64,
1162 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1163 /// walk and may be invalid thereafter.
1164 path_htlc_minimum_msat: u64,
1165 /// All penalties incurred from this channel on the way to the destination, as calculated using
1166 /// channel scoring.
1167 path_penalty_msat: u64,
1168 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1169 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1170 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1171 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1172 /// avoid processing them again.
1173 was_processed: bool,
1174 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1175 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1176 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1177 // value_contribution_msat, which requires tracking it here. See comments below where it is
1178 // used for more info.
1179 value_contribution_msat: u64,
1182 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1183 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1184 let mut debug_struct = f.debug_struct("PathBuildingHop");
1186 .field("node_id", &self.node_id)
1187 .field("short_channel_id", &self.candidate.short_channel_id())
1188 .field("total_fee_msat", &self.total_fee_msat)
1189 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1190 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1191 .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)))
1192 .field("path_penalty_msat", &self.path_penalty_msat)
1193 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1194 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1195 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1196 let debug_struct = debug_struct
1197 .field("value_contribution_msat", &self.value_contribution_msat);
1198 debug_struct.finish()
1202 // Instantiated with a list of hops with correct data in them collected during path finding,
1203 // an instance of this struct should be further modified only via given methods.
1205 struct PaymentPath<'a> {
1206 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1209 impl<'a> PaymentPath<'a> {
1210 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1211 fn get_value_msat(&self) -> u64 {
1212 self.hops.last().unwrap().0.fee_msat
1215 fn get_path_penalty_msat(&self) -> u64 {
1216 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1219 fn get_total_fee_paid_msat(&self) -> u64 {
1220 if self.hops.len() < 1 {
1224 // Can't use next_hops_fee_msat because it gets outdated.
1225 for (i, (hop, _)) in self.hops.iter().enumerate() {
1226 if i != self.hops.len() - 1 {
1227 result += hop.fee_msat;
1233 fn get_cost_msat(&self) -> u64 {
1234 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1237 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1238 // to change fees may result in an inconsistency.
1240 // Sometimes we call this function right after constructing a path which is inconsistent in
1241 // that it the value being transferred has decreased while we were doing path finding, leading
1242 // to the fees being paid not lining up with the actual limits.
1244 // Note that this function is not aware of the available_liquidity limit, and thus does not
1245 // support increasing the value being transferred beyond what was selected during the initial
1247 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
1248 let mut total_fee_paid_msat = 0 as u64;
1249 for i in (0..self.hops.len()).rev() {
1250 let last_hop = i == self.hops.len() - 1;
1252 // For non-last-hop, this value will represent the fees paid on the current hop. It
1253 // will consist of the fees for the use of the next hop, and extra fees to match
1254 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1255 let mut cur_hop_fees_msat = 0;
1257 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1260 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1261 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1262 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1263 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1264 // set it too high just to maliciously take more fees by exploiting this
1265 // match htlc_minimum_msat logic.
1266 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1267 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1268 // Note that there is a risk that *previous hops* (those closer to us, as we go
1269 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1271 // This might make us end up with a broken route, although this should be super-rare
1272 // in practice, both because of how healthy channels look like, and how we pick
1273 // channels in add_entry.
1274 // Also, this can't be exploited more heavily than *announce a free path and fail
1276 cur_hop_transferred_amount_msat += extra_fees_msat;
1277 total_fee_paid_msat += extra_fees_msat;
1278 cur_hop_fees_msat += extra_fees_msat;
1282 // Final hop is a special case: it usually has just value_msat (by design), but also
1283 // it still could overpay for the htlc_minimum_msat.
1284 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1286 // Propagate updated fees for the use of the channels to one hop back, where they
1287 // will be actually paid (fee_msat). The last hop is handled above separately.
1288 cur_hop.fee_msat = cur_hop_fees_msat;
1291 // Fee for the use of the current hop which will be deducted on the previous hop.
1292 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1293 // this channel is free for us.
1295 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1296 cur_hop.hop_use_fee_msat = new_fee;
1297 total_fee_paid_msat += new_fee;
1299 // It should not be possible because this function is called only to reduce the
1300 // value. In that case, compute_fee was already called with the same fees for
1301 // larger amount and there was no overflow.
1310 /// Calculate the fees required to route the given amount over a channel with the given fees.
1311 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1312 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1313 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1317 /// Calculate the fees required to route the given amount over a channel with the given fees,
1318 /// saturating to [`u64::max_value`].
1319 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1320 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1321 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1322 .saturating_add(channel_fees.base_msat as u64)
1325 /// The default `features` we assume for a node in a route, when no `features` are known about that
1328 /// Default features are:
1329 /// * variable_length_onion_optional
1330 fn default_node_features() -> NodeFeatures {
1331 let mut features = NodeFeatures::empty();
1332 features.set_variable_length_onion_optional();
1336 struct LoggedPayeePubkey(Option<PublicKey>);
1337 impl fmt::Display for LoggedPayeePubkey {
1338 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1341 "payee node id ".fmt(f)?;
1345 "blinded payee".fmt(f)
1351 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1352 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1353 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1355 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1356 "blinded route hint with introduction node id ".fmt(f)?;
1357 hint.1.introduction_node_id.fmt(f)?;
1358 " and blinding point ".fmt(f)?;
1359 hint.1.blinding_point.fmt(f)
1361 CandidateRouteHop::FirstHop { .. } => {
1362 "first hop with SCID ".fmt(f)?;
1363 self.0.short_channel_id().unwrap().fmt(f)
1365 CandidateRouteHop::PrivateHop { .. } => {
1366 "route hint with SCID ".fmt(f)?;
1367 self.0.short_channel_id().unwrap().fmt(f)
1371 self.0.short_channel_id().unwrap().fmt(f)
1378 fn sort_first_hop_channels(
1379 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1380 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1382 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1383 // most like to use.
1385 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1386 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1389 // Second, because simply always sorting in descending order would always use our largest
1390 // available outbound capacity, needlessly fragmenting our available channel capacities,
1391 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1392 // which have enough, but not too much, capacity for the payment.
1394 // Available outbound balances factor in liquidity already reserved for previously found paths.
1395 channels.sort_unstable_by(|chan_a, chan_b| {
1396 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1397 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1398 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1399 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1400 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1401 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1402 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1403 // Sort in descending order
1404 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1406 // Sort in ascending order
1407 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1412 /// Finds a route from us (payer) to the given target node (payee).
1414 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1415 /// in the given [`RouteParameters::payment_params`].
1416 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1418 /// Private routing paths between a public node and the target may be included in the `payee` field
1419 /// of [`RouteParameters::payment_params`].
1421 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1422 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1423 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1425 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1426 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1427 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1431 /// Panics if first_hops contains channels without `short_channel_id`s;
1432 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1434 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1435 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1436 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1437 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1438 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1439 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1440 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1441 ) -> Result<Route, LightningError>
1442 where L::Target: Logger, GL::Target: Logger {
1443 let graph_lock = network_graph.read_only();
1444 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1445 scorer, score_params, random_seed_bytes)?;
1446 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1450 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1451 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1452 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1453 _random_seed_bytes: &[u8; 32]
1454 ) -> Result<Route, LightningError>
1455 where L::Target: Logger {
1457 let payment_params = &route_params.payment_params;
1458 let final_value_msat = route_params.final_value_msat;
1459 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1460 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1461 // so use a dummy id for this in the blinded case.
1462 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1463 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1464 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1465 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1466 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1468 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1469 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1472 if final_value_msat > MAX_VALUE_MSAT {
1473 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1476 if final_value_msat == 0 {
1477 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1480 match &payment_params.payee {
1481 Payee::Clear { route_hints, node_id, .. } => {
1482 for route in route_hints.iter() {
1483 for hop in &route.0 {
1484 if hop.src_node_id == *node_id {
1485 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1490 Payee::Blinded { route_hints, .. } => {
1491 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1492 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});
1494 for (_, blinded_path) in route_hints.iter() {
1495 if blinded_path.blinded_hops.len() == 0 {
1496 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1497 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1498 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1499 } else if blinded_path.blinded_hops.len() == 1 &&
1500 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1501 && p.introduction_node_id != blinded_path.introduction_node_id)
1503 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1508 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1509 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1510 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});
1513 // The general routing idea is the following:
1514 // 1. Fill first/last hops communicated by the caller.
1515 // 2. Attempt to construct a path from payer to payee for transferring
1516 // any ~sufficient (described later) value.
1517 // If succeed, remember which channels were used and how much liquidity they have available,
1518 // so that future paths don't rely on the same liquidity.
1519 // 3. Proceed to the next step if:
1520 // - we hit the recommended target value;
1521 // - OR if we could not construct a new path. Any next attempt will fail too.
1522 // Otherwise, repeat step 2.
1523 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1524 // (not recommended value).
1525 // 5. If yes, proceed. If not, fail routing.
1526 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1527 // transferred up to the transfer target value.
1528 // 7. Reduce the value of the last path until we are sending only the target value.
1529 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1530 // them so that we're not sending two HTLCs along the same path.
1532 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1533 // distance from the payee
1535 // We are not a faithful Dijkstra's implementation because we can change values which impact
1536 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1537 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1538 // the value we are currently attempting to send over a path, we simply reduce the value being
1539 // sent along the path for any hops after that channel. This may imply that later fees (which
1540 // we've already tabulated) are lower because a smaller value is passing through the channels
1541 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1542 // channels which were selected earlier (and which may still be used for other paths without a
1543 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1546 // One potentially problematic case for this algorithm would be if there are many
1547 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1548 // graph walking), we may never find a path which is not liquidity-limited and has lower
1549 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1550 // Because we only consider paths with at least 5% of the total value being sent, the damage
1551 // from such a case should be limited, however this could be further reduced in the future by
1552 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1553 // limits for the purposes of fee calculation.
1555 // Alternatively, we could store more detailed path information in the heap (targets, below)
1556 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1557 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1558 // and practically (as we would need to store dynamically-allocated path information in heap
1559 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1560 // results of such an algorithm would likely be biased towards lower-value paths.
1562 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1563 // outside of our current search value, running a path search more times to gather candidate
1564 // paths at different values. While this may be acceptable, further path searches may increase
1565 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1566 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1567 // the same time, remaining generic across different payment values.
1569 let network_channels = network_graph.channels();
1570 let network_nodes = network_graph.nodes();
1572 if payment_params.max_path_count == 0 {
1573 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1576 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1577 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1579 let allow_mpp = if payment_params.max_path_count == 1 {
1581 } else if payment_params.payee.supports_basic_mpp() {
1583 } else if let Some(payee) = payee_node_id_opt {
1584 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1585 |info| info.features.supports_basic_mpp()))
1588 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1589 LoggedPayeePubkey(payment_params.payee.node_id()), if allow_mpp { "with" } else { "without" },
1590 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1593 // Prepare the data we'll use for payee-to-payer search by
1594 // inserting first hops suggested by the caller as targets.
1595 // Our search will then attempt to reach them while traversing from the payee node.
1596 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1597 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1598 if let Some(hops) = first_hops {
1600 if chan.get_outbound_payment_scid().is_none() {
1601 panic!("first_hops should be filled in with usable channels, not pending ones");
1603 if chan.counterparty.node_id == *our_node_pubkey {
1604 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1607 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1608 .or_insert(Vec::new())
1611 if first_hop_targets.is_empty() {
1612 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1616 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1617 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1618 // adding duplicate entries when we find a better path to a given node.
1619 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1621 // Map from node_id to information about the best current path to that node, including feerate
1623 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1625 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1626 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1627 // htlc_minimum with extra fees while still finding a cheaper path.
1628 let mut hit_minimum_limit;
1630 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1631 // We start with a path_value of the exact amount we want, and if that generates a route we may
1632 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1633 // amount we want in total across paths, selecting the best subset at the end.
1634 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1635 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1636 let mut path_value_msat = final_value_msat;
1638 // Routing Fragmentation Mitigation heuristic:
1640 // Routing fragmentation across many payment paths increases the overall routing
1641 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1642 // Taking too many smaller paths also increases the chance of payment failure.
1643 // Thus to avoid this effect, we require from our collected links to provide
1644 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1645 // This requirement is currently set to be 1/max_path_count of the payment
1646 // value to ensure we only ever return routes that do not violate this limit.
1647 let minimal_value_contribution_msat: u64 = if allow_mpp {
1648 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1653 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1654 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1655 // drop the requirement by setting this to 0.
1656 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1658 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1659 // determine if the channel can be used by additional MPP paths or to inform path finding
1660 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1661 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1663 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1664 HashMap::with_capacity(network_nodes.len());
1666 // Keeping track of how much value we already collected across other paths. Helps to decide
1667 // when we want to stop looking for new paths.
1668 let mut already_collected_value_msat = 0;
1670 for (_, channels) in first_hop_targets.iter_mut() {
1671 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1675 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1676 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1678 // Remember how many candidates we ignored to allow for some logging afterwards.
1679 let mut num_ignored_value_contribution = 0;
1680 let mut num_ignored_path_length_limit = 0;
1681 let mut num_ignored_cltv_delta_limit = 0;
1682 let mut num_ignored_previously_failed = 0;
1684 macro_rules! add_entry {
1685 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1686 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1687 // since that value has to be transferred over this channel.
1688 // Returns whether this channel caused an update to `targets`.
1689 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1690 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1691 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1692 // We "return" whether we updated the path at the end, and how much we can route via
1693 // this channel, via this:
1694 let mut did_add_update_path_to_src_node = None;
1695 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1696 // practice these cases should be caught earlier:
1697 // - for regular channels at channel announcement (TODO)
1698 // - for first and last hops early in get_route
1699 if $src_node_id != $dest_node_id {
1700 let scid_opt = $candidate.short_channel_id();
1701 let effective_capacity = $candidate.effective_capacity();
1702 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1704 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1705 // It may be misleading because we might later choose to reduce the value transferred
1706 // over these channels, and the channel which was insufficient might become sufficient.
1707 // Worst case: we drop a good channel here because it can't cover the high following
1708 // fees caused by one expensive channel, but then this channel could have been used
1709 // if the amount being transferred over this path is lower.
1710 // We do this for now, but this is a subject for removal.
1711 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1712 let used_liquidity_msat = used_liquidities
1713 .get(&$candidate.id($src_node_id < $dest_node_id))
1714 .map_or(0, |used_liquidity_msat| {
1715 available_value_contribution_msat = available_value_contribution_msat
1716 .saturating_sub(*used_liquidity_msat);
1717 *used_liquidity_msat
1720 // Verify the liquidity offered by this channel complies to the minimal contribution.
1721 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1722 // Do not consider candidate hops that would exceed the maximum path length.
1723 let path_length_to_node = $next_hops_path_length + 1;
1724 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1726 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1727 // In order to already account for some of the privacy enhancing random CLTV
1728 // expiry delta offset we add on top later, we subtract a rough estimate
1729 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1730 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1731 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1732 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1733 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1734 .saturating_add($candidate.cltv_expiry_delta());
1735 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1737 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1738 // Includes paying fees for the use of the following channels.
1739 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1740 Some(result) => result,
1741 // Can't overflow due to how the values were computed right above.
1742 None => unreachable!(),
1744 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1745 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1746 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1748 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1749 let may_overpay_to_meet_path_minimum_msat =
1750 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1751 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1752 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1753 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1755 let payment_failed_on_this_channel = scid_opt.map_or(false,
1756 |scid| payment_params.previously_failed_channels.contains(&scid));
1758 let should_log_candidate = match $candidate {
1759 CandidateRouteHop::FirstHop { .. } => true,
1760 CandidateRouteHop::PrivateHop { .. } => true,
1761 CandidateRouteHop::Blinded { .. } => true,
1765 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1766 // bother considering this channel. If retrying with recommended_value_msat may
1767 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1768 // around again with a higher amount.
1769 if !contributes_sufficient_value {
1770 if should_log_candidate {
1771 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
1773 num_ignored_value_contribution += 1;
1774 } else if exceeds_max_path_length {
1775 if should_log_candidate {
1776 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
1778 num_ignored_path_length_limit += 1;
1779 } else if exceeds_cltv_delta_limit {
1780 if should_log_candidate {
1781 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
1783 num_ignored_cltv_delta_limit += 1;
1784 } else if payment_failed_on_this_channel {
1785 if should_log_candidate {
1786 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
1788 num_ignored_previously_failed += 1;
1789 } else if may_overpay_to_meet_path_minimum_msat {
1790 hit_minimum_limit = true;
1791 } else if over_path_minimum_msat {
1792 // Note that low contribution here (limited by available_liquidity_msat)
1793 // might violate htlc_minimum_msat on the hops which are next along the
1794 // payment path (upstream to the payee). To avoid that, we recompute
1795 // path fees knowing the final path contribution after constructing it.
1796 let path_htlc_minimum_msat = cmp::max(
1797 compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1798 .saturating_add($next_hops_path_htlc_minimum_msat),
1799 $candidate.htlc_minimum_msat());
1800 let hm_entry = dist.entry($src_node_id);
1801 let old_entry = hm_entry.or_insert_with(|| {
1802 // If there was previously no known way to access the source node
1803 // (recall it goes payee-to-payer) of short_channel_id, first add a
1804 // semi-dummy record just to compute the fees to reach the source node.
1805 // This will affect our decision on selecting short_channel_id
1806 // as a way to reach the $dest_node_id.
1808 node_id: $dest_node_id.clone(),
1809 candidate: $candidate.clone(),
1811 next_hops_fee_msat: u64::max_value(),
1812 hop_use_fee_msat: u64::max_value(),
1813 total_fee_msat: u64::max_value(),
1814 path_htlc_minimum_msat,
1815 path_penalty_msat: u64::max_value(),
1816 was_processed: false,
1817 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1818 value_contribution_msat,
1822 #[allow(unused_mut)] // We only use the mut in cfg(test)
1823 let mut should_process = !old_entry.was_processed;
1824 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1826 // In test/fuzzing builds, we do extra checks to make sure the skipping
1827 // of already-seen nodes only happens in cases we expect (see below).
1828 if !should_process { should_process = true; }
1832 let mut hop_use_fee_msat = 0;
1833 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1835 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1836 // will have the same effective-fee
1837 if $src_node_id != our_node_id {
1838 // Note that `u64::max_value` means we'll always fail the
1839 // `old_entry.total_fee_msat > total_fee_msat` check below
1840 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1841 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1844 let channel_usage = ChannelUsage {
1845 amount_msat: amount_to_transfer_over_msat,
1846 inflight_htlc_msat: used_liquidity_msat,
1849 let channel_penalty_msat = scid_opt.map_or(0,
1850 |scid| scorer.channel_penalty_msat(scid, &$src_node_id, &$dest_node_id,
1851 channel_usage, score_params));
1852 let path_penalty_msat = $next_hops_path_penalty_msat
1853 .saturating_add(channel_penalty_msat);
1854 let new_graph_node = RouteGraphNode {
1855 node_id: $src_node_id,
1856 lowest_fee_to_node: total_fee_msat,
1857 total_cltv_delta: hop_total_cltv_delta,
1858 value_contribution_msat,
1859 path_htlc_minimum_msat,
1861 path_length_to_node,
1864 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1865 // if this way is cheaper than the already known
1866 // (considering the cost to "reach" this channel from the route destination,
1867 // the cost of using this channel,
1868 // and the cost of routing to the source node of this channel).
1869 // Also, consider that htlc_minimum_msat_difference, because we might end up
1870 // paying it. Consider the following exploit:
1871 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1872 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1873 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1874 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1876 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1877 // but it may require additional tracking - we don't want to double-count
1878 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1879 // can't use something that may decrease on future hops.
1880 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1881 .saturating_add(old_entry.path_penalty_msat);
1882 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1883 .saturating_add(path_penalty_msat);
1885 if !old_entry.was_processed && new_cost < old_cost {
1886 targets.push(new_graph_node);
1887 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1888 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1889 old_entry.total_fee_msat = total_fee_msat;
1890 old_entry.node_id = $dest_node_id.clone();
1891 old_entry.candidate = $candidate.clone();
1892 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1893 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1894 old_entry.path_penalty_msat = path_penalty_msat;
1895 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1897 old_entry.value_contribution_msat = value_contribution_msat;
1899 did_add_update_path_to_src_node = Some(value_contribution_msat);
1900 } else if old_entry.was_processed && new_cost < old_cost {
1901 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1903 // If we're skipping processing a node which was previously
1904 // processed even though we found another path to it with a
1905 // cheaper fee, check that it was because the second path we
1906 // found (which we are processing now) has a lower value
1907 // contribution due to an HTLC minimum limit.
1909 // e.g. take a graph with two paths from node 1 to node 2, one
1910 // through channel A, and one through channel B. Channel A and
1911 // B are both in the to-process heap, with their scores set by
1912 // a higher htlc_minimum than fee.
1913 // Channel A is processed first, and the channels onwards from
1914 // node 1 are added to the to-process heap. Thereafter, we pop
1915 // Channel B off of the heap, note that it has a much more
1916 // restrictive htlc_maximum_msat, and recalculate the fees for
1917 // all of node 1's channels using the new, reduced, amount.
1919 // This would be bogus - we'd be selecting a higher-fee path
1920 // with a lower htlc_maximum_msat instead of the one we'd
1921 // already decided to use.
1922 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1924 value_contribution_msat + path_penalty_msat <
1925 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1933 did_add_update_path_to_src_node
1937 let default_node_features = default_node_features();
1939 // Find ways (channels with destination) to reach a given node and store them
1940 // in the corresponding data structures (routing graph etc).
1941 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1942 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1943 // This data can later be helpful to optimize routing (pay lower fees).
1944 macro_rules! add_entries_to_cheapest_to_target_node {
1945 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1946 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1947 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1948 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1949 let was_processed = elem.was_processed;
1950 elem.was_processed = true;
1953 // Entries are added to dist in add_entry!() when there is a channel from a node.
1954 // Because there are no channels from payee, it will not have a dist entry at this point.
1955 // If we're processing any other node, it is always be the result of a channel from it.
1956 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
1961 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1962 for details in first_channels {
1963 let candidate = CandidateRouteHop::FirstHop { details };
1964 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1965 $next_hops_value_contribution,
1966 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1967 $next_hops_cltv_delta, $next_hops_path_length);
1971 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1974 &default_node_features
1977 if !features.requires_unknown_bits() {
1978 for chan_id in $node.channels.iter() {
1979 let chan = network_channels.get(chan_id).unwrap();
1980 if !chan.features.requires_unknown_bits() {
1981 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1982 if first_hops.is_none() || *source != our_node_id {
1983 if directed_channel.direction().enabled {
1984 let candidate = CandidateRouteHop::PublicHop {
1985 info: directed_channel,
1986 short_channel_id: *chan_id,
1988 add_entry!(candidate, *source, $node_id,
1989 $fee_to_target_msat,
1990 $next_hops_value_contribution,
1991 $next_hops_path_htlc_minimum_msat,
1992 $next_hops_path_penalty_msat,
1993 $next_hops_cltv_delta, $next_hops_path_length);
2004 let mut payment_paths = Vec::<PaymentPath>::new();
2006 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2007 'paths_collection: loop {
2008 // For every new path, start from scratch, except for used_liquidities, which
2009 // helps to avoid reusing previously selected paths in future iterations.
2012 hit_minimum_limit = false;
2014 // If first hop is a private channel and the only way to reach the payee, this is the only
2015 // place where it could be added.
2016 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2017 for details in first_channels {
2018 let candidate = CandidateRouteHop::FirstHop { details };
2019 let added = add_entry!(candidate, our_node_id, payee, 0, path_value_msat,
2020 0, 0u64, 0, 0).is_some();
2021 log_trace!(logger, "{} direct route to payee via {}",
2022 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2026 // Add the payee as a target, so that the payee-to-payer
2027 // search algorithm knows what to start with.
2028 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2029 // The payee is not in our network graph, so nothing to add here.
2030 // There is still a chance of reaching them via last_hops though,
2031 // so don't yet fail the payment here.
2032 // If not, targets.pop() will not even let us enter the loop in step 2.
2035 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
2040 // If a caller provided us with last hops, add them to routing targets. Since this happens
2041 // earlier than general path finding, they will be somewhat prioritized, although currently
2042 // it matters only if the fees are exactly the same.
2043 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2044 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2045 let have_intro_node_in_graph =
2046 // Only add the hops in this route to our candidate set if either
2047 // we have a direct channel to the first hop or the first hop is
2048 // in the regular network graph.
2049 first_hop_targets.get(&intro_node_id).is_some() ||
2050 network_nodes.get(&intro_node_id).is_some();
2051 if !have_intro_node_in_graph { continue }
2052 let candidate = if hint.1.blinded_hops.len() == 1 {
2053 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
2054 } else { CandidateRouteHop::Blinded { hint, hint_idx } };
2055 let mut path_contribution_msat = path_value_msat;
2056 if let Some(hop_used_msat) = add_entry!(candidate, intro_node_id, maybe_dummy_payee_node_id,
2057 0, path_contribution_msat, 0, 0_u64, 0, 0)
2059 path_contribution_msat = hop_used_msat;
2061 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2062 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2064 for details in first_channels {
2065 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2066 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2070 add_entry!(first_hop_candidate, our_node_id, intro_node_id, blinded_path_fee,
2071 path_contribution_msat, candidate.htlc_minimum_msat(), 0_u64,
2072 candidate.cltv_expiry_delta(),
2073 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2077 for route in payment_params.payee.unblinded_route_hints().iter()
2078 .filter(|route| !route.0.is_empty())
2080 let first_hop_in_route = &(route.0)[0];
2081 let have_hop_src_in_graph =
2082 // Only add the hops in this route to our candidate set if either
2083 // we have a direct channel to the first hop or the first hop is
2084 // in the regular network graph.
2085 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
2086 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
2087 if have_hop_src_in_graph {
2088 // We start building the path from reverse, i.e., from payee
2089 // to the first RouteHintHop in the path.
2090 let hop_iter = route.0.iter().rev();
2091 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2092 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2093 let mut hop_used = true;
2094 let mut aggregate_next_hops_fee_msat: u64 = 0;
2095 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2096 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2097 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2098 let mut aggregate_next_hops_path_length: u8 = 0;
2099 let mut aggregate_path_contribution_msat = path_value_msat;
2101 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2102 let source = NodeId::from_pubkey(&hop.src_node_id);
2103 let target = NodeId::from_pubkey(&prev_hop_id);
2104 let candidate = network_channels
2105 .get(&hop.short_channel_id)
2106 .and_then(|channel| channel.as_directed_to(&target))
2107 .map(|(info, _)| CandidateRouteHop::PublicHop {
2109 short_channel_id: hop.short_channel_id,
2111 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
2113 if let Some(hop_used_msat) = add_entry!(candidate, source, target,
2114 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2115 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2116 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2118 aggregate_path_contribution_msat = hop_used_msat;
2120 // If this hop was not used then there is no use checking the preceding
2121 // hops in the RouteHint. We can break by just searching for a direct
2122 // channel between last checked hop and first_hop_targets.
2126 let used_liquidity_msat = used_liquidities
2127 .get(&candidate.id(source < target)).copied()
2129 let channel_usage = ChannelUsage {
2130 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2131 inflight_htlc_msat: used_liquidity_msat,
2132 effective_capacity: candidate.effective_capacity(),
2134 let channel_penalty_msat = scorer.channel_penalty_msat(
2135 hop.short_channel_id, &source, &target, channel_usage, score_params
2137 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2138 .saturating_add(channel_penalty_msat);
2140 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2141 .saturating_add(hop.cltv_expiry_delta as u32);
2143 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2146 // Searching for a direct channel between last checked hop and first_hop_targets
2147 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&prev_hop_id)) {
2148 sort_first_hop_channels(first_channels, &used_liquidities,
2149 recommended_value_msat, our_node_pubkey);
2150 for details in first_channels {
2151 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2152 add_entry!(first_hop_candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
2153 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2154 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2155 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2163 // In the next values of the iterator, the aggregate fees already reflects
2164 // the sum of value sent from payer (final_value_msat) and routing fees
2165 // for the last node in the RouteHint. We need to just add the fees to
2166 // route through the current node so that the preceding node (next iteration)
2168 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2169 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2170 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2172 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
2173 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
2174 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
2175 .checked_add(hop_htlc_minimum_msat_inc);
2176 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
2178 if idx == route.0.len() - 1 {
2179 // The last hop in this iterator is the first hop in
2180 // overall RouteHint.
2181 // If this hop connects to a node with which we have a direct channel,
2182 // ignore the network graph and, if the last hop was added, add our
2183 // direct channel to the candidate set.
2185 // Note that we *must* check if the last hop was added as `add_entry`
2186 // always assumes that the third argument is a node to which we have a
2188 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2189 sort_first_hop_channels(first_channels, &used_liquidities,
2190 recommended_value_msat, our_node_pubkey);
2191 for details in first_channels {
2192 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2193 add_entry!(first_hop_candidate, our_node_id,
2194 NodeId::from_pubkey(&hop.src_node_id),
2195 aggregate_next_hops_fee_msat,
2196 aggregate_path_contribution_msat,
2197 aggregate_next_hops_path_htlc_minimum_msat,
2198 aggregate_next_hops_path_penalty_msat,
2199 aggregate_next_hops_cltv_delta,
2200 aggregate_next_hops_path_length);
2208 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2210 // At this point, targets are filled with the data from first and
2211 // last hops communicated by the caller, and the payment receiver.
2212 let mut found_new_path = false;
2215 // If this loop terminates due the exhaustion of targets, two situations are possible:
2216 // - not enough outgoing liquidity:
2217 // 0 < already_collected_value_msat < final_value_msat
2218 // - enough outgoing liquidity:
2219 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2220 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2221 // paths_collection will be stopped because found_new_path==false.
2222 // This is not necessarily a routing failure.
2223 '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() {
2225 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2226 // traversing the graph and arrange the path out of what we found.
2227 if node_id == our_node_id {
2228 let mut new_entry = dist.remove(&our_node_id).unwrap();
2229 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2232 let mut features_set = false;
2233 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
2234 for details in first_channels {
2235 if let Some(scid) = ordered_hops.last().unwrap().0.candidate.short_channel_id() {
2236 if details.get_outbound_payment_scid().unwrap() == scid {
2237 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2238 features_set = true;
2245 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
2246 if let Some(node_info) = node.announcement_info.as_ref() {
2247 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2249 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2252 // We can fill in features for everything except hops which were
2253 // provided via the invoice we're paying. We could guess based on the
2254 // recipient's features but for now we simply avoid guessing at all.
2258 // Means we succesfully traversed from the payer to the payee, now
2259 // save this path for the payment route. Also, update the liquidity
2260 // remaining on the used hops, so that we take them into account
2261 // while looking for more paths.
2262 if ordered_hops.last().unwrap().0.node_id == maybe_dummy_payee_node_id {
2266 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
2267 Some(payment_hop) => payment_hop,
2268 // We can't arrive at None because, if we ever add an entry to targets,
2269 // we also fill in the entry in dist (see add_entry!).
2270 None => unreachable!(),
2272 // We "propagate" the fees one hop backward (topologically) here,
2273 // so that fees paid for a HTLC forwarding on the current channel are
2274 // associated with the previous channel (where they will be subtracted).
2275 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2276 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2278 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2279 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2281 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2282 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2284 let mut payment_path = PaymentPath {hops: ordered_hops};
2286 // We could have possibly constructed a slightly inconsistent path: since we reduce
2287 // value being transferred along the way, we could have violated htlc_minimum_msat
2288 // on some channels we already passed (assuming dest->source direction). Here, we
2289 // recompute the fees again, so that if that's the case, we match the currently
2290 // underpaid htlc_minimum_msat with fees.
2291 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2292 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
2293 payment_path.update_value_and_recompute_fees(value_contribution_msat);
2295 // Since a path allows to transfer as much value as
2296 // the smallest channel it has ("bottleneck"), we should recompute
2297 // the fees so sender HTLC don't overpay fees when traversing
2298 // larger channels than the bottleneck. This may happen because
2299 // when we were selecting those channels we were not aware how much value
2300 // this path will transfer, and the relative fee for them
2301 // might have been computed considering a larger value.
2302 // Remember that we used these channels so that we don't rely
2303 // on the same liquidity in future paths.
2304 let mut prevented_redundant_path_selection = false;
2305 let prev_hop_iter = core::iter::once(&our_node_id)
2306 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
2307 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
2308 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2309 let used_liquidity_msat = used_liquidities
2310 .entry(hop.candidate.id(*prev_hop < hop.node_id))
2311 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2312 .or_insert(spent_on_hop_msat);
2313 let hop_capacity = hop.candidate.effective_capacity();
2314 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2315 if *used_liquidity_msat == hop_max_msat {
2316 // If this path used all of this channel's available liquidity, we know
2317 // this path will not be selected again in the next loop iteration.
2318 prevented_redundant_path_selection = true;
2320 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2322 if !prevented_redundant_path_selection {
2323 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2324 // we'll probably end up picking the same path again on the next iteration.
2325 // Decrease the available liquidity of a hop in the middle of the path.
2326 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2327 let exhausted = u64::max_value();
2329 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2330 LoggedCandidateHop(victim_candidate));
2331 *used_liquidities.entry(victim_candidate.id(false)).or_default() = exhausted;
2332 *used_liquidities.entry(victim_candidate.id(true)).or_default() = exhausted;
2335 // Track the total amount all our collected paths allow to send so that we know
2336 // when to stop looking for more paths
2337 already_collected_value_msat += value_contribution_msat;
2339 payment_paths.push(payment_path);
2340 found_new_path = true;
2341 break 'path_construction;
2344 // If we found a path back to the payee, we shouldn't try to process it again. This is
2345 // the equivalent of the `elem.was_processed` check in
2346 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2347 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2349 // Otherwise, since the current target node is not us,
2350 // keep "unrolling" the payment graph from payee to payer by
2351 // finding a way to reach the current target from the payer side.
2352 match network_nodes.get(&node_id) {
2355 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2356 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2357 total_cltv_delta, path_length_to_node);
2363 if !found_new_path && channel_saturation_pow_half != 0 {
2364 channel_saturation_pow_half = 0;
2365 continue 'paths_collection;
2367 // If we don't support MPP, no use trying to gather more value ever.
2368 break 'paths_collection;
2372 // Stop either when the recommended value is reached or if no new path was found in this
2374 // In the latter case, making another path finding attempt won't help,
2375 // because we deterministically terminated the search due to low liquidity.
2376 if !found_new_path && channel_saturation_pow_half != 0 {
2377 channel_saturation_pow_half = 0;
2378 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2379 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2380 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2381 break 'paths_collection;
2382 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2383 // Further, if this was our first walk of the graph, and we weren't limited by an
2384 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2385 // limited by an htlc_minimum_msat value, find another path with a higher value,
2386 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2387 // still keeping a lower total fee than this path.
2388 if !hit_minimum_limit {
2389 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2390 break 'paths_collection;
2392 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
2393 path_value_msat = recommended_value_msat;
2397 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2398 num_ignored_cltv_delta_limit + num_ignored_previously_failed;
2399 if num_ignored_total > 0 {
2400 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);
2404 if payment_paths.len() == 0 {
2405 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2408 if already_collected_value_msat < final_value_msat {
2409 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2413 let mut selected_route = payment_paths;
2415 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2416 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2418 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2419 // the value they contribute towards the payment amount.
2420 // We sort in descending order as we will remove from the front in `retain`, next.
2421 selected_route.sort_unstable_by(|a, b|
2422 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2423 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2426 // We should make sure that at least 1 path left.
2427 let mut paths_left = selected_route.len();
2428 selected_route.retain(|path| {
2429 if paths_left == 1 {
2432 let path_value_msat = path.get_value_msat();
2433 if path_value_msat <= overpaid_value_msat {
2434 overpaid_value_msat -= path_value_msat;
2440 debug_assert!(selected_route.len() > 0);
2442 if overpaid_value_msat != 0 {
2444 // Now, subtract the remaining overpaid value from the most-expensive path.
2445 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2446 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2447 selected_route.sort_unstable_by(|a, b| {
2448 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2449 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2450 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2452 let expensive_payment_path = selected_route.first_mut().unwrap();
2454 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2455 // can't go negative.
2456 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2457 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2461 // Sort by the path itself and combine redundant paths.
2462 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2463 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2465 selected_route.sort_unstable_by_key(|path| {
2466 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2467 debug_assert!(path.hops.len() <= key.len());
2468 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id(true)).zip(key.iter_mut()) {
2473 for idx in 0..(selected_route.len() - 1) {
2474 if idx + 1 >= selected_route.len() { break; }
2475 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id)),
2476 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id))) {
2477 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2478 selected_route[idx].update_value_and_recompute_fees(new_value);
2479 selected_route.remove(idx + 1);
2483 let mut paths = Vec::new();
2484 for payment_path in selected_route {
2485 let mut hops = Vec::with_capacity(payment_path.hops.len());
2486 let mut prev_hop_node_id = our_node_id;
2487 for (hop, node_features) in payment_path.hops.iter()
2488 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2490 let maybe_announced_channel = if let CandidateRouteHop::PublicHop { .. } = hop.candidate {
2491 // If we sourced the hop from the graph we're sure the target node is announced.
2493 } else if let CandidateRouteHop::FirstHop { details } = hop.candidate {
2494 // If this is a first hop we also know if it's announced.
2497 // If we sourced it any other way, we double-check the network graph to see if
2498 // there are announced channels between the endpoints. If so, the hop might be
2499 // referring to any of the announced channels, as its `short_channel_id` might be
2500 // an alias, in which case we don't take any chances here.
2501 network_graph.node(&hop.node_id).map_or(false, |hop_node|
2502 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
2503 .map_or(false, |c| c.as_directed_from(&prev_hop_node_id).is_some()))
2507 hops.push(RouteHop {
2508 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)})?,
2509 node_features: node_features.clone(),
2510 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2511 channel_features: hop.candidate.features(),
2512 fee_msat: hop.fee_msat,
2513 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2514 maybe_announced_channel,
2517 prev_hop_node_id = hop.node_id;
2519 let mut final_cltv_delta = final_cltv_expiry_delta;
2520 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2521 if let Some(blinded_path) = h.candidate.blinded_path() {
2522 final_cltv_delta = h.candidate.cltv_expiry_delta();
2524 hops: blinded_path.blinded_hops.clone(),
2525 blinding_point: blinded_path.blinding_point,
2526 excess_final_cltv_expiry_delta: 0,
2527 final_value_msat: h.fee_msat,
2531 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2532 // applicable for the previous hop.
2533 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2534 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2537 paths.push(Path { hops, blinded_tail });
2539 // Make sure we would never create a route with more paths than we allow.
2540 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2542 if let Some(node_features) = payment_params.payee.node_features() {
2543 for path in paths.iter_mut() {
2544 path.hops.last_mut().unwrap().node_features = node_features.clone();
2548 let route = Route { paths, route_params: Some(route_params.clone()) };
2549 log_info!(logger, "Got route: {}", log_route!(route));
2553 // When an adversarial intermediary node observes a payment, it may be able to infer its
2554 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2555 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2556 // payment path by adding a randomized 'shadow route' offset to the final hop.
2557 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2558 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2560 let network_channels = network_graph.channels();
2561 let network_nodes = network_graph.nodes();
2563 for path in route.paths.iter_mut() {
2564 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2566 // Remember the last three nodes of the random walk and avoid looping back on them.
2567 // Init with the last three nodes from the actual path, if possible.
2568 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2569 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2570 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2572 // Choose the last publicly known node as the starting point for the random walk.
2573 let mut cur_hop: Option<NodeId> = None;
2574 let mut path_nonce = [0u8; 12];
2575 if let Some(starting_hop) = path.hops.iter().rev()
2576 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2577 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2578 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2581 // Init PRNG with the path-dependant nonce, which is static for private paths.
2582 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2583 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2585 // Pick a random path length in [1 .. 3]
2586 prng.process_in_place(&mut random_path_bytes);
2587 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2589 for random_hop in 0..random_walk_length {
2590 // If we don't find a suitable offset in the public network graph, we default to
2591 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2592 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2594 if let Some(cur_node_id) = cur_hop {
2595 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2596 // Randomly choose the next unvisited hop.
2597 prng.process_in_place(&mut random_path_bytes);
2598 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2599 .checked_rem(cur_node.channels.len())
2600 .and_then(|index| cur_node.channels.get(index))
2601 .and_then(|id| network_channels.get(id)) {
2602 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2603 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2604 nodes_to_avoid[random_hop] = *next_id;
2605 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2606 cur_hop = Some(*next_id);
2613 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2614 .checked_add(random_hop_offset)
2615 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2618 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2619 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2620 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2622 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2623 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2624 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2625 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2626 max_path_offset = cmp::max(
2627 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2628 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2629 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2631 // Add 'shadow' CLTV offset to the final hop
2632 if let Some(tail) = path.blinded_tail.as_mut() {
2633 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2634 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2636 if let Some(last_hop) = path.hops.last_mut() {
2637 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2638 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2643 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2644 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2646 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2647 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2648 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2649 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2650 ) -> Result<Route, LightningError>
2651 where L::Target: Logger, GL::Target: Logger {
2652 let graph_lock = network_graph.read_only();
2653 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
2654 &graph_lock, logger, random_seed_bytes)?;
2655 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2659 fn build_route_from_hops_internal<L: Deref>(
2660 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2661 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
2662 ) -> Result<Route, LightningError> where L::Target: Logger {
2665 our_node_id: NodeId,
2666 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2669 impl ScoreLookUp for HopScorer {
2670 type ScoreParams = ();
2671 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2672 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2674 let mut cur_id = self.our_node_id;
2675 for i in 0..self.hop_ids.len() {
2676 if let Some(next_id) = self.hop_ids[i] {
2677 if cur_id == *source && next_id == *target {
2689 impl<'a> Writeable for HopScorer {
2691 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2696 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2697 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2700 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2701 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2702 for i in 0..hops.len() {
2703 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2706 let scorer = HopScorer { our_node_id, hop_ids };
2708 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
2713 use crate::blinded_path::{BlindedHop, BlindedPath};
2714 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2715 use crate::routing::utxo::UtxoResult;
2716 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2717 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2718 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters};
2719 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2720 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2721 use crate::chain::transaction::OutPoint;
2722 use crate::sign::EntropySource;
2723 use crate::ln::ChannelId;
2724 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2725 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2726 use crate::ln::channelmanager;
2727 use crate::offers::invoice::BlindedPayInfo;
2728 use crate::util::config::UserConfig;
2729 use crate::util::test_utils as ln_test_utils;
2730 use crate::util::chacha20::ChaCha20;
2731 use crate::util::ser::{Readable, Writeable};
2733 use crate::util::ser::Writer;
2735 use bitcoin::hashes::Hash;
2736 use bitcoin::network::constants::Network;
2737 use bitcoin::blockdata::constants::genesis_block;
2738 use bitcoin::blockdata::script::Builder;
2739 use bitcoin::blockdata::opcodes;
2740 use bitcoin::blockdata::transaction::TxOut;
2744 use bitcoin::secp256k1::{PublicKey,SecretKey};
2745 use bitcoin::secp256k1::Secp256k1;
2747 use crate::io::Cursor;
2748 use crate::prelude::*;
2749 use crate::sync::Arc;
2751 use core::convert::TryInto;
2753 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2754 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2755 channelmanager::ChannelDetails {
2756 channel_id: ChannelId::new_zero(),
2757 counterparty: channelmanager::ChannelCounterparty {
2760 unspendable_punishment_reserve: 0,
2761 forwarding_info: None,
2762 outbound_htlc_minimum_msat: None,
2763 outbound_htlc_maximum_msat: None,
2765 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2768 outbound_scid_alias: None,
2769 inbound_scid_alias: None,
2770 channel_value_satoshis: 0,
2772 outbound_capacity_msat,
2773 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2774 next_outbound_htlc_minimum_msat: 0,
2775 inbound_capacity_msat: 42,
2776 unspendable_punishment_reserve: None,
2777 confirmations_required: None,
2778 confirmations: None,
2779 force_close_spend_delay: None,
2780 is_outbound: true, is_channel_ready: true,
2781 is_usable: true, is_public: true,
2782 inbound_htlc_minimum_msat: None,
2783 inbound_htlc_maximum_msat: None,
2785 feerate_sat_per_1000_weight: None,
2786 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
2791 fn simple_route_test() {
2792 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2793 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2794 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2795 let scorer = ln_test_utils::TestScorer::new();
2796 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2797 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2799 // Simple route to 2 via 1
2801 let route_params = RouteParameters::from_payment_params_and_value(
2802 payment_params.clone(), 0);
2803 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2804 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
2805 &Default::default(), &random_seed_bytes) {
2806 assert_eq!(err, "Cannot send a payment of 0 msat");
2807 } else { panic!(); }
2809 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
2810 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2811 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
2812 assert_eq!(route.paths[0].hops.len(), 2);
2814 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2815 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2816 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2817 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2818 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2819 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2821 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2822 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2823 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2824 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2825 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2826 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2830 fn invalid_first_hop_test() {
2831 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2832 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2833 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2834 let scorer = ln_test_utils::TestScorer::new();
2835 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2836 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2838 // Simple route to 2 via 1
2840 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2842 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
2843 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2844 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
2845 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
2846 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2847 } else { panic!(); }
2849 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2850 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
2851 assert_eq!(route.paths[0].hops.len(), 2);
2855 fn htlc_minimum_test() {
2856 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2857 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2858 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2859 let scorer = ln_test_utils::TestScorer::new();
2860 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2861 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2863 // Simple route to 2 via 1
2865 // Disable other paths
2866 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2867 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2868 short_channel_id: 12,
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[0], UnsignedChannelUpdate {
2879 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2880 short_channel_id: 3,
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()
2890 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2891 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2892 short_channel_id: 13,
2894 flags: 2, // to disable
2895 cltv_expiry_delta: 0,
2896 htlc_minimum_msat: 0,
2897 htlc_maximum_msat: MAX_VALUE_MSAT,
2899 fee_proportional_millionths: 0,
2900 excess_data: Vec::new()
2902 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2903 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2904 short_channel_id: 6,
2906 flags: 2, // to disable
2907 cltv_expiry_delta: 0,
2908 htlc_minimum_msat: 0,
2909 htlc_maximum_msat: MAX_VALUE_MSAT,
2911 fee_proportional_millionths: 0,
2912 excess_data: Vec::new()
2914 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2915 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2916 short_channel_id: 7,
2918 flags: 2, // to disable
2919 cltv_expiry_delta: 0,
2920 htlc_minimum_msat: 0,
2921 htlc_maximum_msat: MAX_VALUE_MSAT,
2923 fee_proportional_millionths: 0,
2924 excess_data: Vec::new()
2927 // Check against amount_to_transfer_over_msat.
2928 // Set minimal HTLC of 200_000_000 msat.
2929 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2930 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2931 short_channel_id: 2,
2934 cltv_expiry_delta: 0,
2935 htlc_minimum_msat: 200_000_000,
2936 htlc_maximum_msat: MAX_VALUE_MSAT,
2938 fee_proportional_millionths: 0,
2939 excess_data: Vec::new()
2942 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2944 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2945 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2946 short_channel_id: 4,
2949 cltv_expiry_delta: 0,
2950 htlc_minimum_msat: 0,
2951 htlc_maximum_msat: 199_999_999,
2953 fee_proportional_millionths: 0,
2954 excess_data: Vec::new()
2957 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2958 let route_params = RouteParameters::from_payment_params_and_value(
2959 payment_params, 199_999_999);
2960 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2961 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
2962 &Default::default(), &random_seed_bytes) {
2963 assert_eq!(err, "Failed to find a path to the given destination");
2964 } else { panic!(); }
2966 // Lift the restriction on the first hop.
2967 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2968 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2969 short_channel_id: 2,
2972 cltv_expiry_delta: 0,
2973 htlc_minimum_msat: 0,
2974 htlc_maximum_msat: MAX_VALUE_MSAT,
2976 fee_proportional_millionths: 0,
2977 excess_data: Vec::new()
2980 // A payment above the minimum should pass
2981 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2982 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
2983 assert_eq!(route.paths[0].hops.len(), 2);
2987 fn htlc_minimum_overpay_test() {
2988 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2989 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2990 let config = UserConfig::default();
2991 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
2992 let scorer = ln_test_utils::TestScorer::new();
2993 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2994 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2996 // A route to node#2 via two paths.
2997 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2998 // Thus, they can't send 60 without overpaying.
2999 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3000 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3001 short_channel_id: 2,
3004 cltv_expiry_delta: 0,
3005 htlc_minimum_msat: 35_000,
3006 htlc_maximum_msat: 40_000,
3008 fee_proportional_millionths: 0,
3009 excess_data: Vec::new()
3011 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3012 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3013 short_channel_id: 12,
3016 cltv_expiry_delta: 0,
3017 htlc_minimum_msat: 35_000,
3018 htlc_maximum_msat: 40_000,
3020 fee_proportional_millionths: 0,
3021 excess_data: Vec::new()
3025 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3026 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3027 short_channel_id: 13,
3030 cltv_expiry_delta: 0,
3031 htlc_minimum_msat: 0,
3032 htlc_maximum_msat: MAX_VALUE_MSAT,
3034 fee_proportional_millionths: 0,
3035 excess_data: Vec::new()
3037 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3038 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3039 short_channel_id: 4,
3042 cltv_expiry_delta: 0,
3043 htlc_minimum_msat: 0,
3044 htlc_maximum_msat: MAX_VALUE_MSAT,
3046 fee_proportional_millionths: 0,
3047 excess_data: Vec::new()
3050 // Disable other paths
3051 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3052 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3053 short_channel_id: 1,
3055 flags: 2, // to disable
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()
3064 let route_params = RouteParameters::from_payment_params_and_value(
3065 payment_params.clone(), 60_000);
3066 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3067 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3068 // Overpay fees to hit htlc_minimum_msat.
3069 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3070 // TODO: this could be better balanced to overpay 10k and not 15k.
3071 assert_eq!(overpaid_fees, 15_000);
3073 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3074 // while taking even more fee to match htlc_minimum_msat.
3075 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3076 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3077 short_channel_id: 12,
3080 cltv_expiry_delta: 0,
3081 htlc_minimum_msat: 65_000,
3082 htlc_maximum_msat: 80_000,
3084 fee_proportional_millionths: 0,
3085 excess_data: Vec::new()
3087 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3088 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3089 short_channel_id: 2,
3092 cltv_expiry_delta: 0,
3093 htlc_minimum_msat: 0,
3094 htlc_maximum_msat: MAX_VALUE_MSAT,
3096 fee_proportional_millionths: 0,
3097 excess_data: Vec::new()
3099 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3100 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3101 short_channel_id: 4,
3104 cltv_expiry_delta: 0,
3105 htlc_minimum_msat: 0,
3106 htlc_maximum_msat: MAX_VALUE_MSAT,
3108 fee_proportional_millionths: 100_000,
3109 excess_data: Vec::new()
3112 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3113 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3114 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3115 assert_eq!(route.paths.len(), 1);
3116 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3117 let fees = route.paths[0].hops[0].fee_msat;
3118 assert_eq!(fees, 5_000);
3120 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3121 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3122 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3123 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3124 // the other channel.
3125 assert_eq!(route.paths.len(), 1);
3126 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3127 let fees = route.paths[0].hops[0].fee_msat;
3128 assert_eq!(fees, 5_000);
3132 fn disable_channels_test() {
3133 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3134 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3135 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3136 let scorer = ln_test_utils::TestScorer::new();
3137 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3138 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3140 // // Disable channels 4 and 12 by flags=2
3141 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3142 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3143 short_channel_id: 4,
3145 flags: 2, // to disable
3146 cltv_expiry_delta: 0,
3147 htlc_minimum_msat: 0,
3148 htlc_maximum_msat: MAX_VALUE_MSAT,
3150 fee_proportional_millionths: 0,
3151 excess_data: Vec::new()
3153 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3154 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3155 short_channel_id: 12,
3157 flags: 2, // to disable
3158 cltv_expiry_delta: 0,
3159 htlc_minimum_msat: 0,
3160 htlc_maximum_msat: MAX_VALUE_MSAT,
3162 fee_proportional_millionths: 0,
3163 excess_data: Vec::new()
3166 // If all the channels require some features we don't understand, route should fail
3167 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3168 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3169 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3170 &Default::default(), &random_seed_bytes) {
3171 assert_eq!(err, "Failed to find a path to the given destination");
3172 } else { panic!(); }
3174 // If we specify a channel to node7, that overrides our local channel view and that gets used
3175 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3176 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3177 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3178 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3179 &Default::default(), &random_seed_bytes).unwrap();
3180 assert_eq!(route.paths[0].hops.len(), 2);
3182 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3183 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3184 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3185 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3186 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3187 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3189 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3190 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3191 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3192 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3193 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3194 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3198 fn disable_node_test() {
3199 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3200 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3201 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3202 let scorer = ln_test_utils::TestScorer::new();
3203 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3204 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3206 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3207 let mut unknown_features = NodeFeatures::empty();
3208 unknown_features.set_unknown_feature_required();
3209 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3210 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3211 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3213 // If all nodes require some features we don't understand, route should fail
3214 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3215 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3216 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3217 &Default::default(), &random_seed_bytes) {
3218 assert_eq!(err, "Failed to find a path to the given destination");
3219 } else { panic!(); }
3221 // If we specify a channel to node7, that overrides our local channel view and that gets used
3222 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3223 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3224 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3225 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3226 &Default::default(), &random_seed_bytes).unwrap();
3227 assert_eq!(route.paths[0].hops.len(), 2);
3229 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3230 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3231 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3232 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3233 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3234 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3236 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3237 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3238 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3239 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3240 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3241 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3243 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3244 // naively) assume that the user checked the feature bits on the invoice, which override
3245 // the node_announcement.
3249 fn our_chans_test() {
3250 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3251 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3252 let scorer = ln_test_utils::TestScorer::new();
3253 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3254 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3256 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3257 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3258 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3259 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3260 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3261 assert_eq!(route.paths[0].hops.len(), 3);
3263 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3264 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3265 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3266 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3267 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3268 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3270 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3271 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3272 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3273 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3274 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3275 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3277 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3278 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3279 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3280 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3281 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3282 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3284 // If we specify a channel to node7, that overrides our local channel view and that gets used
3285 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3286 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3287 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3288 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3289 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3290 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3291 &Default::default(), &random_seed_bytes).unwrap();
3292 assert_eq!(route.paths[0].hops.len(), 2);
3294 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3295 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3296 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3297 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3298 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3299 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3301 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3302 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3303 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3304 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3305 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3306 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3309 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3310 let zero_fees = RoutingFees {
3312 proportional_millionths: 0,
3314 vec![RouteHint(vec![RouteHintHop {
3315 src_node_id: nodes[3],
3316 short_channel_id: 8,
3318 cltv_expiry_delta: (8 << 4) | 1,
3319 htlc_minimum_msat: None,
3320 htlc_maximum_msat: None,
3322 ]), RouteHint(vec![RouteHintHop {
3323 src_node_id: nodes[4],
3324 short_channel_id: 9,
3327 proportional_millionths: 0,
3329 cltv_expiry_delta: (9 << 4) | 1,
3330 htlc_minimum_msat: None,
3331 htlc_maximum_msat: None,
3332 }]), RouteHint(vec![RouteHintHop {
3333 src_node_id: nodes[5],
3334 short_channel_id: 10,
3336 cltv_expiry_delta: (10 << 4) | 1,
3337 htlc_minimum_msat: None,
3338 htlc_maximum_msat: None,
3342 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3343 let zero_fees = RoutingFees {
3345 proportional_millionths: 0,
3347 vec![RouteHint(vec![RouteHintHop {
3348 src_node_id: nodes[2],
3349 short_channel_id: 5,
3352 proportional_millionths: 0,
3354 cltv_expiry_delta: (5 << 4) | 1,
3355 htlc_minimum_msat: None,
3356 htlc_maximum_msat: None,
3358 src_node_id: nodes[3],
3359 short_channel_id: 8,
3361 cltv_expiry_delta: (8 << 4) | 1,
3362 htlc_minimum_msat: None,
3363 htlc_maximum_msat: None,
3365 ]), RouteHint(vec![RouteHintHop {
3366 src_node_id: nodes[4],
3367 short_channel_id: 9,
3370 proportional_millionths: 0,
3372 cltv_expiry_delta: (9 << 4) | 1,
3373 htlc_minimum_msat: None,
3374 htlc_maximum_msat: None,
3375 }]), RouteHint(vec![RouteHintHop {
3376 src_node_id: nodes[5],
3377 short_channel_id: 10,
3379 cltv_expiry_delta: (10 << 4) | 1,
3380 htlc_minimum_msat: None,
3381 htlc_maximum_msat: None,
3386 fn partial_route_hint_test() {
3387 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3388 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3389 let scorer = ln_test_utils::TestScorer::new();
3390 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3391 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3393 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3394 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3395 // RouteHint may be partially used by the algo to build the best path.
3397 // First check that last hop can't have its source as the payee.
3398 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3399 src_node_id: nodes[6],
3400 short_channel_id: 8,
3403 proportional_millionths: 0,
3405 cltv_expiry_delta: (8 << 4) | 1,
3406 htlc_minimum_msat: None,
3407 htlc_maximum_msat: None,
3410 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3411 invalid_last_hops.push(invalid_last_hop);
3413 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3414 .with_route_hints(invalid_last_hops).unwrap();
3415 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3416 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3417 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3418 &Default::default(), &random_seed_bytes) {
3419 assert_eq!(err, "Route hint cannot have the payee as the source.");
3420 } else { panic!(); }
3423 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3424 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3425 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3426 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3427 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3428 assert_eq!(route.paths[0].hops.len(), 5);
3430 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3431 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3432 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3433 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3434 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3435 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3437 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3438 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3439 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3440 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3441 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3442 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3444 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3445 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3446 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3447 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3448 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3449 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3451 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3452 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3453 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3454 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3455 // If we have a peer in the node map, we'll use their features here since we don't have
3456 // a way of figuring out their features from the invoice:
3457 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3458 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3460 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3461 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3462 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3463 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3464 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3465 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3468 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3469 let zero_fees = RoutingFees {
3471 proportional_millionths: 0,
3473 vec![RouteHint(vec![RouteHintHop {
3474 src_node_id: nodes[3],
3475 short_channel_id: 8,
3477 cltv_expiry_delta: (8 << 4) | 1,
3478 htlc_minimum_msat: None,
3479 htlc_maximum_msat: None,
3480 }]), RouteHint(vec![
3482 ]), RouteHint(vec![RouteHintHop {
3483 src_node_id: nodes[5],
3484 short_channel_id: 10,
3486 cltv_expiry_delta: (10 << 4) | 1,
3487 htlc_minimum_msat: None,
3488 htlc_maximum_msat: None,
3493 fn ignores_empty_last_hops_test() {
3494 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3495 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3496 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3497 let scorer = ln_test_utils::TestScorer::new();
3498 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3499 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3501 // Test handling of an empty RouteHint passed in Invoice.
3502 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3503 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3504 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3505 assert_eq!(route.paths[0].hops.len(), 5);
3507 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3508 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3509 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3510 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3511 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3512 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3514 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3515 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3516 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3517 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3518 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3519 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3521 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3522 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3523 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3524 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3525 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3526 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3528 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3529 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3530 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3531 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3532 // If we have a peer in the node map, we'll use their features here since we don't have
3533 // a way of figuring out their features from the invoice:
3534 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3535 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3537 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3538 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3539 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3540 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3541 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3542 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3545 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3547 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3548 let zero_fees = RoutingFees {
3550 proportional_millionths: 0,
3552 vec![RouteHint(vec![RouteHintHop {
3553 src_node_id: hint_hops[0],
3554 short_channel_id: 0xff00,
3557 proportional_millionths: 0,
3559 cltv_expiry_delta: (5 << 4) | 1,
3560 htlc_minimum_msat: None,
3561 htlc_maximum_msat: None,
3563 src_node_id: hint_hops[1],
3564 short_channel_id: 0xff01,
3566 cltv_expiry_delta: (8 << 4) | 1,
3567 htlc_minimum_msat: None,
3568 htlc_maximum_msat: None,
3573 fn multi_hint_last_hops_test() {
3574 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3575 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3576 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3577 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3578 let scorer = ln_test_utils::TestScorer::new();
3579 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3580 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3581 // Test through channels 2, 3, 0xff00, 0xff01.
3582 // Test shows that multiple hop hints are considered.
3584 // Disabling channels 6 & 7 by flags=2
3585 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3586 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3587 short_channel_id: 6,
3589 flags: 2, // to disable
3590 cltv_expiry_delta: 0,
3591 htlc_minimum_msat: 0,
3592 htlc_maximum_msat: MAX_VALUE_MSAT,
3594 fee_proportional_millionths: 0,
3595 excess_data: Vec::new()
3597 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3598 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3599 short_channel_id: 7,
3601 flags: 2, // to disable
3602 cltv_expiry_delta: 0,
3603 htlc_minimum_msat: 0,
3604 htlc_maximum_msat: MAX_VALUE_MSAT,
3606 fee_proportional_millionths: 0,
3607 excess_data: Vec::new()
3610 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3611 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3612 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3613 assert_eq!(route.paths[0].hops.len(), 4);
3615 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3616 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3617 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3618 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3619 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3620 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3622 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3623 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3624 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3625 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3626 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3627 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3629 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3630 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3631 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3632 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3633 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3634 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3636 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3637 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3638 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3639 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3640 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3641 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3645 fn private_multi_hint_last_hops_test() {
3646 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3647 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3649 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3650 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3652 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3653 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3654 let scorer = ln_test_utils::TestScorer::new();
3655 // Test through channels 2, 3, 0xff00, 0xff01.
3656 // Test shows that multiple hop hints are considered.
3658 // Disabling channels 6 & 7 by flags=2
3659 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3660 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3661 short_channel_id: 6,
3663 flags: 2, // to disable
3664 cltv_expiry_delta: 0,
3665 htlc_minimum_msat: 0,
3666 htlc_maximum_msat: MAX_VALUE_MSAT,
3668 fee_proportional_millionths: 0,
3669 excess_data: Vec::new()
3671 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3672 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3673 short_channel_id: 7,
3675 flags: 2, // to disable
3676 cltv_expiry_delta: 0,
3677 htlc_minimum_msat: 0,
3678 htlc_maximum_msat: MAX_VALUE_MSAT,
3680 fee_proportional_millionths: 0,
3681 excess_data: Vec::new()
3684 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3685 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3686 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
3687 assert_eq!(route.paths[0].hops.len(), 4);
3689 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3690 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3691 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3692 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3693 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3694 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3696 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3697 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3698 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3699 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3700 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3701 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3703 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3704 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3705 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3706 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3707 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3708 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3710 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3711 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3712 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3713 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3714 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3715 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3718 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3719 let zero_fees = RoutingFees {
3721 proportional_millionths: 0,
3723 vec![RouteHint(vec![RouteHintHop {
3724 src_node_id: nodes[4],
3725 short_channel_id: 11,
3727 cltv_expiry_delta: (11 << 4) | 1,
3728 htlc_minimum_msat: None,
3729 htlc_maximum_msat: None,
3731 src_node_id: nodes[3],
3732 short_channel_id: 8,
3734 cltv_expiry_delta: (8 << 4) | 1,
3735 htlc_minimum_msat: None,
3736 htlc_maximum_msat: None,
3737 }]), RouteHint(vec![RouteHintHop {
3738 src_node_id: nodes[4],
3739 short_channel_id: 9,
3742 proportional_millionths: 0,
3744 cltv_expiry_delta: (9 << 4) | 1,
3745 htlc_minimum_msat: None,
3746 htlc_maximum_msat: None,
3747 }]), RouteHint(vec![RouteHintHop {
3748 src_node_id: nodes[5],
3749 short_channel_id: 10,
3751 cltv_expiry_delta: (10 << 4) | 1,
3752 htlc_minimum_msat: None,
3753 htlc_maximum_msat: None,
3758 fn last_hops_with_public_channel_test() {
3759 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3760 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3761 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
3762 let scorer = ln_test_utils::TestScorer::new();
3763 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3764 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3765 // This test shows that public routes can be present in the invoice
3766 // which would be handled in the same manner.
3768 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3769 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3770 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3771 assert_eq!(route.paths[0].hops.len(), 5);
3773 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3774 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3775 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3776 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3777 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3778 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3780 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3781 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3782 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3783 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3784 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3785 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3787 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3788 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3789 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3790 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3791 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3792 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3794 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3795 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3796 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3797 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3798 // If we have a peer in the node map, we'll use their features here since we don't have
3799 // a way of figuring out their features from the invoice:
3800 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3801 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3803 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3804 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3805 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3806 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3807 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3808 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3812 fn our_chans_last_hop_connect_test() {
3813 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3814 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3815 let scorer = ln_test_utils::TestScorer::new();
3816 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3817 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3819 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3820 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3821 let mut last_hops = last_hops(&nodes);
3822 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3823 .with_route_hints(last_hops.clone()).unwrap();
3824 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3825 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3826 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3827 &Default::default(), &random_seed_bytes).unwrap();
3828 assert_eq!(route.paths[0].hops.len(), 2);
3830 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3831 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3832 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3833 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3834 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3835 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3837 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3838 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3839 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3840 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3841 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3842 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3844 last_hops[0].0[0].fees.base_msat = 1000;
3846 // Revert to via 6 as the fee on 8 goes up
3847 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3848 .with_route_hints(last_hops).unwrap();
3849 let route_params = RouteParameters::from_payment_params_and_value(
3850 payment_params.clone(), 100);
3851 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3852 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3853 assert_eq!(route.paths[0].hops.len(), 4);
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, 200); // fee increased as its % of value transferred across node
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, 100);
3865 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 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[5]);
3870 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3871 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3872 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3873 // If we have a peer in the node map, we'll use their features here since we don't have
3874 // a way of figuring out their features from the invoice:
3875 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3876 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3878 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3879 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3880 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3881 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3882 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3883 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3885 // ...but still use 8 for larger payments as 6 has a variable feerate
3886 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
3887 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3888 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3889 assert_eq!(route.paths[0].hops.len(), 5);
3891 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3892 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3893 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3894 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3895 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3896 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3898 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3899 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3900 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3901 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3902 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3903 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3905 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3906 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3907 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3908 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3909 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3910 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3912 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3913 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3914 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
3915 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3916 // If we have a peer in the node map, we'll use their features here since we don't have
3917 // a way of figuring out their features from the invoice:
3918 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3919 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3921 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3922 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3923 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
3924 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3925 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3926 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3929 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> {
3930 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).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());
3934 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3935 let last_hops = RouteHint(vec![RouteHintHop {
3936 src_node_id: middle_node_id,
3937 short_channel_id: 8,
3940 proportional_millionths: last_hop_fee_prop,
3942 cltv_expiry_delta: (8 << 4) | 1,
3943 htlc_minimum_msat: None,
3944 htlc_maximum_msat: last_hop_htlc_max,
3946 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
3947 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3948 let scorer = ln_test_utils::TestScorer::new();
3949 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3950 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3951 let logger = ln_test_utils::TestLogger::new();
3952 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3953 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
3954 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
3955 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
3956 &random_seed_bytes);
3961 fn unannounced_path_test() {
3962 // We should be able to send a payment to a destination without any help of a routing graph
3963 // if we have a channel with a common counterparty that appears in the first and last hop
3965 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3967 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3968 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3969 assert_eq!(route.paths[0].hops.len(), 2);
3971 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
3972 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3973 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
3974 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3975 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
3976 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3978 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
3979 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3980 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
3981 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3982 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3983 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3987 fn overflow_unannounced_path_test_liquidity_underflow() {
3988 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3989 // the last-hop had a fee which overflowed a u64, we'd panic.
3990 // This was due to us adding the first-hop from us unconditionally, causing us to think
3991 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3992 // In this test, we previously hit a subtraction underflow due to having less available
3993 // liquidity at the last hop than 0.
3994 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());
3998 fn overflow_unannounced_path_test_feerate_overflow() {
3999 // This tests for the same case as above, except instead of hitting a subtraction
4000 // underflow, we hit a case where the fee charged at a hop overflowed.
4001 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());
4005 fn available_amount_while_routing_test() {
4006 // Tests whether we choose the correct available channel amount while routing.
4008 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4009 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4010 let scorer = ln_test_utils::TestScorer::new();
4011 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4012 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4013 let config = UserConfig::default();
4014 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4016 // We will use a simple single-path route from
4017 // our node to node2 via node0: channels {1, 3}.
4019 // First disable all other paths.
4020 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4021 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4022 short_channel_id: 2,
4025 cltv_expiry_delta: 0,
4026 htlc_minimum_msat: 0,
4027 htlc_maximum_msat: 100_000,
4029 fee_proportional_millionths: 0,
4030 excess_data: Vec::new()
4032 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4033 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4034 short_channel_id: 12,
4037 cltv_expiry_delta: 0,
4038 htlc_minimum_msat: 0,
4039 htlc_maximum_msat: 100_000,
4041 fee_proportional_millionths: 0,
4042 excess_data: Vec::new()
4045 // Make the first channel (#1) very permissive,
4046 // and we will be testing all limits on the second channel.
4047 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4048 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4049 short_channel_id: 1,
4052 cltv_expiry_delta: 0,
4053 htlc_minimum_msat: 0,
4054 htlc_maximum_msat: 1_000_000_000,
4056 fee_proportional_millionths: 0,
4057 excess_data: Vec::new()
4060 // First, let's see if routing works if we have absolutely no idea about the available amount.
4061 // In this case, it should be set to 250_000 sats.
4062 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4063 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4064 short_channel_id: 3,
4067 cltv_expiry_delta: 0,
4068 htlc_minimum_msat: 0,
4069 htlc_maximum_msat: 250_000_000,
4071 fee_proportional_millionths: 0,
4072 excess_data: Vec::new()
4076 // Attempt to route more than available results in a failure.
4077 let route_params = RouteParameters::from_payment_params_and_value(
4078 payment_params.clone(), 250_000_001);
4079 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4080 &our_id, &route_params, &network_graph.read_only(), None,
4081 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4082 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4083 } else { panic!(); }
4087 // Now, attempt to route an exact amount we have should be fine.
4088 let route_params = RouteParameters::from_payment_params_and_value(
4089 payment_params.clone(), 250_000_000);
4090 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4091 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4092 assert_eq!(route.paths.len(), 1);
4093 let path = route.paths.last().unwrap();
4094 assert_eq!(path.hops.len(), 2);
4095 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4096 assert_eq!(path.final_value_msat(), 250_000_000);
4099 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4100 // Disable channel #1 and use another first hop.
4101 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4102 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4103 short_channel_id: 1,
4106 cltv_expiry_delta: 0,
4107 htlc_minimum_msat: 0,
4108 htlc_maximum_msat: 1_000_000_000,
4110 fee_proportional_millionths: 0,
4111 excess_data: Vec::new()
4114 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4115 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4118 // Attempt to route more than available results in a failure.
4119 let route_params = RouteParameters::from_payment_params_and_value(
4120 payment_params.clone(), 200_000_001);
4121 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4122 &our_id, &route_params, &network_graph.read_only(),
4123 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4124 &Default::default(), &random_seed_bytes) {
4125 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4126 } else { panic!(); }
4130 // Now, attempt to route an exact amount we have should be fine.
4131 let route_params = RouteParameters::from_payment_params_and_value(
4132 payment_params.clone(), 200_000_000);
4133 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4134 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4135 &Default::default(), &random_seed_bytes).unwrap();
4136 assert_eq!(route.paths.len(), 1);
4137 let path = route.paths.last().unwrap();
4138 assert_eq!(path.hops.len(), 2);
4139 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4140 assert_eq!(path.final_value_msat(), 200_000_000);
4143 // Enable channel #1 back.
4144 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4145 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4146 short_channel_id: 1,
4149 cltv_expiry_delta: 0,
4150 htlc_minimum_msat: 0,
4151 htlc_maximum_msat: 1_000_000_000,
4153 fee_proportional_millionths: 0,
4154 excess_data: Vec::new()
4158 // Now let's see if routing works if we know only htlc_maximum_msat.
4159 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4160 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4161 short_channel_id: 3,
4164 cltv_expiry_delta: 0,
4165 htlc_minimum_msat: 0,
4166 htlc_maximum_msat: 15_000,
4168 fee_proportional_millionths: 0,
4169 excess_data: Vec::new()
4173 // Attempt to route more than available results in a failure.
4174 let route_params = RouteParameters::from_payment_params_and_value(
4175 payment_params.clone(), 15_001);
4176 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4177 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4178 &scorer, &Default::default(), &random_seed_bytes) {
4179 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4180 } else { panic!(); }
4184 // Now, attempt to route an exact amount we have should be fine.
4185 let route_params = RouteParameters::from_payment_params_and_value(
4186 payment_params.clone(), 15_000);
4187 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4188 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4189 assert_eq!(route.paths.len(), 1);
4190 let path = route.paths.last().unwrap();
4191 assert_eq!(path.hops.len(), 2);
4192 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4193 assert_eq!(path.final_value_msat(), 15_000);
4196 // Now let's see if routing works if we know only capacity from the UTXO.
4198 // We can't change UTXO capacity on the fly, so we'll disable
4199 // the existing channel and add another one with the capacity we need.
4200 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4201 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4202 short_channel_id: 3,
4205 cltv_expiry_delta: 0,
4206 htlc_minimum_msat: 0,
4207 htlc_maximum_msat: MAX_VALUE_MSAT,
4209 fee_proportional_millionths: 0,
4210 excess_data: Vec::new()
4213 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4214 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4215 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4216 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4217 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4219 *chain_monitor.utxo_ret.lock().unwrap() =
4220 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4221 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4223 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4224 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4225 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4226 short_channel_id: 333,
4229 cltv_expiry_delta: (3 << 4) | 1,
4230 htlc_minimum_msat: 0,
4231 htlc_maximum_msat: 15_000,
4233 fee_proportional_millionths: 0,
4234 excess_data: Vec::new()
4236 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4237 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4238 short_channel_id: 333,
4241 cltv_expiry_delta: (3 << 4) | 2,
4242 htlc_minimum_msat: 0,
4243 htlc_maximum_msat: 15_000,
4245 fee_proportional_millionths: 0,
4246 excess_data: Vec::new()
4250 // Attempt to route more than available results in a failure.
4251 let route_params = RouteParameters::from_payment_params_and_value(
4252 payment_params.clone(), 15_001);
4253 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4254 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4255 &scorer, &Default::default(), &random_seed_bytes) {
4256 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4257 } else { panic!(); }
4261 // Now, attempt to route an exact amount we have should be fine.
4262 let route_params = RouteParameters::from_payment_params_and_value(
4263 payment_params.clone(), 15_000);
4264 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4265 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4266 assert_eq!(route.paths.len(), 1);
4267 let path = route.paths.last().unwrap();
4268 assert_eq!(path.hops.len(), 2);
4269 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4270 assert_eq!(path.final_value_msat(), 15_000);
4273 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4274 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4275 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4276 short_channel_id: 333,
4279 cltv_expiry_delta: 0,
4280 htlc_minimum_msat: 0,
4281 htlc_maximum_msat: 10_000,
4283 fee_proportional_millionths: 0,
4284 excess_data: Vec::new()
4288 // Attempt to route more than available results in a failure.
4289 let route_params = RouteParameters::from_payment_params_and_value(
4290 payment_params.clone(), 10_001);
4291 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4292 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4293 &scorer, &Default::default(), &random_seed_bytes) {
4294 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4295 } else { panic!(); }
4299 // Now, attempt to route an exact amount we have should be fine.
4300 let route_params = RouteParameters::from_payment_params_and_value(
4301 payment_params.clone(), 10_000);
4302 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4303 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4304 assert_eq!(route.paths.len(), 1);
4305 let path = route.paths.last().unwrap();
4306 assert_eq!(path.hops.len(), 2);
4307 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4308 assert_eq!(path.final_value_msat(), 10_000);
4313 fn available_liquidity_last_hop_test() {
4314 // Check that available liquidity properly limits the path even when only
4315 // one of the latter hops is limited.
4316 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4317 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4318 let scorer = ln_test_utils::TestScorer::new();
4319 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4320 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4321 let config = UserConfig::default();
4322 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4324 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4325 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4326 // Total capacity: 50 sats.
4328 // Disable other potential paths.
4329 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4330 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4331 short_channel_id: 2,
4334 cltv_expiry_delta: 0,
4335 htlc_minimum_msat: 0,
4336 htlc_maximum_msat: 100_000,
4338 fee_proportional_millionths: 0,
4339 excess_data: Vec::new()
4341 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4342 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4343 short_channel_id: 7,
4346 cltv_expiry_delta: 0,
4347 htlc_minimum_msat: 0,
4348 htlc_maximum_msat: 100_000,
4350 fee_proportional_millionths: 0,
4351 excess_data: Vec::new()
4356 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4357 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4358 short_channel_id: 12,
4361 cltv_expiry_delta: 0,
4362 htlc_minimum_msat: 0,
4363 htlc_maximum_msat: 100_000,
4365 fee_proportional_millionths: 0,
4366 excess_data: Vec::new()
4368 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4370 short_channel_id: 13,
4373 cltv_expiry_delta: 0,
4374 htlc_minimum_msat: 0,
4375 htlc_maximum_msat: 100_000,
4377 fee_proportional_millionths: 0,
4378 excess_data: Vec::new()
4381 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4382 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4383 short_channel_id: 6,
4386 cltv_expiry_delta: 0,
4387 htlc_minimum_msat: 0,
4388 htlc_maximum_msat: 50_000,
4390 fee_proportional_millionths: 0,
4391 excess_data: Vec::new()
4393 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4394 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4395 short_channel_id: 11,
4398 cltv_expiry_delta: 0,
4399 htlc_minimum_msat: 0,
4400 htlc_maximum_msat: 100_000,
4402 fee_proportional_millionths: 0,
4403 excess_data: Vec::new()
4406 // Attempt to route more than available results in a failure.
4407 let route_params = RouteParameters::from_payment_params_and_value(
4408 payment_params.clone(), 60_000);
4409 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4410 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4411 &scorer, &Default::default(), &random_seed_bytes) {
4412 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4413 } else { panic!(); }
4417 // Now, attempt to route 49 sats (just a bit below the capacity).
4418 let route_params = RouteParameters::from_payment_params_and_value(
4419 payment_params.clone(), 49_000);
4420 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4421 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4422 assert_eq!(route.paths.len(), 1);
4423 let mut total_amount_paid_msat = 0;
4424 for path in &route.paths {
4425 assert_eq!(path.hops.len(), 4);
4426 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4427 total_amount_paid_msat += path.final_value_msat();
4429 assert_eq!(total_amount_paid_msat, 49_000);
4433 // Attempt to route an exact amount is also fine
4434 let route_params = RouteParameters::from_payment_params_and_value(
4435 payment_params, 50_000);
4436 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4437 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4438 assert_eq!(route.paths.len(), 1);
4439 let mut total_amount_paid_msat = 0;
4440 for path in &route.paths {
4441 assert_eq!(path.hops.len(), 4);
4442 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4443 total_amount_paid_msat += path.final_value_msat();
4445 assert_eq!(total_amount_paid_msat, 50_000);
4450 fn ignore_fee_first_hop_test() {
4451 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4452 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4453 let scorer = ln_test_utils::TestScorer::new();
4454 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4455 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4456 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4458 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4459 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4460 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4461 short_channel_id: 1,
4464 cltv_expiry_delta: 0,
4465 htlc_minimum_msat: 0,
4466 htlc_maximum_msat: 100_000,
4467 fee_base_msat: 1_000_000,
4468 fee_proportional_millionths: 0,
4469 excess_data: Vec::new()
4471 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4472 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4473 short_channel_id: 3,
4476 cltv_expiry_delta: 0,
4477 htlc_minimum_msat: 0,
4478 htlc_maximum_msat: 50_000,
4480 fee_proportional_millionths: 0,
4481 excess_data: Vec::new()
4485 let route_params = RouteParameters::from_payment_params_and_value(
4486 payment_params, 50_000);
4487 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4488 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4489 assert_eq!(route.paths.len(), 1);
4490 let mut total_amount_paid_msat = 0;
4491 for path in &route.paths {
4492 assert_eq!(path.hops.len(), 2);
4493 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4494 total_amount_paid_msat += path.final_value_msat();
4496 assert_eq!(total_amount_paid_msat, 50_000);
4501 fn simple_mpp_route_test() {
4502 let (secp_ctx, _, _, _, _) = build_graph();
4503 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4504 let config = UserConfig::default();
4505 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4506 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4507 do_simple_mpp_route_test(clear_payment_params);
4509 // MPP to a 1-hop blinded path for nodes[2]
4510 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
4511 let blinded_path = BlindedPath {
4512 introduction_node_id: nodes[2],
4513 blinding_point: ln_test_utils::pubkey(42),
4514 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4516 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4518 fee_proportional_millionths: 0,
4519 htlc_minimum_msat: 0,
4520 htlc_maximum_msat: 0,
4521 cltv_expiry_delta: 0,
4522 features: BlindedHopFeatures::empty(),
4524 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4525 .with_bolt12_features(bolt12_features.clone()).unwrap();
4526 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4528 // MPP to 3 2-hop blinded paths
4529 let mut blinded_path_node_0 = blinded_path.clone();
4530 blinded_path_node_0.introduction_node_id = nodes[0];
4531 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4532 let mut node_0_payinfo = blinded_payinfo.clone();
4533 node_0_payinfo.htlc_maximum_msat = 50_000;
4535 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4536 blinded_path_node_7.introduction_node_id = nodes[7];
4537 let mut node_7_payinfo = blinded_payinfo.clone();
4538 node_7_payinfo.htlc_maximum_msat = 60_000;
4540 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4541 blinded_path_node_1.introduction_node_id = nodes[1];
4542 let mut node_1_payinfo = blinded_payinfo.clone();
4543 node_1_payinfo.htlc_maximum_msat = 180_000;
4545 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4547 (node_0_payinfo, blinded_path_node_0),
4548 (node_7_payinfo, blinded_path_node_7),
4549 (node_1_payinfo, blinded_path_node_1)
4551 .with_bolt12_features(bolt12_features).unwrap();
4552 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4556 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4557 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4558 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4559 let scorer = ln_test_utils::TestScorer::new();
4560 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4561 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4563 // We need a route consisting of 3 paths:
4564 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4565 // To achieve this, the amount being transferred should be around
4566 // the total capacity of these 3 paths.
4568 // First, we set limits on these (previously unlimited) channels.
4569 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4571 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4572 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4573 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4574 short_channel_id: 1,
4577 cltv_expiry_delta: 0,
4578 htlc_minimum_msat: 0,
4579 htlc_maximum_msat: 100_000,
4581 fee_proportional_millionths: 0,
4582 excess_data: Vec::new()
4584 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4585 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4586 short_channel_id: 3,
4589 cltv_expiry_delta: 0,
4590 htlc_minimum_msat: 0,
4591 htlc_maximum_msat: 50_000,
4593 fee_proportional_millionths: 0,
4594 excess_data: Vec::new()
4597 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4598 // (total limit 60).
4599 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4600 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4601 short_channel_id: 12,
4604 cltv_expiry_delta: 0,
4605 htlc_minimum_msat: 0,
4606 htlc_maximum_msat: 60_000,
4608 fee_proportional_millionths: 0,
4609 excess_data: Vec::new()
4611 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4612 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4613 short_channel_id: 13,
4616 cltv_expiry_delta: 0,
4617 htlc_minimum_msat: 0,
4618 htlc_maximum_msat: 60_000,
4620 fee_proportional_millionths: 0,
4621 excess_data: Vec::new()
4624 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4625 // (total capacity 180 sats).
4626 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4627 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4628 short_channel_id: 2,
4631 cltv_expiry_delta: 0,
4632 htlc_minimum_msat: 0,
4633 htlc_maximum_msat: 200_000,
4635 fee_proportional_millionths: 0,
4636 excess_data: Vec::new()
4638 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4639 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4640 short_channel_id: 4,
4643 cltv_expiry_delta: 0,
4644 htlc_minimum_msat: 0,
4645 htlc_maximum_msat: 180_000,
4647 fee_proportional_millionths: 0,
4648 excess_data: Vec::new()
4652 // Attempt to route more than available results in a failure.
4653 let route_params = RouteParameters::from_payment_params_and_value(
4654 payment_params.clone(), 300_000);
4655 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4656 &our_id, &route_params, &network_graph.read_only(), None,
4657 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4658 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4659 } else { panic!(); }
4663 // Attempt to route while setting max_path_count to 0 results in a failure.
4664 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4665 let route_params = RouteParameters::from_payment_params_and_value(
4666 zero_payment_params, 100);
4667 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4668 &our_id, &route_params, &network_graph.read_only(), None,
4669 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4670 assert_eq!(err, "Can't find a route with no paths allowed.");
4671 } else { panic!(); }
4675 // Attempt to route while setting max_path_count to 3 results in a failure.
4676 // This is the case because the minimal_value_contribution_msat would require each path
4677 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4678 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4679 let route_params = RouteParameters::from_payment_params_and_value(
4680 fail_payment_params, 250_000);
4681 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4682 &our_id, &route_params, &network_graph.read_only(), None,
4683 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4684 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4685 } else { panic!(); }
4689 // Now, attempt to route 250 sats (just a bit below the capacity).
4690 // Our algorithm should provide us with these 3 paths.
4691 let route_params = RouteParameters::from_payment_params_and_value(
4692 payment_params.clone(), 250_000);
4693 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4694 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4695 assert_eq!(route.paths.len(), 3);
4696 let mut total_amount_paid_msat = 0;
4697 for path in &route.paths {
4698 if let Some(bt) = &path.blinded_tail {
4699 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4701 assert_eq!(path.hops.len(), 2);
4702 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4704 total_amount_paid_msat += path.final_value_msat();
4706 assert_eq!(total_amount_paid_msat, 250_000);
4710 // Attempt to route an exact amount is also fine
4711 let route_params = RouteParameters::from_payment_params_and_value(
4712 payment_params.clone(), 290_000);
4713 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4714 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4715 assert_eq!(route.paths.len(), 3);
4716 let mut total_amount_paid_msat = 0;
4717 for path in &route.paths {
4718 if payment_params.payee.blinded_route_hints().len() != 0 {
4719 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
4720 if let Some(bt) = &path.blinded_tail {
4721 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4722 if bt.hops.len() > 1 {
4723 assert_eq!(path.hops.last().unwrap().pubkey,
4724 payment_params.payee.blinded_route_hints().iter()
4725 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
4726 .map(|(_, p)| p.introduction_node_id).unwrap());
4728 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4731 assert_eq!(path.hops.len(), 2);
4732 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4734 total_amount_paid_msat += path.final_value_msat();
4736 assert_eq!(total_amount_paid_msat, 290_000);
4741 fn long_mpp_route_test() {
4742 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4743 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4744 let scorer = ln_test_utils::TestScorer::new();
4745 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4746 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4747 let config = UserConfig::default();
4748 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4749 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4751 // We need a route consisting of 3 paths:
4752 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4753 // Note that these paths overlap (channels 5, 12, 13).
4754 // We will route 300 sats.
4755 // Each path will have 100 sats capacity, those channels which
4756 // are used twice will have 200 sats capacity.
4758 // Disable other potential paths.
4759 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4760 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4761 short_channel_id: 2,
4764 cltv_expiry_delta: 0,
4765 htlc_minimum_msat: 0,
4766 htlc_maximum_msat: 100_000,
4768 fee_proportional_millionths: 0,
4769 excess_data: Vec::new()
4771 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4772 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4773 short_channel_id: 7,
4776 cltv_expiry_delta: 0,
4777 htlc_minimum_msat: 0,
4778 htlc_maximum_msat: 100_000,
4780 fee_proportional_millionths: 0,
4781 excess_data: Vec::new()
4784 // Path via {node0, node2} is channels {1, 3, 5}.
4785 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4786 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4787 short_channel_id: 1,
4790 cltv_expiry_delta: 0,
4791 htlc_minimum_msat: 0,
4792 htlc_maximum_msat: 100_000,
4794 fee_proportional_millionths: 0,
4795 excess_data: Vec::new()
4797 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4798 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4799 short_channel_id: 3,
4802 cltv_expiry_delta: 0,
4803 htlc_minimum_msat: 0,
4804 htlc_maximum_msat: 100_000,
4806 fee_proportional_millionths: 0,
4807 excess_data: Vec::new()
4810 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4811 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4812 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4813 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4814 short_channel_id: 5,
4817 cltv_expiry_delta: 0,
4818 htlc_minimum_msat: 0,
4819 htlc_maximum_msat: 200_000,
4821 fee_proportional_millionths: 0,
4822 excess_data: Vec::new()
4825 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4826 // Add 100 sats to the capacities of {12, 13}, because these channels
4827 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4828 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4829 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4830 short_channel_id: 12,
4833 cltv_expiry_delta: 0,
4834 htlc_minimum_msat: 0,
4835 htlc_maximum_msat: 200_000,
4837 fee_proportional_millionths: 0,
4838 excess_data: Vec::new()
4840 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4841 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4842 short_channel_id: 13,
4845 cltv_expiry_delta: 0,
4846 htlc_minimum_msat: 0,
4847 htlc_maximum_msat: 200_000,
4849 fee_proportional_millionths: 0,
4850 excess_data: Vec::new()
4853 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4854 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4855 short_channel_id: 6,
4858 cltv_expiry_delta: 0,
4859 htlc_minimum_msat: 0,
4860 htlc_maximum_msat: 100_000,
4862 fee_proportional_millionths: 0,
4863 excess_data: Vec::new()
4865 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4866 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4867 short_channel_id: 11,
4870 cltv_expiry_delta: 0,
4871 htlc_minimum_msat: 0,
4872 htlc_maximum_msat: 100_000,
4874 fee_proportional_millionths: 0,
4875 excess_data: Vec::new()
4878 // Path via {node7, node2} is channels {12, 13, 5}.
4879 // We already limited them to 200 sats (they are used twice for 100 sats).
4880 // Nothing to do here.
4883 // Attempt to route more than available results in a failure.
4884 let route_params = RouteParameters::from_payment_params_and_value(
4885 payment_params.clone(), 350_000);
4886 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4887 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4888 &scorer, &Default::default(), &random_seed_bytes) {
4889 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4890 } else { panic!(); }
4894 // Now, attempt to route 300 sats (exact amount we can route).
4895 // Our algorithm should provide us with these 3 paths, 100 sats each.
4896 let route_params = RouteParameters::from_payment_params_and_value(
4897 payment_params, 300_000);
4898 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4899 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4900 assert_eq!(route.paths.len(), 3);
4902 let mut total_amount_paid_msat = 0;
4903 for path in &route.paths {
4904 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4905 total_amount_paid_msat += path.final_value_msat();
4907 assert_eq!(total_amount_paid_msat, 300_000);
4913 fn mpp_cheaper_route_test() {
4914 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4915 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4916 let scorer = ln_test_utils::TestScorer::new();
4917 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4918 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4919 let config = UserConfig::default();
4920 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4922 // This test checks that if we have two cheaper paths and one more expensive path,
4923 // so that liquidity-wise any 2 of 3 combination is sufficient,
4924 // two cheaper paths will be taken.
4925 // These paths have equal available liquidity.
4927 // We need a combination of 3 paths:
4928 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4929 // Note that these paths overlap (channels 5, 12, 13).
4930 // Each path will have 100 sats capacity, those channels which
4931 // are used twice will have 200 sats capacity.
4933 // Disable other potential paths.
4934 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4935 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4936 short_channel_id: 2,
4939 cltv_expiry_delta: 0,
4940 htlc_minimum_msat: 0,
4941 htlc_maximum_msat: 100_000,
4943 fee_proportional_millionths: 0,
4944 excess_data: Vec::new()
4946 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4947 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4948 short_channel_id: 7,
4951 cltv_expiry_delta: 0,
4952 htlc_minimum_msat: 0,
4953 htlc_maximum_msat: 100_000,
4955 fee_proportional_millionths: 0,
4956 excess_data: Vec::new()
4959 // Path via {node0, node2} is channels {1, 3, 5}.
4960 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4961 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4962 short_channel_id: 1,
4965 cltv_expiry_delta: 0,
4966 htlc_minimum_msat: 0,
4967 htlc_maximum_msat: 100_000,
4969 fee_proportional_millionths: 0,
4970 excess_data: Vec::new()
4972 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4973 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4974 short_channel_id: 3,
4977 cltv_expiry_delta: 0,
4978 htlc_minimum_msat: 0,
4979 htlc_maximum_msat: 100_000,
4981 fee_proportional_millionths: 0,
4982 excess_data: Vec::new()
4985 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4986 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4987 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4988 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4989 short_channel_id: 5,
4992 cltv_expiry_delta: 0,
4993 htlc_minimum_msat: 0,
4994 htlc_maximum_msat: 200_000,
4996 fee_proportional_millionths: 0,
4997 excess_data: Vec::new()
5000 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5001 // Add 100 sats to the capacities of {12, 13}, because these channels
5002 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5003 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5004 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5005 short_channel_id: 12,
5008 cltv_expiry_delta: 0,
5009 htlc_minimum_msat: 0,
5010 htlc_maximum_msat: 200_000,
5012 fee_proportional_millionths: 0,
5013 excess_data: Vec::new()
5015 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5016 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5017 short_channel_id: 13,
5020 cltv_expiry_delta: 0,
5021 htlc_minimum_msat: 0,
5022 htlc_maximum_msat: 200_000,
5024 fee_proportional_millionths: 0,
5025 excess_data: Vec::new()
5028 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5029 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5030 short_channel_id: 6,
5033 cltv_expiry_delta: 0,
5034 htlc_minimum_msat: 0,
5035 htlc_maximum_msat: 100_000,
5036 fee_base_msat: 1_000,
5037 fee_proportional_millionths: 0,
5038 excess_data: Vec::new()
5040 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5041 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5042 short_channel_id: 11,
5045 cltv_expiry_delta: 0,
5046 htlc_minimum_msat: 0,
5047 htlc_maximum_msat: 100_000,
5049 fee_proportional_millionths: 0,
5050 excess_data: Vec::new()
5053 // Path via {node7, node2} is channels {12, 13, 5}.
5054 // We already limited them to 200 sats (they are used twice for 100 sats).
5055 // Nothing to do here.
5058 // Now, attempt to route 180 sats.
5059 // Our algorithm should provide us with these 2 paths.
5060 let route_params = RouteParameters::from_payment_params_and_value(
5061 payment_params, 180_000);
5062 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5063 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5064 assert_eq!(route.paths.len(), 2);
5066 let mut total_value_transferred_msat = 0;
5067 let mut total_paid_msat = 0;
5068 for path in &route.paths {
5069 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5070 total_value_transferred_msat += path.final_value_msat();
5071 for hop in &path.hops {
5072 total_paid_msat += hop.fee_msat;
5075 // If we paid fee, this would be higher.
5076 assert_eq!(total_value_transferred_msat, 180_000);
5077 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5078 assert_eq!(total_fees_paid, 0);
5083 fn fees_on_mpp_route_test() {
5084 // This test makes sure that MPP algorithm properly takes into account
5085 // fees charged on the channels, by making the fees impactful:
5086 // if the fee is not properly accounted for, the behavior is different.
5087 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5088 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5089 let scorer = ln_test_utils::TestScorer::new();
5090 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5091 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5092 let config = UserConfig::default();
5093 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5095 // We need a route consisting of 2 paths:
5096 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5097 // We will route 200 sats, Each path will have 100 sats capacity.
5099 // This test is not particularly stable: e.g.,
5100 // there's a way to route via {node0, node2, node4}.
5101 // It works while pathfinding is deterministic, but can be broken otherwise.
5102 // It's fine to ignore this concern for now.
5104 // Disable other potential paths.
5105 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5106 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5107 short_channel_id: 2,
5110 cltv_expiry_delta: 0,
5111 htlc_minimum_msat: 0,
5112 htlc_maximum_msat: 100_000,
5114 fee_proportional_millionths: 0,
5115 excess_data: Vec::new()
5118 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5119 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5120 short_channel_id: 7,
5123 cltv_expiry_delta: 0,
5124 htlc_minimum_msat: 0,
5125 htlc_maximum_msat: 100_000,
5127 fee_proportional_millionths: 0,
5128 excess_data: Vec::new()
5131 // Path via {node0, node2} is channels {1, 3, 5}.
5132 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5133 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5134 short_channel_id: 1,
5137 cltv_expiry_delta: 0,
5138 htlc_minimum_msat: 0,
5139 htlc_maximum_msat: 100_000,
5141 fee_proportional_millionths: 0,
5142 excess_data: Vec::new()
5144 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5145 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5146 short_channel_id: 3,
5149 cltv_expiry_delta: 0,
5150 htlc_minimum_msat: 0,
5151 htlc_maximum_msat: 100_000,
5153 fee_proportional_millionths: 0,
5154 excess_data: Vec::new()
5157 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5158 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5159 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5160 short_channel_id: 5,
5163 cltv_expiry_delta: 0,
5164 htlc_minimum_msat: 0,
5165 htlc_maximum_msat: 100_000,
5167 fee_proportional_millionths: 0,
5168 excess_data: Vec::new()
5171 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5172 // All channels should be 100 sats capacity. But for the fee experiment,
5173 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5174 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5175 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5176 // so no matter how large are other channels,
5177 // the whole path will be limited by 100 sats with just these 2 conditions:
5178 // - channel 12 capacity is 250 sats
5179 // - fee for channel 6 is 150 sats
5180 // Let's test this by enforcing these 2 conditions and removing other limits.
5181 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5182 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5183 short_channel_id: 12,
5186 cltv_expiry_delta: 0,
5187 htlc_minimum_msat: 0,
5188 htlc_maximum_msat: 250_000,
5190 fee_proportional_millionths: 0,
5191 excess_data: Vec::new()
5193 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5194 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5195 short_channel_id: 13,
5198 cltv_expiry_delta: 0,
5199 htlc_minimum_msat: 0,
5200 htlc_maximum_msat: MAX_VALUE_MSAT,
5202 fee_proportional_millionths: 0,
5203 excess_data: Vec::new()
5206 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5207 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5208 short_channel_id: 6,
5211 cltv_expiry_delta: 0,
5212 htlc_minimum_msat: 0,
5213 htlc_maximum_msat: MAX_VALUE_MSAT,
5214 fee_base_msat: 150_000,
5215 fee_proportional_millionths: 0,
5216 excess_data: Vec::new()
5218 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5219 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5220 short_channel_id: 11,
5223 cltv_expiry_delta: 0,
5224 htlc_minimum_msat: 0,
5225 htlc_maximum_msat: MAX_VALUE_MSAT,
5227 fee_proportional_millionths: 0,
5228 excess_data: Vec::new()
5232 // Attempt to route more than available results in a failure.
5233 let route_params = RouteParameters::from_payment_params_and_value(
5234 payment_params.clone(), 210_000);
5235 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5236 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5237 &scorer, &Default::default(), &random_seed_bytes) {
5238 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5239 } else { panic!(); }
5243 // Now, attempt to route 200 sats (exact amount we can route).
5244 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 200_000);
5245 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5246 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5247 assert_eq!(route.paths.len(), 2);
5249 let mut total_amount_paid_msat = 0;
5250 for path in &route.paths {
5251 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5252 total_amount_paid_msat += path.final_value_msat();
5254 assert_eq!(total_amount_paid_msat, 200_000);
5255 assert_eq!(route.get_total_fees(), 150_000);
5260 fn mpp_with_last_hops() {
5261 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5262 // via a single last-hop route hint, we'd fail to route if we first collected routes
5263 // totaling close but not quite enough to fund the full payment.
5265 // This was because we considered last-hop hints to have exactly the sought payment amount
5266 // instead of the amount we were trying to collect, needlessly limiting our path searching
5267 // at the very first hop.
5269 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5270 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5271 // to only have the remaining to-collect amount in available liquidity.
5273 // This bug appeared in production in some specific channel configurations.
5274 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5275 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5276 let scorer = ln_test_utils::TestScorer::new();
5277 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5278 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5279 let config = UserConfig::default();
5280 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5281 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5282 src_node_id: nodes[2],
5283 short_channel_id: 42,
5284 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5285 cltv_expiry_delta: 42,
5286 htlc_minimum_msat: None,
5287 htlc_maximum_msat: None,
5288 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5290 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5291 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5292 // would first use the no-fee route and then fail to find a path along the second route as
5293 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5294 // under 5% of our payment amount.
5295 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5296 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5297 short_channel_id: 1,
5300 cltv_expiry_delta: (5 << 4) | 5,
5301 htlc_minimum_msat: 0,
5302 htlc_maximum_msat: 99_000,
5303 fee_base_msat: u32::max_value(),
5304 fee_proportional_millionths: u32::max_value(),
5305 excess_data: Vec::new()
5307 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5308 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5309 short_channel_id: 2,
5312 cltv_expiry_delta: (5 << 4) | 3,
5313 htlc_minimum_msat: 0,
5314 htlc_maximum_msat: 99_000,
5315 fee_base_msat: u32::max_value(),
5316 fee_proportional_millionths: u32::max_value(),
5317 excess_data: Vec::new()
5319 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5320 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5321 short_channel_id: 4,
5324 cltv_expiry_delta: (4 << 4) | 1,
5325 htlc_minimum_msat: 0,
5326 htlc_maximum_msat: MAX_VALUE_MSAT,
5328 fee_proportional_millionths: 0,
5329 excess_data: Vec::new()
5331 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5332 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5333 short_channel_id: 13,
5335 flags: 0|2, // Channel disabled
5336 cltv_expiry_delta: (13 << 4) | 1,
5337 htlc_minimum_msat: 0,
5338 htlc_maximum_msat: MAX_VALUE_MSAT,
5340 fee_proportional_millionths: 2000000,
5341 excess_data: Vec::new()
5344 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5346 let route_params = RouteParameters::from_payment_params_and_value(
5347 payment_params, 100_000);
5348 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5349 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5350 assert_eq!(route.paths.len(), 2);
5351 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5352 // Paths are manually ordered ordered by SCID, so:
5353 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5354 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5355 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5356 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5357 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5358 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5359 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5360 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5361 assert_eq!(route.get_total_fees(), 1);
5362 assert_eq!(route.get_total_amount(), 100_000);
5366 fn drop_lowest_channel_mpp_route_test() {
5367 // This test checks that low-capacity channel is dropped when after
5368 // path finding we realize that we found more capacity than we need.
5369 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5370 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5371 let scorer = ln_test_utils::TestScorer::new();
5372 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5373 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5374 let config = UserConfig::default();
5375 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5376 .with_max_channel_saturation_power_of_half(0);
5378 // We need a route consisting of 3 paths:
5379 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5381 // The first and the second paths should be sufficient, but the third should be
5382 // cheaper, so that we select it but drop later.
5384 // First, we set limits on these (previously unlimited) channels.
5385 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5387 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5388 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5389 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5390 short_channel_id: 1,
5393 cltv_expiry_delta: 0,
5394 htlc_minimum_msat: 0,
5395 htlc_maximum_msat: 100_000,
5397 fee_proportional_millionths: 0,
5398 excess_data: Vec::new()
5400 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5401 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5402 short_channel_id: 3,
5405 cltv_expiry_delta: 0,
5406 htlc_minimum_msat: 0,
5407 htlc_maximum_msat: 50_000,
5409 fee_proportional_millionths: 0,
5410 excess_data: Vec::new()
5413 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5414 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5415 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5416 short_channel_id: 12,
5419 cltv_expiry_delta: 0,
5420 htlc_minimum_msat: 0,
5421 htlc_maximum_msat: 60_000,
5423 fee_proportional_millionths: 0,
5424 excess_data: Vec::new()
5426 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5427 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5428 short_channel_id: 13,
5431 cltv_expiry_delta: 0,
5432 htlc_minimum_msat: 0,
5433 htlc_maximum_msat: 60_000,
5435 fee_proportional_millionths: 0,
5436 excess_data: Vec::new()
5439 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5440 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5441 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5442 short_channel_id: 2,
5445 cltv_expiry_delta: 0,
5446 htlc_minimum_msat: 0,
5447 htlc_maximum_msat: 20_000,
5449 fee_proportional_millionths: 0,
5450 excess_data: Vec::new()
5452 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5453 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5454 short_channel_id: 4,
5457 cltv_expiry_delta: 0,
5458 htlc_minimum_msat: 0,
5459 htlc_maximum_msat: 20_000,
5461 fee_proportional_millionths: 0,
5462 excess_data: Vec::new()
5466 // Attempt to route more than available results in a failure.
5467 let route_params = RouteParameters::from_payment_params_and_value(
5468 payment_params.clone(), 150_000);
5469 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5470 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5471 &scorer, &Default::default(), &random_seed_bytes) {
5472 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5473 } else { panic!(); }
5477 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5478 // Our algorithm should provide us with these 3 paths.
5479 let route_params = RouteParameters::from_payment_params_and_value(
5480 payment_params.clone(), 125_000);
5481 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5482 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5483 assert_eq!(route.paths.len(), 3);
5484 let mut total_amount_paid_msat = 0;
5485 for path in &route.paths {
5486 assert_eq!(path.hops.len(), 2);
5487 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5488 total_amount_paid_msat += path.final_value_msat();
5490 assert_eq!(total_amount_paid_msat, 125_000);
5494 // Attempt to route without the last small cheap channel
5495 let route_params = RouteParameters::from_payment_params_and_value(
5496 payment_params, 90_000);
5497 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5498 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5499 assert_eq!(route.paths.len(), 2);
5500 let mut total_amount_paid_msat = 0;
5501 for path in &route.paths {
5502 assert_eq!(path.hops.len(), 2);
5503 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5504 total_amount_paid_msat += path.final_value_msat();
5506 assert_eq!(total_amount_paid_msat, 90_000);
5511 fn min_criteria_consistency() {
5512 // Test that we don't use an inconsistent metric between updating and walking nodes during
5513 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5514 // was updated with a different criterion from the heap sorting, resulting in loops in
5515 // calculated paths. We test for that specific case here.
5517 // We construct a network that looks like this:
5519 // node2 -1(3)2- node3
5523 // node1 -1(5)2- node4 -1(1)2- node6
5529 // We create a loop on the side of our real path - our destination is node 6, with a
5530 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5531 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5532 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5533 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5534 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5535 // "previous hop" being set to node 3, creating a loop in the path.
5536 let secp_ctx = Secp256k1::new();
5537 let logger = Arc::new(ln_test_utils::TestLogger::new());
5538 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5539 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5540 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5541 let scorer = ln_test_utils::TestScorer::new();
5542 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5543 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5544 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5546 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5547 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5548 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5549 short_channel_id: 6,
5552 cltv_expiry_delta: (6 << 4) | 0,
5553 htlc_minimum_msat: 0,
5554 htlc_maximum_msat: MAX_VALUE_MSAT,
5556 fee_proportional_millionths: 0,
5557 excess_data: Vec::new()
5559 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5561 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5562 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5563 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5564 short_channel_id: 5,
5567 cltv_expiry_delta: (5 << 4) | 0,
5568 htlc_minimum_msat: 0,
5569 htlc_maximum_msat: MAX_VALUE_MSAT,
5571 fee_proportional_millionths: 0,
5572 excess_data: Vec::new()
5574 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5576 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5577 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5578 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5579 short_channel_id: 4,
5582 cltv_expiry_delta: (4 << 4) | 0,
5583 htlc_minimum_msat: 0,
5584 htlc_maximum_msat: MAX_VALUE_MSAT,
5586 fee_proportional_millionths: 0,
5587 excess_data: Vec::new()
5589 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5591 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5592 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5593 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5594 short_channel_id: 3,
5597 cltv_expiry_delta: (3 << 4) | 0,
5598 htlc_minimum_msat: 0,
5599 htlc_maximum_msat: MAX_VALUE_MSAT,
5601 fee_proportional_millionths: 0,
5602 excess_data: Vec::new()
5604 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5606 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5607 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5608 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5609 short_channel_id: 2,
5612 cltv_expiry_delta: (2 << 4) | 0,
5613 htlc_minimum_msat: 0,
5614 htlc_maximum_msat: MAX_VALUE_MSAT,
5616 fee_proportional_millionths: 0,
5617 excess_data: Vec::new()
5620 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5621 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5622 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5623 short_channel_id: 1,
5626 cltv_expiry_delta: (1 << 4) | 0,
5627 htlc_minimum_msat: 100,
5628 htlc_maximum_msat: MAX_VALUE_MSAT,
5630 fee_proportional_millionths: 0,
5631 excess_data: Vec::new()
5633 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5636 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5637 let route_params = RouteParameters::from_payment_params_and_value(
5638 payment_params, 10_000);
5639 let route = get_route(&our_id, &route_params, &network.read_only(), None,
5640 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5641 assert_eq!(route.paths.len(), 1);
5642 assert_eq!(route.paths[0].hops.len(), 3);
5644 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5645 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5646 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5647 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5648 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5649 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5651 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5652 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5653 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5654 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5655 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5656 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5658 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5659 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5660 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5661 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5662 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5663 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5669 fn exact_fee_liquidity_limit() {
5670 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5671 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5672 // we calculated fees on a higher value, resulting in us ignoring such paths.
5673 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5674 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5675 let scorer = ln_test_utils::TestScorer::new();
5676 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5677 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5678 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5680 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5682 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5683 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5684 short_channel_id: 2,
5687 cltv_expiry_delta: 0,
5688 htlc_minimum_msat: 0,
5689 htlc_maximum_msat: 85_000,
5691 fee_proportional_millionths: 0,
5692 excess_data: Vec::new()
5695 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5696 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5697 short_channel_id: 12,
5700 cltv_expiry_delta: (4 << 4) | 1,
5701 htlc_minimum_msat: 0,
5702 htlc_maximum_msat: 270_000,
5704 fee_proportional_millionths: 1000000,
5705 excess_data: Vec::new()
5709 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5710 // 200% fee charged channel 13 in the 1-to-2 direction.
5711 let route_params = RouteParameters::from_payment_params_and_value(
5712 payment_params, 90_000);
5713 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5714 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5715 assert_eq!(route.paths.len(), 1);
5716 assert_eq!(route.paths[0].hops.len(), 2);
5718 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5719 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5720 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5721 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5722 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5723 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5725 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5726 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5727 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5728 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5729 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5730 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5735 fn htlc_max_reduction_below_min() {
5736 // Test that if, while walking the graph, we reduce the value being sent to meet an
5737 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5738 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5739 // resulting in us thinking there is no possible path, even if other paths exist.
5740 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5741 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5742 let scorer = ln_test_utils::TestScorer::new();
5743 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5744 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5745 let config = UserConfig::default();
5746 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5748 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5749 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5750 // then try to send 90_000.
5751 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5752 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5753 short_channel_id: 2,
5756 cltv_expiry_delta: 0,
5757 htlc_minimum_msat: 0,
5758 htlc_maximum_msat: 80_000,
5760 fee_proportional_millionths: 0,
5761 excess_data: Vec::new()
5763 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5764 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5765 short_channel_id: 4,
5768 cltv_expiry_delta: (4 << 4) | 1,
5769 htlc_minimum_msat: 90_000,
5770 htlc_maximum_msat: MAX_VALUE_MSAT,
5772 fee_proportional_millionths: 0,
5773 excess_data: Vec::new()
5777 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5778 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5779 // expensive) channels 12-13 path.
5780 let route_params = RouteParameters::from_payment_params_and_value(
5781 payment_params, 90_000);
5782 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5783 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5784 assert_eq!(route.paths.len(), 1);
5785 assert_eq!(route.paths[0].hops.len(), 2);
5787 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5788 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5789 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5790 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5791 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5792 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5794 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5795 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5796 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5797 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5798 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5799 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5804 fn multiple_direct_first_hops() {
5805 // Previously we'd only ever considered one first hop path per counterparty.
5806 // However, as we don't restrict users to one channel per peer, we really need to support
5807 // looking at all first hop paths.
5808 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5809 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5810 // route over multiple channels with the same first hop.
5811 let secp_ctx = Secp256k1::new();
5812 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5813 let logger = Arc::new(ln_test_utils::TestLogger::new());
5814 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5815 let scorer = ln_test_utils::TestScorer::new();
5816 let config = UserConfig::default();
5817 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5818 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5819 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5822 let route_params = RouteParameters::from_payment_params_and_value(
5823 payment_params.clone(), 100_000);
5824 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5825 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5826 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5827 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5828 assert_eq!(route.paths.len(), 1);
5829 assert_eq!(route.paths[0].hops.len(), 1);
5831 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5832 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5833 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5836 let route_params = RouteParameters::from_payment_params_and_value(
5837 payment_params.clone(), 100_000);
5838 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5839 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5840 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5841 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5842 assert_eq!(route.paths.len(), 2);
5843 assert_eq!(route.paths[0].hops.len(), 1);
5844 assert_eq!(route.paths[1].hops.len(), 1);
5846 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5847 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5849 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5850 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5852 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5853 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5857 // If we have a bunch of outbound channels to the same node, where most are not
5858 // sufficient to pay the full payment, but one is, we should default to just using the
5859 // one single channel that has sufficient balance, avoiding MPP.
5861 // If we have several options above the 3xpayment value threshold, we should pick the
5862 // smallest of them, avoiding further fragmenting our available outbound balance to
5864 let route_params = RouteParameters::from_payment_params_and_value(
5865 payment_params, 100_000);
5866 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5867 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5868 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5869 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5870 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5871 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5872 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5873 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5874 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5875 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5876 assert_eq!(route.paths.len(), 1);
5877 assert_eq!(route.paths[0].hops.len(), 1);
5879 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5880 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5881 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5886 fn prefers_shorter_route_with_higher_fees() {
5887 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5888 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5889 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5891 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5892 let scorer = ln_test_utils::TestScorer::new();
5893 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5894 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5895 let route_params = RouteParameters::from_payment_params_and_value(
5896 payment_params.clone(), 100);
5897 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
5898 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5899 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5901 assert_eq!(route.get_total_fees(), 100);
5902 assert_eq!(route.get_total_amount(), 100);
5903 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5905 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5906 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5907 let scorer = FixedPenaltyScorer::with_penalty(100);
5908 let route_params = RouteParameters::from_payment_params_and_value(
5909 payment_params, 100);
5910 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
5911 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5912 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5914 assert_eq!(route.get_total_fees(), 300);
5915 assert_eq!(route.get_total_amount(), 100);
5916 assert_eq!(path, vec![2, 4, 7, 10]);
5919 struct BadChannelScorer {
5920 short_channel_id: u64,
5924 impl Writeable for BadChannelScorer {
5925 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5927 impl ScoreLookUp for BadChannelScorer {
5928 type ScoreParams = ();
5929 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5930 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5934 struct BadNodeScorer {
5939 impl Writeable for BadNodeScorer {
5940 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5943 impl ScoreLookUp for BadNodeScorer {
5944 type ScoreParams = ();
5945 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5946 if *target == self.node_id { u64::max_value() } else { 0 }
5951 fn avoids_routing_through_bad_channels_and_nodes() {
5952 let (secp_ctx, network, _, _, logger) = build_graph();
5953 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5954 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5955 let network_graph = network.read_only();
5957 // A path to nodes[6] exists when no penalties are applied to any channel.
5958 let scorer = ln_test_utils::TestScorer::new();
5959 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5960 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5961 let route_params = RouteParameters::from_payment_params_and_value(
5962 payment_params, 100);
5963 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
5964 &scorer, &Default::default(), &random_seed_bytes).unwrap();
5965 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5967 assert_eq!(route.get_total_fees(), 100);
5968 assert_eq!(route.get_total_amount(), 100);
5969 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5971 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5972 let scorer = BadChannelScorer { short_channel_id: 6 };
5973 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
5974 &scorer, &Default::default(), &random_seed_bytes).unwrap();
5975 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5977 assert_eq!(route.get_total_fees(), 300);
5978 assert_eq!(route.get_total_amount(), 100);
5979 assert_eq!(path, vec![2, 4, 7, 10]);
5981 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5982 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5983 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
5984 &scorer, &Default::default(), &random_seed_bytes) {
5985 Err(LightningError { err, .. } ) => {
5986 assert_eq!(err, "Failed to find a path to the given destination");
5988 Ok(_) => panic!("Expected error"),
5993 fn total_fees_single_path() {
5995 paths: vec![Path { hops: vec![
5997 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5998 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5999 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6002 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6003 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6004 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6007 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6008 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6009 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6011 ], blinded_tail: None }],
6015 assert_eq!(route.get_total_fees(), 250);
6016 assert_eq!(route.get_total_amount(), 225);
6020 fn total_fees_multi_path() {
6022 paths: vec![Path { hops: vec![
6024 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6025 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6026 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6029 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6030 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6031 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6033 ], blinded_tail: None }, Path { hops: vec![
6035 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6036 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6037 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6040 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6041 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6042 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6044 ], blinded_tail: None }],
6048 assert_eq!(route.get_total_fees(), 200);
6049 assert_eq!(route.get_total_amount(), 300);
6053 fn total_empty_route_no_panic() {
6054 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6055 // would both panic if the route was completely empty. We test to ensure they return 0
6056 // here, even though its somewhat nonsensical as a route.
6057 let route = Route { paths: Vec::new(), route_params: None };
6059 assert_eq!(route.get_total_fees(), 0);
6060 assert_eq!(route.get_total_amount(), 0);
6064 fn limits_total_cltv_delta() {
6065 let (secp_ctx, network, _, _, logger) = build_graph();
6066 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6067 let network_graph = network.read_only();
6069 let scorer = ln_test_utils::TestScorer::new();
6071 // Make sure that generally there is at least one route available
6072 let feasible_max_total_cltv_delta = 1008;
6073 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6074 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6075 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6076 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6077 let route_params = RouteParameters::from_payment_params_and_value(
6078 feasible_payment_params, 100);
6079 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6080 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6081 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6082 assert_ne!(path.len(), 0);
6084 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6085 let fail_max_total_cltv_delta = 23;
6086 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6087 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6088 let route_params = RouteParameters::from_payment_params_and_value(
6089 fail_payment_params, 100);
6090 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6091 &Default::default(), &random_seed_bytes)
6093 Err(LightningError { err, .. } ) => {
6094 assert_eq!(err, "Failed to find a path to the given destination");
6096 Ok(_) => panic!("Expected error"),
6101 fn avoids_recently_failed_paths() {
6102 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6103 // randomly inserting channels into it until we can't find a route anymore.
6104 let (secp_ctx, network, _, _, logger) = build_graph();
6105 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6106 let network_graph = network.read_only();
6108 let scorer = ln_test_utils::TestScorer::new();
6109 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6110 .with_max_path_count(1);
6111 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6112 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6114 // We should be able to find a route initially, and then after we fail a few random
6115 // channels eventually we won't be able to any longer.
6116 let route_params = RouteParameters::from_payment_params_and_value(
6117 payment_params.clone(), 100);
6118 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6119 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6121 let route_params = RouteParameters::from_payment_params_and_value(
6122 payment_params.clone(), 100);
6123 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6124 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6126 for chan in route.paths[0].hops.iter() {
6127 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6129 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6130 % route.paths[0].hops.len();
6131 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6137 fn limits_path_length() {
6138 let (secp_ctx, network, _, _, logger) = build_line_graph();
6139 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6140 let network_graph = network.read_only();
6142 let scorer = ln_test_utils::TestScorer::new();
6143 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6144 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6146 // First check we can actually create a long route on this graph.
6147 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6148 let route_params = RouteParameters::from_payment_params_and_value(
6149 feasible_payment_params, 100);
6150 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6151 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6152 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6153 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6155 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6156 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6157 let route_params = RouteParameters::from_payment_params_and_value(
6158 fail_payment_params, 100);
6159 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6160 &Default::default(), &random_seed_bytes)
6162 Err(LightningError { err, .. } ) => {
6163 assert_eq!(err, "Failed to find a path to the given destination");
6165 Ok(_) => panic!("Expected error"),
6170 fn adds_and_limits_cltv_offset() {
6171 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6172 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6174 let scorer = ln_test_utils::TestScorer::new();
6176 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6177 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6178 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6179 let route_params = RouteParameters::from_payment_params_and_value(
6180 payment_params.clone(), 100);
6181 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6182 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6183 assert_eq!(route.paths.len(), 1);
6185 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6187 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6188 let mut route_default = route.clone();
6189 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6190 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6191 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6192 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6193 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6195 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6196 let mut route_limited = route.clone();
6197 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6198 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6199 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6200 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6201 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6205 fn adds_plausible_cltv_offset() {
6206 let (secp_ctx, network, _, _, logger) = build_graph();
6207 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6208 let network_graph = network.read_only();
6209 let network_nodes = network_graph.nodes();
6210 let network_channels = network_graph.channels();
6211 let scorer = ln_test_utils::TestScorer::new();
6212 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6213 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6214 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6216 let route_params = RouteParameters::from_payment_params_and_value(
6217 payment_params.clone(), 100);
6218 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6219 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6220 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6222 let mut path_plausibility = vec![];
6224 for p in route.paths {
6225 // 1. Select random observation point
6226 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6227 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6229 prng.process_in_place(&mut random_bytes);
6230 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6231 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6233 // 2. Calculate what CLTV expiry delta we would observe there
6234 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6236 // 3. Starting from the observation point, find candidate paths
6237 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6238 candidates.push_back((observation_point, vec![]));
6240 let mut found_plausible_candidate = false;
6242 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6243 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6244 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6245 found_plausible_candidate = true;
6246 break 'candidate_loop;
6250 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6251 for channel_id in &cur_node.channels {
6252 if let Some(channel_info) = network_channels.get(&channel_id) {
6253 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6254 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6255 if cur_path_cltv_deltas.iter().sum::<u32>()
6256 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6257 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6258 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6259 candidates.push_back((*next_id, new_path_cltv_deltas));
6267 path_plausibility.push(found_plausible_candidate);
6269 assert!(path_plausibility.iter().all(|x| *x));
6273 fn builds_correct_path_from_hops() {
6274 let (secp_ctx, network, _, _, logger) = build_graph();
6275 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6276 let network_graph = network.read_only();
6278 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6279 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6281 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6282 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6283 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6284 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6285 Arc::clone(&logger), &random_seed_bytes).unwrap();
6286 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6287 assert_eq!(hops.len(), route.paths[0].hops.len());
6288 for (idx, hop_pubkey) in hops.iter().enumerate() {
6289 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6294 fn avoids_saturating_channels() {
6295 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6296 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6297 let decay_params = ProbabilisticScoringDecayParameters::default();
6298 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6300 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6301 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6302 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6303 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6304 short_channel_id: 4,
6307 cltv_expiry_delta: (4 << 4) | 1,
6308 htlc_minimum_msat: 0,
6309 htlc_maximum_msat: 250_000_000,
6311 fee_proportional_millionths: 0,
6312 excess_data: Vec::new()
6314 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6315 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6316 short_channel_id: 13,
6319 cltv_expiry_delta: (13 << 4) | 1,
6320 htlc_minimum_msat: 0,
6321 htlc_maximum_msat: 250_000_000,
6323 fee_proportional_millionths: 0,
6324 excess_data: Vec::new()
6327 let config = UserConfig::default();
6328 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6329 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6330 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6331 // 100,000 sats is less than the available liquidity on each channel, set above.
6332 let route_params = RouteParameters::from_payment_params_and_value(
6333 payment_params, 100_000_000);
6334 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6335 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6336 assert_eq!(route.paths.len(), 2);
6337 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6338 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6341 #[cfg(not(feature = "no-std"))]
6342 pub(super) fn random_init_seed() -> u64 {
6343 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6344 use core::hash::{BuildHasher, Hasher};
6345 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6346 println!("Using seed of {}", seed);
6351 #[cfg(not(feature = "no-std"))]
6352 fn generate_routes() {
6353 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6355 let logger = ln_test_utils::TestLogger::new();
6356 let graph = match super::bench_utils::read_network_graph(&logger) {
6364 let params = ProbabilisticScoringFeeParameters::default();
6365 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6366 let features = super::Bolt11InvoiceFeatures::empty();
6368 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6372 #[cfg(not(feature = "no-std"))]
6373 fn generate_routes_mpp() {
6374 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6376 let logger = ln_test_utils::TestLogger::new();
6377 let graph = match super::bench_utils::read_network_graph(&logger) {
6385 let params = ProbabilisticScoringFeeParameters::default();
6386 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6387 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6389 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6393 #[cfg(not(feature = "no-std"))]
6394 fn generate_large_mpp_routes() {
6395 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6397 let logger = ln_test_utils::TestLogger::new();
6398 let graph = match super::bench_utils::read_network_graph(&logger) {
6406 let params = ProbabilisticScoringFeeParameters::default();
6407 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6408 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6410 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6414 fn honors_manual_penalties() {
6415 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6416 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6418 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6419 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6421 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6422 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6424 // First check set manual penalties are returned by the scorer.
6425 let usage = ChannelUsage {
6427 inflight_htlc_msat: 0,
6428 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6430 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6431 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6432 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
6434 // Then check we can get a normal route
6435 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6436 let route_params = RouteParameters::from_payment_params_and_value(
6437 payment_params, 100);
6438 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6439 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6440 assert!(route.is_ok());
6442 // Then check that we can't get a route if we ban an intermediate node.
6443 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6444 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6445 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6446 assert!(route.is_err());
6448 // Finally make sure we can route again, when we remove the ban.
6449 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6450 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6451 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6452 assert!(route.is_ok());
6456 fn abide_by_route_hint_max_htlc() {
6457 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6458 // params in the final route.
6459 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6460 let netgraph = network_graph.read_only();
6461 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6462 let scorer = ln_test_utils::TestScorer::new();
6463 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6464 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6465 let config = UserConfig::default();
6467 let max_htlc_msat = 50_000;
6468 let route_hint_1 = RouteHint(vec![RouteHintHop {
6469 src_node_id: nodes[2],
6470 short_channel_id: 42,
6473 proportional_millionths: 0,
6475 cltv_expiry_delta: 10,
6476 htlc_minimum_msat: None,
6477 htlc_maximum_msat: Some(max_htlc_msat),
6479 let dest_node_id = ln_test_utils::pubkey(42);
6480 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6481 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6482 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6484 // Make sure we'll error if our route hints don't have enough liquidity according to their
6485 // htlc_maximum_msat.
6486 let route_params = RouteParameters::from_payment_params_and_value(
6487 payment_params, max_htlc_msat + 1);
6488 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6489 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
6492 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6493 } else { panic!(); }
6495 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6496 let mut route_hint_2 = route_hint_1.clone();
6497 route_hint_2.0[0].short_channel_id = 43;
6498 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6499 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6500 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6501 let route_params = RouteParameters::from_payment_params_and_value(
6502 payment_params, max_htlc_msat + 1);
6503 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
6504 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6505 assert_eq!(route.paths.len(), 2);
6506 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6507 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6511 fn direct_channel_to_hints_with_max_htlc() {
6512 // Check that if we have a first hop channel peer that's connected to multiple provided route
6513 // hints, that we properly split the payment between the route hints if needed.
6514 let logger = Arc::new(ln_test_utils::TestLogger::new());
6515 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6516 let scorer = ln_test_utils::TestScorer::new();
6517 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6518 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6519 let config = UserConfig::default();
6521 let our_node_id = ln_test_utils::pubkey(42);
6522 let intermed_node_id = ln_test_utils::pubkey(43);
6523 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6525 let amt_msat = 900_000;
6526 let max_htlc_msat = 500_000;
6527 let route_hint_1 = RouteHint(vec![RouteHintHop {
6528 src_node_id: intermed_node_id,
6529 short_channel_id: 44,
6532 proportional_millionths: 0,
6534 cltv_expiry_delta: 10,
6535 htlc_minimum_msat: None,
6536 htlc_maximum_msat: Some(max_htlc_msat),
6538 src_node_id: intermed_node_id,
6539 short_channel_id: 45,
6542 proportional_millionths: 0,
6544 cltv_expiry_delta: 10,
6545 htlc_minimum_msat: None,
6546 // Check that later route hint max htlcs don't override earlier ones
6547 htlc_maximum_msat: Some(max_htlc_msat - 50),
6549 let mut route_hint_2 = route_hint_1.clone();
6550 route_hint_2.0[0].short_channel_id = 46;
6551 route_hint_2.0[1].short_channel_id = 47;
6552 let dest_node_id = ln_test_utils::pubkey(44);
6553 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6554 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6555 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6557 let route_params = RouteParameters::from_payment_params_and_value(
6558 payment_params, amt_msat);
6559 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6560 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6561 &Default::default(), &random_seed_bytes).unwrap();
6562 assert_eq!(route.paths.len(), 2);
6563 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6564 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6565 assert_eq!(route.get_total_amount(), amt_msat);
6567 // Re-run but with two first hop channels connected to the same route hint peers that must be
6569 let first_hops = vec![
6570 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6571 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6573 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6574 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6575 &Default::default(), &random_seed_bytes).unwrap();
6576 assert_eq!(route.paths.len(), 2);
6577 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6578 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6579 assert_eq!(route.get_total_amount(), amt_msat);
6581 // Make sure this works for blinded route hints.
6582 let blinded_path = BlindedPath {
6583 introduction_node_id: intermed_node_id,
6584 blinding_point: ln_test_utils::pubkey(42),
6586 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6587 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6590 let blinded_payinfo = BlindedPayInfo {
6592 fee_proportional_millionths: 0,
6593 htlc_minimum_msat: 1,
6594 htlc_maximum_msat: max_htlc_msat,
6595 cltv_expiry_delta: 10,
6596 features: BlindedHopFeatures::empty(),
6598 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6599 let payment_params = PaymentParameters::blinded(vec![
6600 (blinded_payinfo.clone(), blinded_path.clone()),
6601 (blinded_payinfo.clone(), blinded_path.clone())])
6602 .with_bolt12_features(bolt12_features).unwrap();
6603 let route_params = RouteParameters::from_payment_params_and_value(
6604 payment_params, amt_msat);
6605 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6606 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6607 &Default::default(), &random_seed_bytes).unwrap();
6608 assert_eq!(route.paths.len(), 2);
6609 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6610 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6611 assert_eq!(route.get_total_amount(), amt_msat);
6615 fn blinded_route_ser() {
6616 let blinded_path_1 = BlindedPath {
6617 introduction_node_id: ln_test_utils::pubkey(42),
6618 blinding_point: ln_test_utils::pubkey(43),
6620 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6621 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6624 let blinded_path_2 = BlindedPath {
6625 introduction_node_id: ln_test_utils::pubkey(46),
6626 blinding_point: ln_test_utils::pubkey(47),
6628 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6629 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6632 // (De)serialize a Route with 1 blinded path out of two total paths.
6633 let mut route = Route { paths: vec![Path {
6634 hops: vec![RouteHop {
6635 pubkey: ln_test_utils::pubkey(50),
6636 node_features: NodeFeatures::empty(),
6637 short_channel_id: 42,
6638 channel_features: ChannelFeatures::empty(),
6640 cltv_expiry_delta: 0,
6641 maybe_announced_channel: true,
6643 blinded_tail: Some(BlindedTail {
6644 hops: blinded_path_1.blinded_hops,
6645 blinding_point: blinded_path_1.blinding_point,
6646 excess_final_cltv_expiry_delta: 40,
6647 final_value_msat: 100,
6649 hops: vec![RouteHop {
6650 pubkey: ln_test_utils::pubkey(51),
6651 node_features: NodeFeatures::empty(),
6652 short_channel_id: 43,
6653 channel_features: ChannelFeatures::empty(),
6655 cltv_expiry_delta: 0,
6656 maybe_announced_channel: true,
6657 }], blinded_tail: None }],
6660 let encoded_route = route.encode();
6661 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6662 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6663 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6665 // (De)serialize a Route with two paths, each containing a blinded tail.
6666 route.paths[1].blinded_tail = Some(BlindedTail {
6667 hops: blinded_path_2.blinded_hops,
6668 blinding_point: blinded_path_2.blinding_point,
6669 excess_final_cltv_expiry_delta: 41,
6670 final_value_msat: 101,
6672 let encoded_route = route.encode();
6673 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6674 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6675 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6679 fn blinded_path_inflight_processing() {
6680 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6681 // account for the blinded tail's final amount_msat.
6682 let mut inflight_htlcs = InFlightHtlcs::new();
6683 let blinded_path = BlindedPath {
6684 introduction_node_id: ln_test_utils::pubkey(43),
6685 blinding_point: ln_test_utils::pubkey(48),
6686 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
6689 hops: vec![RouteHop {
6690 pubkey: ln_test_utils::pubkey(42),
6691 node_features: NodeFeatures::empty(),
6692 short_channel_id: 42,
6693 channel_features: ChannelFeatures::empty(),
6695 cltv_expiry_delta: 0,
6696 maybe_announced_channel: false,
6699 pubkey: blinded_path.introduction_node_id,
6700 node_features: NodeFeatures::empty(),
6701 short_channel_id: 43,
6702 channel_features: ChannelFeatures::empty(),
6704 cltv_expiry_delta: 0,
6705 maybe_announced_channel: false,
6707 blinded_tail: Some(BlindedTail {
6708 hops: blinded_path.blinded_hops,
6709 blinding_point: blinded_path.blinding_point,
6710 excess_final_cltv_expiry_delta: 0,
6711 final_value_msat: 200,
6714 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
6715 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
6716 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
6720 fn blinded_path_cltv_shadow_offset() {
6721 // Make sure we add a shadow offset when sending to blinded paths.
6722 let blinded_path = BlindedPath {
6723 introduction_node_id: ln_test_utils::pubkey(43),
6724 blinding_point: ln_test_utils::pubkey(44),
6726 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
6727 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
6730 let mut route = Route { paths: vec![Path {
6731 hops: vec![RouteHop {
6732 pubkey: ln_test_utils::pubkey(42),
6733 node_features: NodeFeatures::empty(),
6734 short_channel_id: 42,
6735 channel_features: ChannelFeatures::empty(),
6737 cltv_expiry_delta: 0,
6738 maybe_announced_channel: false,
6741 pubkey: blinded_path.introduction_node_id,
6742 node_features: NodeFeatures::empty(),
6743 short_channel_id: 43,
6744 channel_features: ChannelFeatures::empty(),
6746 cltv_expiry_delta: 0,
6747 maybe_announced_channel: false,
6750 blinded_tail: Some(BlindedTail {
6751 hops: blinded_path.blinded_hops,
6752 blinding_point: blinded_path.blinding_point,
6753 excess_final_cltv_expiry_delta: 0,
6754 final_value_msat: 200,
6756 }], route_params: None};
6758 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
6759 let (_, network_graph, _, _, _) = build_line_graph();
6760 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
6761 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
6762 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
6766 fn simple_blinded_route_hints() {
6767 do_simple_blinded_route_hints(1);
6768 do_simple_blinded_route_hints(2);
6769 do_simple_blinded_route_hints(3);
6772 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
6773 // Check that we can generate a route to a blinded path with the expected hops.
6774 let (secp_ctx, network, _, _, logger) = build_graph();
6775 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6776 let network_graph = network.read_only();
6778 let scorer = ln_test_utils::TestScorer::new();
6779 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6780 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6782 let mut blinded_path = BlindedPath {
6783 introduction_node_id: nodes[2],
6784 blinding_point: ln_test_utils::pubkey(42),
6785 blinded_hops: Vec::with_capacity(num_blinded_hops),
6787 for i in 0..num_blinded_hops {
6788 blinded_path.blinded_hops.push(
6789 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
6792 let blinded_payinfo = BlindedPayInfo {
6794 fee_proportional_millionths: 500,
6795 htlc_minimum_msat: 1000,
6796 htlc_maximum_msat: 100_000_000,
6797 cltv_expiry_delta: 15,
6798 features: BlindedHopFeatures::empty(),
6801 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
6802 let route_params = RouteParameters::from_payment_params_and_value(
6803 payment_params, 1001);
6804 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6805 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6806 assert_eq!(route.paths.len(), 1);
6807 assert_eq!(route.paths[0].hops.len(), 2);
6809 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
6810 assert_eq!(tail.hops, blinded_path.blinded_hops);
6811 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
6812 assert_eq!(tail.final_value_msat, 1001);
6814 let final_hop = route.paths[0].hops.last().unwrap();
6815 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
6816 if tail.hops.len() > 1 {
6817 assert_eq!(final_hop.fee_msat,
6818 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
6819 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
6821 assert_eq!(final_hop.fee_msat, 0);
6822 assert_eq!(final_hop.cltv_expiry_delta, 0);
6827 fn blinded_path_routing_errors() {
6828 // Check that we can generate a route to a blinded path with the expected hops.
6829 let (secp_ctx, network, _, _, logger) = build_graph();
6830 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6831 let network_graph = network.read_only();
6833 let scorer = ln_test_utils::TestScorer::new();
6834 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6835 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6837 let mut invalid_blinded_path = BlindedPath {
6838 introduction_node_id: nodes[2],
6839 blinding_point: ln_test_utils::pubkey(42),
6841 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
6844 let blinded_payinfo = BlindedPayInfo {
6846 fee_proportional_millionths: 500,
6847 htlc_minimum_msat: 1000,
6848 htlc_maximum_msat: 100_000_000,
6849 cltv_expiry_delta: 15,
6850 features: BlindedHopFeatures::empty(),
6853 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
6854 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
6855 let payment_params = PaymentParameters::blinded(vec![
6856 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
6857 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
6858 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6859 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6860 &scorer, &Default::default(), &random_seed_bytes)
6862 Err(LightningError { err, .. }) => {
6863 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
6865 _ => panic!("Expected error")
6868 invalid_blinded_path.introduction_node_id = our_id;
6869 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
6870 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6871 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6872 &Default::default(), &random_seed_bytes)
6874 Err(LightningError { err, .. }) => {
6875 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
6877 _ => panic!("Expected error")
6880 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
6881 invalid_blinded_path.blinded_hops.clear();
6882 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
6883 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6884 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6885 &Default::default(), &random_seed_bytes)
6887 Err(LightningError { err, .. }) => {
6888 assert_eq!(err, "0-hop blinded path provided");
6890 _ => panic!("Expected error")
6895 fn matching_intro_node_paths_provided() {
6896 // Check that if multiple blinded paths with the same intro node are provided in payment
6897 // parameters, we'll return the correct paths in the resulting MPP route.
6898 let (secp_ctx, network, _, _, logger) = build_graph();
6899 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6900 let network_graph = network.read_only();
6902 let scorer = ln_test_utils::TestScorer::new();
6903 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6904 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6905 let config = UserConfig::default();
6907 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6908 let blinded_path_1 = BlindedPath {
6909 introduction_node_id: nodes[2],
6910 blinding_point: ln_test_utils::pubkey(42),
6912 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6913 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6916 let blinded_payinfo_1 = BlindedPayInfo {
6918 fee_proportional_millionths: 0,
6919 htlc_minimum_msat: 0,
6920 htlc_maximum_msat: 30_000,
6921 cltv_expiry_delta: 0,
6922 features: BlindedHopFeatures::empty(),
6925 let mut blinded_path_2 = blinded_path_1.clone();
6926 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
6927 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
6928 blinded_payinfo_2.htlc_maximum_msat = 70_000;
6930 let blinded_hints = vec![
6931 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
6932 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
6934 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
6935 .with_bolt12_features(bolt12_features.clone()).unwrap();
6937 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
6938 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6939 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6940 assert_eq!(route.paths.len(), 2);
6941 let mut total_amount_paid_msat = 0;
6942 for path in route.paths.into_iter() {
6943 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6944 if let Some(bt) = &path.blinded_tail {
6945 assert_eq!(bt.blinding_point,
6946 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
6947 .map(|(_, bp)| bp.blinding_point).unwrap());
6948 } else { panic!(); }
6949 total_amount_paid_msat += path.final_value_msat();
6951 assert_eq!(total_amount_paid_msat, 100_000);
6955 fn direct_to_intro_node() {
6956 // This previously caused a debug panic in the router when asserting
6957 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
6958 // direct channels we failed to account for the fee charged for use of the blinded path.
6961 // node0 -1(1)2 - node1
6962 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
6963 // doesn't account for the blinded path fee.
6965 let secp_ctx = Secp256k1::new();
6966 let logger = Arc::new(ln_test_utils::TestLogger::new());
6967 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6968 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
6969 let scorer = ln_test_utils::TestScorer::new();
6970 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6971 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6973 let amt_msat = 10_000_000;
6974 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
6975 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
6976 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6977 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6978 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6979 short_channel_id: 1,
6982 cltv_expiry_delta: 42,
6983 htlc_minimum_msat: 1_000,
6984 htlc_maximum_msat: 10_000_000,
6986 fee_proportional_millionths: 0,
6987 excess_data: Vec::new()
6989 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6990 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6991 short_channel_id: 1,
6994 cltv_expiry_delta: 42,
6995 htlc_minimum_msat: 1_000,
6996 htlc_maximum_msat: 10_000_000,
6998 fee_proportional_millionths: 0,
6999 excess_data: Vec::new()
7001 let first_hops = vec![
7002 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7004 let blinded_path = BlindedPath {
7005 introduction_node_id: nodes[1],
7006 blinding_point: ln_test_utils::pubkey(42),
7008 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7009 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7012 let blinded_payinfo = BlindedPayInfo {
7013 fee_base_msat: 1000,
7014 fee_proportional_millionths: 0,
7015 htlc_minimum_msat: 1000,
7016 htlc_maximum_msat: MAX_VALUE_MSAT,
7017 cltv_expiry_delta: 0,
7018 features: BlindedHopFeatures::empty(),
7020 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7022 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7024 let netgraph = network_graph.read_only();
7025 let route_params = RouteParameters::from_payment_params_and_value(
7026 payment_params.clone(), amt_msat);
7027 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7028 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7029 &Default::default(), &random_seed_bytes) {
7030 assert_eq!(err, "Failed to find a path to the given destination");
7031 } else { panic!("Expected error") }
7033 // Sending an exact amount accounting for the blinded path fee works.
7034 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7035 let route_params = RouteParameters::from_payment_params_and_value(
7036 payment_params, amt_minus_blinded_path_fee);
7037 let route = get_route(&nodes[0], &route_params, &netgraph,
7038 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7039 &Default::default(), &random_seed_bytes).unwrap();
7040 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7041 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7045 fn direct_to_matching_intro_nodes() {
7046 // This previously caused us to enter `unreachable` code in the following situation:
7047 // 1. We add a route candidate for intro_node contributing a high amount
7048 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7049 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7050 // amount, and update our route candidate for intro_node for the lower amount
7051 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7052 // lower contribution amount, but fail (this was previously caused by failure to account for
7053 // blinded path fees when adding first_hop<>intro_node candidates)
7054 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7055 // candidate still thinks its path is contributing the original higher amount. This caused us
7056 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7058 let secp_ctx = Secp256k1::new();
7059 let logger = Arc::new(ln_test_utils::TestLogger::new());
7060 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7061 let scorer = ln_test_utils::TestScorer::new();
7062 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7063 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7064 let config = UserConfig::default();
7066 // Values are taken from the fuzz input that uncovered this panic.
7067 let amt_msat = 21_7020_5185_1403_2640;
7068 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7069 let first_hops = vec![
7070 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7071 18446744073709551615)];
7073 let blinded_path = BlindedPath {
7074 introduction_node_id: nodes[1],
7075 blinding_point: ln_test_utils::pubkey(42),
7077 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7078 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7081 let blinded_payinfo = BlindedPayInfo {
7082 fee_base_msat: 5046_2720,
7083 fee_proportional_millionths: 0,
7084 htlc_minimum_msat: 4503_5996_2737_0496,
7085 htlc_maximum_msat: 45_0359_9627_3704_9600,
7086 cltv_expiry_delta: 0,
7087 features: BlindedHopFeatures::empty(),
7089 let mut blinded_hints = vec![
7090 (blinded_payinfo.clone(), blinded_path.clone()),
7091 (blinded_payinfo.clone(), blinded_path.clone()),
7093 blinded_hints[1].0.fee_base_msat = 419_4304;
7094 blinded_hints[1].0.fee_proportional_millionths = 257;
7095 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7096 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7097 blinded_hints[1].0.cltv_expiry_delta = 0;
7099 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7100 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7101 .with_bolt12_features(bolt12_features.clone()).unwrap();
7103 let netgraph = network_graph.read_only();
7104 let route_params = RouteParameters::from_payment_params_and_value(
7105 payment_params, amt_msat);
7106 let route = get_route(&nodes[0], &route_params, &netgraph,
7107 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7108 &Default::default(), &random_seed_bytes).unwrap();
7109 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7110 assert_eq!(route.get_total_amount(), amt_msat);
7114 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
7115 pub(crate) mod bench_utils {
7119 use bitcoin::hashes::Hash;
7120 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
7122 use crate::chain::transaction::OutPoint;
7123 use crate::routing::scoring::ScoreUpdate;
7124 use crate::sign::{EntropySource, KeysManager};
7125 use crate::ln::ChannelId;
7126 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
7127 use crate::ln::features::Bolt11InvoiceFeatures;
7128 use crate::routing::gossip::NetworkGraph;
7129 use crate::util::config::UserConfig;
7130 use crate::util::ser::ReadableArgs;
7131 use crate::util::test_utils::TestLogger;
7133 /// Tries to open a network graph file, or panics with a URL to fetch it.
7134 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
7135 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
7136 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
7137 .or_else(|_| { // Fall back to guessing based on the binary location
7138 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
7139 let mut path = std::env::current_exe().unwrap();
7140 path.pop(); // lightning-...
7142 path.pop(); // debug
7143 path.pop(); // target
7144 path.push("lightning");
7145 path.push("net_graph-2023-01-18.bin");
7148 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
7149 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
7150 let mut path = std::env::current_exe().unwrap();
7151 path.pop(); // bench...
7153 path.pop(); // debug
7154 path.pop(); // target
7155 path.pop(); // bench
7156 path.push("lightning");
7157 path.push("net_graph-2023-01-18.bin");
7160 .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");
7161 #[cfg(require_route_graph_test)]
7162 return Ok(res.unwrap());
7163 #[cfg(not(require_route_graph_test))]
7167 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
7168 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
7171 pub(crate) fn payer_pubkey() -> PublicKey {
7172 let secp_ctx = Secp256k1::new();
7173 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
7177 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
7179 channel_id: ChannelId::new_zero(),
7180 counterparty: ChannelCounterparty {
7181 features: channelmanager::provided_init_features(&UserConfig::default()),
7183 unspendable_punishment_reserve: 0,
7184 forwarding_info: None,
7185 outbound_htlc_minimum_msat: None,
7186 outbound_htlc_maximum_msat: None,
7188 funding_txo: Some(OutPoint {
7189 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
7192 short_channel_id: Some(1),
7193 inbound_scid_alias: None,
7194 outbound_scid_alias: None,
7195 channel_value_satoshis: 10_000_000_000,
7197 outbound_capacity_msat: 10_000_000_000,
7198 next_outbound_htlc_minimum_msat: 0,
7199 next_outbound_htlc_limit_msat: 10_000_000_000,
7200 inbound_capacity_msat: 0,
7201 unspendable_punishment_reserve: None,
7202 confirmations_required: None,
7203 confirmations: None,
7204 force_close_spend_delay: None,
7206 is_channel_ready: true,
7209 inbound_htlc_minimum_msat: None,
7210 inbound_htlc_maximum_msat: None,
7212 feerate_sat_per_1000_weight: None,
7213 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
7217 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
7218 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
7219 starting_amount: u64, route_count: usize,
7220 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
7221 let payer = payer_pubkey();
7222 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7223 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7225 let nodes = graph.read_only().nodes().clone();
7226 let mut route_endpoints = Vec::new();
7227 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
7228 // with some routes we picked being un-routable.
7229 for _ in 0..route_count * 3 / 2 {
7231 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7232 let src = PublicKey::from_slice(nodes.unordered_keys()
7233 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
7234 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7235 let dst = PublicKey::from_slice(nodes.unordered_keys()
7236 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
7237 let params = PaymentParameters::from_node_id(dst, 42)
7238 .with_bolt11_features(features.clone()).unwrap();
7239 let first_hop = first_hop(src);
7240 let amt_msat = starting_amount + seed % 1_000_000;
7241 let route_params = RouteParameters::from_payment_params_and_value(
7242 params.clone(), amt_msat);
7244 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
7245 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
7247 // ...and seed the scorer with success and failure data...
7248 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7249 let mut score_amt = seed % 1_000_000_000;
7251 // Generate fail/success paths for a wider range of potential amounts with
7252 // MPP enabled to give us a chance to apply penalties for more potential
7254 let mpp_features = channelmanager::provided_invoice_features(&UserConfig::default());
7255 let params = PaymentParameters::from_node_id(dst, 42)
7256 .with_bolt11_features(mpp_features).unwrap();
7257 let route_params = RouteParameters::from_payment_params_and_value(
7258 params.clone(), score_amt);
7259 let route_res = get_route(&payer, &route_params, &graph.read_only(),
7260 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
7261 &random_seed_bytes);
7262 if let Ok(route) = route_res {
7263 for path in route.paths {
7264 if seed & 0x80 == 0 {
7265 scorer.payment_path_successful(&path);
7267 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
7268 scorer.payment_path_failed(&path, short_channel_id);
7270 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7274 // If we couldn't find a path with a higer amount, reduce and try again.
7278 route_endpoints.push((first_hop, params, amt_msat));
7284 // Because we've changed channel scores, it's possible we'll take different routes to the
7285 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
7286 // requires a too-high CLTV delta.
7287 route_endpoints.retain(|(first_hop, params, amt_msat)| {
7288 let route_params = RouteParameters::from_payment_params_and_value(
7289 params.clone(), *amt_msat);
7290 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
7291 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
7293 route_endpoints.truncate(route_count);
7294 assert_eq!(route_endpoints.len(), route_count);
7302 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
7303 use crate::sign::{EntropySource, KeysManager};
7304 use crate::ln::channelmanager;
7305 use crate::ln::features::Bolt11InvoiceFeatures;
7306 use crate::routing::gossip::NetworkGraph;
7307 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
7308 use crate::util::config::UserConfig;
7309 use crate::util::logger::{Logger, Record};
7310 use crate::util::test_utils::TestLogger;
7312 use criterion::Criterion;
7314 struct DummyLogger {}
7315 impl Logger for DummyLogger {
7316 fn log(&self, _record: &Record) {}
7319 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7320 let logger = TestLogger::new();
7321 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7322 let scorer = FixedPenaltyScorer::with_penalty(0);
7323 generate_routes(bench, &network_graph, scorer, &Default::default(),
7324 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
7327 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7328 let logger = TestLogger::new();
7329 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7330 let scorer = FixedPenaltyScorer::with_penalty(0);
7331 generate_routes(bench, &network_graph, scorer, &Default::default(),
7332 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7333 "generate_mpp_routes_with_zero_penalty_scorer");
7336 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7337 let logger = TestLogger::new();
7338 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7339 let params = ProbabilisticScoringFeeParameters::default();
7340 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7341 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
7342 "generate_routes_with_probabilistic_scorer");
7345 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7346 let logger = TestLogger::new();
7347 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7348 let params = ProbabilisticScoringFeeParameters::default();
7349 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7350 generate_routes(bench, &network_graph, scorer, ¶ms,
7351 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7352 "generate_mpp_routes_with_probabilistic_scorer");
7355 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7356 let logger = TestLogger::new();
7357 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7358 let params = ProbabilisticScoringFeeParameters::default();
7359 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7360 generate_routes(bench, &network_graph, scorer, ¶ms,
7361 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
7362 "generate_large_mpp_routes_with_probabilistic_scorer");
7365 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
7366 let logger = TestLogger::new();
7367 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7368 let mut params = ProbabilisticScoringFeeParameters::default();
7369 params.linear_success_probability = false;
7370 let scorer = ProbabilisticScorer::new(
7371 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7372 generate_routes(bench, &network_graph, scorer, ¶ms,
7373 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7374 "generate_routes_with_nonlinear_probabilistic_scorer");
7377 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
7378 let logger = TestLogger::new();
7379 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7380 let mut params = ProbabilisticScoringFeeParameters::default();
7381 params.linear_success_probability = false;
7382 let scorer = ProbabilisticScorer::new(
7383 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7384 generate_routes(bench, &network_graph, scorer, ¶ms,
7385 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7386 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
7389 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
7390 let logger = TestLogger::new();
7391 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7392 let mut params = ProbabilisticScoringFeeParameters::default();
7393 params.linear_success_probability = false;
7394 let scorer = ProbabilisticScorer::new(
7395 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7396 generate_routes(bench, &network_graph, scorer, ¶ms,
7397 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
7398 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
7401 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
7402 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
7403 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
7404 bench_name: &'static str,
7406 let payer = bench_utils::payer_pubkey();
7407 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7408 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7410 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
7411 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
7413 // ...then benchmark finding paths between the nodes we learned.
7415 bench.bench_function(bench_name, |b| b.iter(|| {
7416 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
7417 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
7418 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
7419 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());