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, Debug, 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 impl fmt::Display for Route {
384 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
385 log_route!(self).fmt(f)
389 const SERIALIZATION_VERSION: u8 = 1;
390 const MIN_SERIALIZATION_VERSION: u8 = 1;
392 impl Writeable for Route {
393 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
394 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
395 (self.paths.len() as u64).write(writer)?;
396 let mut blinded_tails = Vec::new();
397 for path in self.paths.iter() {
398 (path.hops.len() as u8).write(writer)?;
399 for (idx, hop) in path.hops.iter().enumerate() {
401 if let Some(blinded_tail) = &path.blinded_tail {
402 if blinded_tails.is_empty() {
403 blinded_tails = Vec::with_capacity(path.hops.len());
405 blinded_tails.push(None);
408 blinded_tails.push(Some(blinded_tail));
409 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
412 write_tlv_fields!(writer, {
413 // For compatibility with LDK versions prior to 0.0.117, we take the individual
414 // RouteParameters' fields and reconstruct them on read.
415 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
416 (2, blinded_tails, optional_vec),
417 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
418 (5, self.route_params.as_ref().map(|p| p.max_total_routing_fee_msat), option),
424 impl Readable for Route {
425 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
426 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
427 let path_count: u64 = Readable::read(reader)?;
428 if path_count == 0 { return Err(DecodeError::InvalidValue); }
429 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
430 let mut min_final_cltv_expiry_delta = u32::max_value();
431 for _ in 0..path_count {
432 let hop_count: u8 = Readable::read(reader)?;
433 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
434 for _ in 0..hop_count {
435 hops.push(Readable::read(reader)?);
437 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
438 min_final_cltv_expiry_delta =
439 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
440 paths.push(Path { hops, blinded_tail: None });
442 _init_and_read_len_prefixed_tlv_fields!(reader, {
443 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
444 (2, blinded_tails, optional_vec),
445 (3, final_value_msat, option),
446 (5, max_total_routing_fee_msat, option)
448 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
449 if blinded_tails.len() != 0 {
450 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
451 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
452 path.blinded_tail = blinded_tail_opt;
456 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
457 let route_params = match (payment_params, final_value_msat) {
458 (Some(payment_params), Some(final_value_msat)) => {
459 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
464 Ok(Route { paths, route_params })
468 /// Parameters needed to find a [`Route`].
470 /// Passed to [`find_route`] and [`build_route_from_hops`].
471 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
472 pub struct RouteParameters {
473 /// The parameters of the failed payment path.
474 pub payment_params: PaymentParameters,
476 /// The amount in msats sent on the failed payment path.
477 pub final_value_msat: u64,
479 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
481 /// This limit also applies to the total fees that may arise while retrying failed payment
484 /// Default value: `None`
485 pub max_total_routing_fee_msat: Option<u64>,
488 impl RouteParameters {
489 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
490 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
491 Self { payment_params, final_value_msat, max_total_routing_fee_msat: None }
495 impl Writeable for RouteParameters {
496 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
497 write_tlv_fields!(writer, {
498 (0, self.payment_params, required),
499 (1, self.max_total_routing_fee_msat, option),
500 (2, self.final_value_msat, required),
501 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
502 // `RouteParameters` directly. For compatibility, we write it here.
503 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
509 impl Readable for RouteParameters {
510 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
511 _init_and_read_len_prefixed_tlv_fields!(reader, {
512 (0, payment_params, (required: ReadableArgs, 0)),
513 (1, max_total_routing_fee_msat, option),
514 (2, final_value_msat, required),
515 (4, final_cltv_delta, option),
517 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
518 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
519 if final_cltv_expiry_delta == &0 {
520 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
525 final_value_msat: final_value_msat.0.unwrap(),
526 max_total_routing_fee_msat,
531 /// Maximum total CTLV difference we allow for a full payment path.
532 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
534 /// Maximum number of paths we allow an (MPP) payment to have.
535 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
536 // limits, but for now more than 10 paths likely carries too much one-path failure.
537 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
539 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
541 // The median hop CLTV expiry delta currently seen in the network.
542 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
544 // During routing, we only consider paths shorter than our maximum length estimate.
545 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
546 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
547 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
549 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
550 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
551 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
552 // (payment_secret and total_msat) = 93 bytes for the final hop.
553 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
554 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
555 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
557 /// Information used to route a payment.
558 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
559 pub struct PaymentParameters {
560 /// Information about the payee, such as their features and route hints for their channels.
563 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
564 pub expiry_time: Option<u64>,
566 /// The maximum total CLTV delta we accept for the route.
567 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
568 pub max_total_cltv_expiry_delta: u32,
570 /// The maximum number of paths that may be used by (MPP) payments.
571 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
572 pub max_path_count: u8,
574 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
575 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
576 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
577 /// increasing failure probability for those paths.
579 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
580 /// restriction have been found. While paths which meet this criteria will be searched for, it
581 /// is ultimately up to the scorer to select them over other paths.
583 /// A value of 0 will allow payments up to and including a channel's total announced usable
584 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
587 pub max_channel_saturation_power_of_half: u8,
589 /// A list of SCIDs which this payment was previously attempted over and which caused the
590 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
592 pub previously_failed_channels: Vec<u64>,
595 impl Writeable for PaymentParameters {
596 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
597 let mut clear_hints = &vec![];
598 let mut blinded_hints = &vec![];
600 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
601 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
603 write_tlv_fields!(writer, {
604 (0, self.payee.node_id(), option),
605 (1, self.max_total_cltv_expiry_delta, required),
606 (2, self.payee.features(), option),
607 (3, self.max_path_count, required),
608 (4, *clear_hints, required_vec),
609 (5, self.max_channel_saturation_power_of_half, required),
610 (6, self.expiry_time, option),
611 (7, self.previously_failed_channels, required_vec),
612 (8, *blinded_hints, optional_vec),
613 (9, self.payee.final_cltv_expiry_delta(), option),
619 impl ReadableArgs<u32> for PaymentParameters {
620 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
621 _init_and_read_len_prefixed_tlv_fields!(reader, {
622 (0, payee_pubkey, option),
623 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
624 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
625 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
626 (4, clear_route_hints, required_vec),
627 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
628 (6, expiry_time, option),
629 (7, previously_failed_channels, optional_vec),
630 (8, blinded_route_hints, optional_vec),
631 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
633 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
634 let payee = if blinded_route_hints.len() != 0 {
635 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
637 route_hints: blinded_route_hints,
638 features: features.and_then(|f: Features| f.bolt12()),
642 route_hints: clear_route_hints,
643 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
644 features: features.and_then(|f| f.bolt11()),
645 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
649 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
650 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
652 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
654 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
660 impl PaymentParameters {
661 /// Creates a payee with the node id of the given `pubkey`.
663 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
665 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
667 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
669 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
670 max_path_count: DEFAULT_MAX_PATH_COUNT,
671 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
672 previously_failed_channels: Vec::new(),
676 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
678 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
681 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
682 /// whether your router will be allowed to find a multi-part route for this payment. If you
683 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
684 /// [`RecipientOnionFields::secret_only`].
686 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
687 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
688 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
689 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
690 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
693 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
694 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
695 /// [`PaymentParameters::expiry_time`].
696 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
697 Self::blinded(invoice.payment_paths().to_vec())
698 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
699 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
702 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
703 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
705 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
707 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
708 max_path_count: DEFAULT_MAX_PATH_COUNT,
709 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
710 previously_failed_channels: Vec::new(),
714 /// Includes the payee's features. Errors if the parameters were not initialized with
715 /// [`PaymentParameters::from_bolt12_invoice`].
717 /// This is not exported to bindings users since bindings don't support move semantics
718 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
720 Payee::Clear { .. } => Err(()),
721 Payee::Blinded { route_hints, .. } =>
722 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
726 /// Includes the payee's features. Errors if the parameters were initialized with
727 /// [`PaymentParameters::from_bolt12_invoice`].
729 /// This is not exported to bindings users since bindings don't support move semantics
730 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
732 Payee::Blinded { .. } => Err(()),
733 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
735 payee: Payee::Clear {
736 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
742 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
743 /// [`PaymentParameters::from_bolt12_invoice`].
745 /// This is not exported to bindings users since bindings don't support move semantics
746 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
748 Payee::Blinded { .. } => Err(()),
749 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
751 payee: Payee::Clear {
752 route_hints, node_id, features, final_cltv_expiry_delta,
758 /// Includes a payment expiration in seconds relative to the UNIX epoch.
760 /// This is not exported to bindings users since bindings don't support move semantics
761 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
762 Self { expiry_time: Some(expiry_time), ..self }
765 /// Includes a limit for the total CLTV expiry delta which is considered during routing
767 /// This is not exported to bindings users since bindings don't support move semantics
768 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
769 Self { max_total_cltv_expiry_delta, ..self }
772 /// Includes a limit for the maximum number of payment paths that may be used.
774 /// This is not exported to bindings users since bindings don't support move semantics
775 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
776 Self { max_path_count, ..self }
779 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
780 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
782 /// This is not exported to bindings users since bindings don't support move semantics
783 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
784 Self { max_channel_saturation_power_of_half, ..self }
788 /// The recipient of a payment, differing based on whether they've hidden their identity with route
790 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
792 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
793 /// will be included in the final [`Route`].
795 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
797 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
798 /// Features supported by the payee.
800 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
802 features: Option<Bolt12InvoiceFeatures>,
804 /// The recipient included these route hints in their BOLT11 invoice.
806 /// The node id of the payee.
808 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
809 route_hints: Vec<RouteHint>,
810 /// Features supported by the payee.
812 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
813 /// does not contain any features.
815 /// [`for_keysend`]: PaymentParameters::for_keysend
816 features: Option<Bolt11InvoiceFeatures>,
817 /// The minimum CLTV delta at the end of the route. This value must not be zero.
818 final_cltv_expiry_delta: u32,
823 fn node_id(&self) -> Option<PublicKey> {
825 Self::Clear { node_id, .. } => Some(*node_id),
829 fn node_features(&self) -> Option<NodeFeatures> {
831 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
832 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
835 fn supports_basic_mpp(&self) -> bool {
837 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
838 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
841 fn features(&self) -> Option<FeaturesRef> {
843 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
844 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
847 fn final_cltv_expiry_delta(&self) -> Option<u32> {
849 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
853 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
855 Self::Blinded { route_hints, .. } => &route_hints[..],
856 Self::Clear { .. } => &[]
860 fn unblinded_route_hints(&self) -> &[RouteHint] {
862 Self::Blinded { .. } => &[],
863 Self::Clear { route_hints, .. } => &route_hints[..]
868 enum FeaturesRef<'a> {
869 Bolt11(&'a Bolt11InvoiceFeatures),
870 Bolt12(&'a Bolt12InvoiceFeatures),
873 Bolt11(Bolt11InvoiceFeatures),
874 Bolt12(Bolt12InvoiceFeatures),
878 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
880 Self::Bolt12(f) => Some(f),
884 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
886 Self::Bolt11(f) => Some(f),
892 impl<'a> Writeable for FeaturesRef<'a> {
893 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
895 Self::Bolt11(f) => Ok(f.write(w)?),
896 Self::Bolt12(f) => Ok(f.write(w)?),
901 impl ReadableArgs<bool> for Features {
902 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
903 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
904 Ok(Self::Bolt12(Readable::read(reader)?))
908 /// A list of hops along a payment path terminating with a channel to the recipient.
909 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
910 pub struct RouteHint(pub Vec<RouteHintHop>);
912 impl Writeable for RouteHint {
913 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
914 (self.0.len() as u64).write(writer)?;
915 for hop in self.0.iter() {
922 impl Readable for RouteHint {
923 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
924 let hop_count: u64 = Readable::read(reader)?;
925 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
926 for _ in 0..hop_count {
927 hops.push(Readable::read(reader)?);
933 /// A channel descriptor for a hop along a payment path.
934 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
935 pub struct RouteHintHop {
936 /// The node_id of the non-target end of the route
937 pub src_node_id: PublicKey,
938 /// The short_channel_id of this channel
939 pub short_channel_id: u64,
940 /// The fees which must be paid to use this channel
941 pub fees: RoutingFees,
942 /// The difference in CLTV values between this node and the next node.
943 pub cltv_expiry_delta: u16,
944 /// The minimum value, in msat, which must be relayed to the next hop.
945 pub htlc_minimum_msat: Option<u64>,
946 /// The maximum value in msat available for routing with a single HTLC.
947 pub htlc_maximum_msat: Option<u64>,
950 impl_writeable_tlv_based!(RouteHintHop, {
951 (0, src_node_id, required),
952 (1, htlc_minimum_msat, option),
953 (2, short_channel_id, required),
954 (3, htlc_maximum_msat, option),
956 (6, cltv_expiry_delta, required),
959 #[derive(Eq, PartialEq)]
960 struct RouteGraphNode {
962 lowest_fee_to_node: u64,
963 total_cltv_delta: u32,
964 // The maximum value a yet-to-be-constructed payment path might flow through this node.
965 // This value is upper-bounded by us by:
966 // - how much is needed for a path being constructed
967 // - how much value can channels following this node (up to the destination) can contribute,
968 // considering their capacity and fees
969 value_contribution_msat: u64,
970 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
971 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
972 path_htlc_minimum_msat: u64,
973 /// All penalties incurred from this hop on the way to the destination, as calculated using
975 path_penalty_msat: u64,
976 /// The number of hops walked up to this node.
977 path_length_to_node: u8,
980 impl cmp::Ord for RouteGraphNode {
981 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
982 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
983 .saturating_add(other.path_penalty_msat);
984 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
985 .saturating_add(self.path_penalty_msat);
986 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
990 impl cmp::PartialOrd for RouteGraphNode {
991 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
992 Some(self.cmp(other))
996 /// A wrapper around the various hop representations.
998 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
999 #[derive(Clone, Debug)]
1000 enum CandidateRouteHop<'a> {
1001 /// A hop from the payer, where the outbound liquidity is known.
1003 details: &'a ChannelDetails,
1005 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
1007 info: DirectedChannelInfo<'a>,
1008 short_channel_id: u64,
1010 /// A hop to the payee found in the BOLT 11 payment invoice, though not necessarily a direct
1013 hint: &'a RouteHintHop,
1015 /// The payee's identity is concealed behind blinded paths provided in a BOLT 12 invoice.
1017 hint: &'a (BlindedPayInfo, BlindedPath),
1020 /// Similar to [`Self::Blinded`], but the path here has 1 blinded hop. `BlindedPayInfo` provided
1021 /// for 1-hop blinded paths is ignored because it is meant to apply to the hops *between* the
1022 /// introduction node and the destination. Useful for tracking that we need to include a blinded
1023 /// path at the end of our [`Route`].
1025 hint: &'a (BlindedPayInfo, BlindedPath),
1030 impl<'a> CandidateRouteHop<'a> {
1031 fn short_channel_id(&self) -> Option<u64> {
1033 CandidateRouteHop::FirstHop { details } => Some(details.get_outbound_payment_scid().unwrap()),
1034 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
1035 CandidateRouteHop::PrivateHop { hint } => Some(hint.short_channel_id),
1036 CandidateRouteHop::Blinded { .. } => None,
1037 CandidateRouteHop::OneHopBlinded { .. } => None,
1041 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1042 fn features(&self) -> ChannelFeatures {
1044 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
1045 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
1046 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
1047 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
1048 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
1052 fn cltv_expiry_delta(&self) -> u32 {
1054 CandidateRouteHop::FirstHop { .. } => 0,
1055 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1056 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
1057 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1058 CandidateRouteHop::OneHopBlinded { .. } => 0,
1062 fn htlc_minimum_msat(&self) -> u64 {
1064 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_minimum_msat,
1065 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1066 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
1067 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1068 CandidateRouteHop::OneHopBlinded { .. } => 0,
1072 fn fees(&self) -> RoutingFees {
1074 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1075 base_msat: 0, proportional_millionths: 0,
1077 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1078 CandidateRouteHop::PrivateHop { hint } => hint.fees,
1079 CandidateRouteHop::Blinded { hint, .. } => {
1081 base_msat: hint.0.fee_base_msat,
1082 proportional_millionths: hint.0.fee_proportional_millionths
1085 CandidateRouteHop::OneHopBlinded { .. } =>
1086 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1090 fn effective_capacity(&self) -> EffectiveCapacity {
1092 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
1093 liquidity_msat: details.next_outbound_htlc_limit_msat,
1095 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1096 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }} =>
1097 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1098 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }} =>
1099 EffectiveCapacity::Infinite,
1100 CandidateRouteHop::Blinded { hint, .. } =>
1101 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1102 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1106 fn id(&self, channel_direction: bool /* src_node_id < target_node_id */) -> CandidateHopId {
1108 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1109 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1110 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), channel_direction)),
1113 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1115 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1123 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1124 enum CandidateHopId {
1125 /// Contains (scid, src_node_id < target_node_id)
1127 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1132 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1133 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1135 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1136 EffectiveCapacity::Infinite => u64::max_value(),
1137 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1138 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1139 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1140 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1141 // expected to have been generated from up-to-date capacity information.
1142 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1143 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1144 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1148 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1149 -> bool where I1::Item: PartialEq<I2::Item> {
1151 let a = iter_a.next();
1152 let b = iter_b.next();
1153 if a.is_none() && b.is_none() { return true; }
1154 if a.is_none() || b.is_none() { return false; }
1155 if a.unwrap().ne(&b.unwrap()) { return false; }
1159 /// It's useful to keep track of the hops associated with the fees required to use them,
1160 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1161 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1162 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1164 struct PathBuildingHop<'a> {
1165 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
1166 // is a larger refactor and will require careful performance analysis.
1168 candidate: CandidateRouteHop<'a>,
1171 /// All the fees paid *after* this channel on the way to the destination
1172 next_hops_fee_msat: u64,
1173 /// Fee paid for the use of the current channel (see candidate.fees()).
1174 /// The value will be actually deducted from the counterparty balance on the previous link.
1175 hop_use_fee_msat: u64,
1176 /// Used to compare channels when choosing the for routing.
1177 /// Includes paying for the use of a hop and the following hops, as well as
1178 /// an estimated cost of reaching this hop.
1179 /// Might get stale when fees are recomputed. Primarily for internal use.
1180 total_fee_msat: u64,
1181 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1182 /// walk and may be invalid thereafter.
1183 path_htlc_minimum_msat: u64,
1184 /// All penalties incurred from this channel on the way to the destination, as calculated using
1185 /// channel scoring.
1186 path_penalty_msat: u64,
1187 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1188 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1189 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1190 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1191 /// avoid processing them again.
1192 was_processed: bool,
1193 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1194 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1195 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1196 // value_contribution_msat, which requires tracking it here. See comments below where it is
1197 // used for more info.
1198 value_contribution_msat: u64,
1201 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1202 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1203 let mut debug_struct = f.debug_struct("PathBuildingHop");
1205 .field("node_id", &self.node_id)
1206 .field("short_channel_id", &self.candidate.short_channel_id())
1207 .field("total_fee_msat", &self.total_fee_msat)
1208 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1209 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1210 .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)))
1211 .field("path_penalty_msat", &self.path_penalty_msat)
1212 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1213 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1214 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1215 let debug_struct = debug_struct
1216 .field("value_contribution_msat", &self.value_contribution_msat);
1217 debug_struct.finish()
1221 // Instantiated with a list of hops with correct data in them collected during path finding,
1222 // an instance of this struct should be further modified only via given methods.
1224 struct PaymentPath<'a> {
1225 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1228 impl<'a> PaymentPath<'a> {
1229 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1230 fn get_value_msat(&self) -> u64 {
1231 self.hops.last().unwrap().0.fee_msat
1234 fn get_path_penalty_msat(&self) -> u64 {
1235 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1238 fn get_total_fee_paid_msat(&self) -> u64 {
1239 if self.hops.len() < 1 {
1243 // Can't use next_hops_fee_msat because it gets outdated.
1244 for (i, (hop, _)) in self.hops.iter().enumerate() {
1245 if i != self.hops.len() - 1 {
1246 result += hop.fee_msat;
1252 fn get_cost_msat(&self) -> u64 {
1253 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1256 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1257 // to change fees may result in an inconsistency.
1259 // Sometimes we call this function right after constructing a path which is inconsistent in
1260 // that it the value being transferred has decreased while we were doing path finding, leading
1261 // to the fees being paid not lining up with the actual limits.
1263 // Note that this function is not aware of the available_liquidity limit, and thus does not
1264 // support increasing the value being transferred beyond what was selected during the initial
1266 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
1267 let mut total_fee_paid_msat = 0 as u64;
1268 for i in (0..self.hops.len()).rev() {
1269 let last_hop = i == self.hops.len() - 1;
1271 // For non-last-hop, this value will represent the fees paid on the current hop. It
1272 // will consist of the fees for the use of the next hop, and extra fees to match
1273 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1274 let mut cur_hop_fees_msat = 0;
1276 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1279 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1280 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1281 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1282 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1283 // set it too high just to maliciously take more fees by exploiting this
1284 // match htlc_minimum_msat logic.
1285 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1286 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1287 // Note that there is a risk that *previous hops* (those closer to us, as we go
1288 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1290 // This might make us end up with a broken route, although this should be super-rare
1291 // in practice, both because of how healthy channels look like, and how we pick
1292 // channels in add_entry.
1293 // Also, this can't be exploited more heavily than *announce a free path and fail
1295 cur_hop_transferred_amount_msat += extra_fees_msat;
1296 total_fee_paid_msat += extra_fees_msat;
1297 cur_hop_fees_msat += extra_fees_msat;
1301 // Final hop is a special case: it usually has just value_msat (by design), but also
1302 // it still could overpay for the htlc_minimum_msat.
1303 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1305 // Propagate updated fees for the use of the channels to one hop back, where they
1306 // will be actually paid (fee_msat). The last hop is handled above separately.
1307 cur_hop.fee_msat = cur_hop_fees_msat;
1310 // Fee for the use of the current hop which will be deducted on the previous hop.
1311 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1312 // this channel is free for us.
1314 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1315 cur_hop.hop_use_fee_msat = new_fee;
1316 total_fee_paid_msat += new_fee;
1318 // It should not be possible because this function is called only to reduce the
1319 // value. In that case, compute_fee was already called with the same fees for
1320 // larger amount and there was no overflow.
1329 /// Calculate the fees required to route the given amount over a channel with the given fees.
1330 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1331 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1332 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1336 /// Calculate the fees required to route the given amount over a channel with the given fees,
1337 /// saturating to [`u64::max_value`].
1338 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1339 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1340 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1341 .saturating_add(channel_fees.base_msat as u64)
1344 /// The default `features` we assume for a node in a route, when no `features` are known about that
1347 /// Default features are:
1348 /// * variable_length_onion_optional
1349 fn default_node_features() -> NodeFeatures {
1350 let mut features = NodeFeatures::empty();
1351 features.set_variable_length_onion_optional();
1355 struct LoggedPayeePubkey(Option<PublicKey>);
1356 impl fmt::Display for LoggedPayeePubkey {
1357 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1360 "payee node id ".fmt(f)?;
1364 "blinded payee".fmt(f)
1370 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1371 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1372 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1374 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1375 "blinded route hint with introduction node id ".fmt(f)?;
1376 hint.1.introduction_node_id.fmt(f)?;
1377 " and blinding point ".fmt(f)?;
1378 hint.1.blinding_point.fmt(f)
1380 CandidateRouteHop::FirstHop { .. } => {
1381 "first hop with SCID ".fmt(f)?;
1382 self.0.short_channel_id().unwrap().fmt(f)
1384 CandidateRouteHop::PrivateHop { .. } => {
1385 "route hint with SCID ".fmt(f)?;
1386 self.0.short_channel_id().unwrap().fmt(f)
1390 self.0.short_channel_id().unwrap().fmt(f)
1397 fn sort_first_hop_channels(
1398 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1399 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1401 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1402 // most like to use.
1404 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1405 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1408 // Second, because simply always sorting in descending order would always use our largest
1409 // available outbound capacity, needlessly fragmenting our available channel capacities,
1410 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1411 // which have enough, but not too much, capacity for the payment.
1413 // Available outbound balances factor in liquidity already reserved for previously found paths.
1414 channels.sort_unstable_by(|chan_a, chan_b| {
1415 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1416 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1417 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1418 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1419 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1420 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1421 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1422 // Sort in descending order
1423 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1425 // Sort in ascending order
1426 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1431 /// Finds a route from us (payer) to the given target node (payee).
1433 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1434 /// in the given [`RouteParameters::payment_params`].
1435 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1437 /// Private routing paths between a public node and the target may be included in the `payee` field
1438 /// of [`RouteParameters::payment_params`].
1440 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1441 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1442 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1444 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1445 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1446 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1450 /// Panics if first_hops contains channels without `short_channel_id`s;
1451 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1453 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1454 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1455 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1456 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1457 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1458 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1459 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1460 ) -> Result<Route, LightningError>
1461 where L::Target: Logger, GL::Target: Logger {
1462 let graph_lock = network_graph.read_only();
1463 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1464 scorer, score_params, random_seed_bytes)?;
1465 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1469 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1470 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1471 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1472 _random_seed_bytes: &[u8; 32]
1473 ) -> Result<Route, LightningError>
1474 where L::Target: Logger {
1476 let payment_params = &route_params.payment_params;
1477 let final_value_msat = route_params.final_value_msat;
1478 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1479 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1480 // so use a dummy id for this in the blinded case.
1481 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1482 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1483 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1484 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1485 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1487 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1488 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1491 if final_value_msat > MAX_VALUE_MSAT {
1492 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1495 if final_value_msat == 0 {
1496 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1499 match &payment_params.payee {
1500 Payee::Clear { route_hints, node_id, .. } => {
1501 for route in route_hints.iter() {
1502 for hop in &route.0 {
1503 if hop.src_node_id == *node_id {
1504 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1509 Payee::Blinded { route_hints, .. } => {
1510 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1511 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});
1513 for (_, blinded_path) in route_hints.iter() {
1514 if blinded_path.blinded_hops.len() == 0 {
1515 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1516 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1517 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1518 } else if blinded_path.blinded_hops.len() == 1 &&
1519 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1520 && p.introduction_node_id != blinded_path.introduction_node_id)
1522 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1527 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1528 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1529 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});
1532 // The general routing idea is the following:
1533 // 1. Fill first/last hops communicated by the caller.
1534 // 2. Attempt to construct a path from payer to payee for transferring
1535 // any ~sufficient (described later) value.
1536 // If succeed, remember which channels were used and how much liquidity they have available,
1537 // so that future paths don't rely on the same liquidity.
1538 // 3. Proceed to the next step if:
1539 // - we hit the recommended target value;
1540 // - OR if we could not construct a new path. Any next attempt will fail too.
1541 // Otherwise, repeat step 2.
1542 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1543 // (not recommended value).
1544 // 5. If yes, proceed. If not, fail routing.
1545 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1546 // transferred up to the transfer target value.
1547 // 7. Reduce the value of the last path until we are sending only the target value.
1548 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1549 // them so that we're not sending two HTLCs along the same path.
1551 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1552 // distance from the payee
1554 // We are not a faithful Dijkstra's implementation because we can change values which impact
1555 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1556 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1557 // the value we are currently attempting to send over a path, we simply reduce the value being
1558 // sent along the path for any hops after that channel. This may imply that later fees (which
1559 // we've already tabulated) are lower because a smaller value is passing through the channels
1560 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1561 // channels which were selected earlier (and which may still be used for other paths without a
1562 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1565 // One potentially problematic case for this algorithm would be if there are many
1566 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1567 // graph walking), we may never find a path which is not liquidity-limited and has lower
1568 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1569 // Because we only consider paths with at least 5% of the total value being sent, the damage
1570 // from such a case should be limited, however this could be further reduced in the future by
1571 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1572 // limits for the purposes of fee calculation.
1574 // Alternatively, we could store more detailed path information in the heap (targets, below)
1575 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1576 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1577 // and practically (as we would need to store dynamically-allocated path information in heap
1578 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1579 // results of such an algorithm would likely be biased towards lower-value paths.
1581 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1582 // outside of our current search value, running a path search more times to gather candidate
1583 // paths at different values. While this may be acceptable, further path searches may increase
1584 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1585 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1586 // the same time, remaining generic across different payment values.
1588 let network_channels = network_graph.channels();
1589 let network_nodes = network_graph.nodes();
1591 if payment_params.max_path_count == 0 {
1592 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1595 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1596 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1598 let allow_mpp = if payment_params.max_path_count == 1 {
1600 } else if payment_params.payee.supports_basic_mpp() {
1602 } else if let Some(payee) = payee_node_id_opt {
1603 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1604 |info| info.features.supports_basic_mpp()))
1607 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1608 LoggedPayeePubkey(payment_params.payee.node_id()), if allow_mpp { "with" } else { "without" },
1609 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1612 // Prepare the data we'll use for payee-to-payer search by
1613 // inserting first hops suggested by the caller as targets.
1614 // Our search will then attempt to reach them while traversing from the payee node.
1615 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1616 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1617 if let Some(hops) = first_hops {
1619 if chan.get_outbound_payment_scid().is_none() {
1620 panic!("first_hops should be filled in with usable channels, not pending ones");
1622 if chan.counterparty.node_id == *our_node_pubkey {
1623 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1626 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1627 .or_insert(Vec::new())
1630 if first_hop_targets.is_empty() {
1631 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1635 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1636 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1637 // adding duplicate entries when we find a better path to a given node.
1638 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1640 // Map from node_id to information about the best current path to that node, including feerate
1642 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1644 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1645 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1646 // htlc_minimum with extra fees while still finding a cheaper path.
1647 let mut hit_minimum_limit;
1649 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1650 // We start with a path_value of the exact amount we want, and if that generates a route we may
1651 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1652 // amount we want in total across paths, selecting the best subset at the end.
1653 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1654 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1655 let mut path_value_msat = final_value_msat;
1657 // Routing Fragmentation Mitigation heuristic:
1659 // Routing fragmentation across many payment paths increases the overall routing
1660 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1661 // Taking too many smaller paths also increases the chance of payment failure.
1662 // Thus to avoid this effect, we require from our collected links to provide
1663 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1664 // This requirement is currently set to be 1/max_path_count of the payment
1665 // value to ensure we only ever return routes that do not violate this limit.
1666 let minimal_value_contribution_msat: u64 = if allow_mpp {
1667 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1672 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1673 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1674 // drop the requirement by setting this to 0.
1675 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1677 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1678 // determine if the channel can be used by additional MPP paths or to inform path finding
1679 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1680 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1682 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1683 HashMap::with_capacity(network_nodes.len());
1685 // Keeping track of how much value we already collected across other paths. Helps to decide
1686 // when we want to stop looking for new paths.
1687 let mut already_collected_value_msat = 0;
1689 for (_, channels) in first_hop_targets.iter_mut() {
1690 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1694 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1695 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1697 // Remember how many candidates we ignored to allow for some logging afterwards.
1698 let mut num_ignored_value_contribution = 0;
1699 let mut num_ignored_path_length_limit = 0;
1700 let mut num_ignored_cltv_delta_limit = 0;
1701 let mut num_ignored_previously_failed = 0;
1702 let mut num_ignored_total_fee_limit = 0;
1704 macro_rules! add_entry {
1705 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1706 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1707 // since that value has to be transferred over this channel.
1708 // Returns whether this channel caused an update to `targets`.
1709 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1710 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1711 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1712 // We "return" whether we updated the path at the end, and how much we can route via
1713 // this channel, via this:
1714 let mut did_add_update_path_to_src_node = None;
1715 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1716 // practice these cases should be caught earlier:
1717 // - for regular channels at channel announcement (TODO)
1718 // - for first and last hops early in get_route
1719 if $src_node_id != $dest_node_id {
1720 let scid_opt = $candidate.short_channel_id();
1721 let effective_capacity = $candidate.effective_capacity();
1722 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1724 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1725 // It may be misleading because we might later choose to reduce the value transferred
1726 // over these channels, and the channel which was insufficient might become sufficient.
1727 // Worst case: we drop a good channel here because it can't cover the high following
1728 // fees caused by one expensive channel, but then this channel could have been used
1729 // if the amount being transferred over this path is lower.
1730 // We do this for now, but this is a subject for removal.
1731 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1732 let used_liquidity_msat = used_liquidities
1733 .get(&$candidate.id($src_node_id < $dest_node_id))
1734 .map_or(0, |used_liquidity_msat| {
1735 available_value_contribution_msat = available_value_contribution_msat
1736 .saturating_sub(*used_liquidity_msat);
1737 *used_liquidity_msat
1740 // Verify the liquidity offered by this channel complies to the minimal contribution.
1741 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1742 // Do not consider candidate hops that would exceed the maximum path length.
1743 let path_length_to_node = $next_hops_path_length + 1;
1744 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1746 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1747 // In order to already account for some of the privacy enhancing random CLTV
1748 // expiry delta offset we add on top later, we subtract a rough estimate
1749 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1750 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1751 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1752 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1753 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1754 .saturating_add($candidate.cltv_expiry_delta());
1755 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1757 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1758 // Includes paying fees for the use of the following channels.
1759 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1760 Some(result) => result,
1761 // Can't overflow due to how the values were computed right above.
1762 None => unreachable!(),
1764 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1765 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1766 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1768 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1769 let may_overpay_to_meet_path_minimum_msat =
1770 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1771 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1772 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1773 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1775 let payment_failed_on_this_channel = scid_opt.map_or(false,
1776 |scid| payment_params.previously_failed_channels.contains(&scid));
1778 let should_log_candidate = match $candidate {
1779 CandidateRouteHop::FirstHop { .. } => true,
1780 CandidateRouteHop::PrivateHop { .. } => true,
1781 CandidateRouteHop::Blinded { .. } => true,
1785 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1786 // bother considering this channel. If retrying with recommended_value_msat may
1787 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1788 // around again with a higher amount.
1789 if !contributes_sufficient_value {
1790 if should_log_candidate {
1791 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
1793 num_ignored_value_contribution += 1;
1794 } else if exceeds_max_path_length {
1795 if should_log_candidate {
1796 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
1798 num_ignored_path_length_limit += 1;
1799 } else if exceeds_cltv_delta_limit {
1800 if should_log_candidate {
1801 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
1803 num_ignored_cltv_delta_limit += 1;
1804 } else if payment_failed_on_this_channel {
1805 if should_log_candidate {
1806 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
1808 num_ignored_previously_failed += 1;
1809 } else if may_overpay_to_meet_path_minimum_msat {
1810 hit_minimum_limit = true;
1811 } else if over_path_minimum_msat {
1812 // Note that low contribution here (limited by available_liquidity_msat)
1813 // might violate htlc_minimum_msat on the hops which are next along the
1814 // payment path (upstream to the payee). To avoid that, we recompute
1815 // path fees knowing the final path contribution after constructing it.
1816 let path_htlc_minimum_msat = cmp::max(
1817 compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1818 .saturating_add($next_hops_path_htlc_minimum_msat),
1819 $candidate.htlc_minimum_msat());
1820 let hm_entry = dist.entry($src_node_id);
1821 let old_entry = hm_entry.or_insert_with(|| {
1822 // If there was previously no known way to access the source node
1823 // (recall it goes payee-to-payer) of short_channel_id, first add a
1824 // semi-dummy record just to compute the fees to reach the source node.
1825 // This will affect our decision on selecting short_channel_id
1826 // as a way to reach the $dest_node_id.
1828 node_id: $dest_node_id.clone(),
1829 candidate: $candidate.clone(),
1831 next_hops_fee_msat: u64::max_value(),
1832 hop_use_fee_msat: u64::max_value(),
1833 total_fee_msat: u64::max_value(),
1834 path_htlc_minimum_msat,
1835 path_penalty_msat: u64::max_value(),
1836 was_processed: false,
1837 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1838 value_contribution_msat,
1842 #[allow(unused_mut)] // We only use the mut in cfg(test)
1843 let mut should_process = !old_entry.was_processed;
1844 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1846 // In test/fuzzing builds, we do extra checks to make sure the skipping
1847 // of already-seen nodes only happens in cases we expect (see below).
1848 if !should_process { should_process = true; }
1852 let mut hop_use_fee_msat = 0;
1853 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1855 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1856 // will have the same effective-fee
1857 if $src_node_id != our_node_id {
1858 // Note that `u64::max_value` means we'll always fail the
1859 // `old_entry.total_fee_msat > total_fee_msat` check below
1860 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1861 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1864 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
1865 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1866 if total_fee_msat > max_total_routing_fee_msat {
1867 if should_log_candidate {
1868 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
1870 num_ignored_total_fee_limit += 1;
1872 let channel_usage = ChannelUsage {
1873 amount_msat: amount_to_transfer_over_msat,
1874 inflight_htlc_msat: used_liquidity_msat,
1877 let channel_penalty_msat = scid_opt.map_or(0,
1878 |scid| scorer.channel_penalty_msat(scid, &$src_node_id, &$dest_node_id,
1879 channel_usage, score_params));
1880 let path_penalty_msat = $next_hops_path_penalty_msat
1881 .saturating_add(channel_penalty_msat);
1882 let new_graph_node = RouteGraphNode {
1883 node_id: $src_node_id,
1884 lowest_fee_to_node: total_fee_msat,
1885 total_cltv_delta: hop_total_cltv_delta,
1886 value_contribution_msat,
1887 path_htlc_minimum_msat,
1889 path_length_to_node,
1892 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1893 // if this way is cheaper than the already known
1894 // (considering the cost to "reach" this channel from the route destination,
1895 // the cost of using this channel,
1896 // and the cost of routing to the source node of this channel).
1897 // Also, consider that htlc_minimum_msat_difference, because we might end up
1898 // paying it. Consider the following exploit:
1899 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1900 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1901 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1902 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1904 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1905 // but it may require additional tracking - we don't want to double-count
1906 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1907 // can't use something that may decrease on future hops.
1908 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1909 .saturating_add(old_entry.path_penalty_msat);
1910 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1911 .saturating_add(path_penalty_msat);
1913 if !old_entry.was_processed && new_cost < old_cost {
1914 targets.push(new_graph_node);
1915 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1916 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1917 old_entry.total_fee_msat = total_fee_msat;
1918 old_entry.node_id = $dest_node_id.clone();
1919 old_entry.candidate = $candidate.clone();
1920 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1921 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1922 old_entry.path_penalty_msat = path_penalty_msat;
1923 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1925 old_entry.value_contribution_msat = value_contribution_msat;
1927 did_add_update_path_to_src_node = Some(value_contribution_msat);
1928 } else if old_entry.was_processed && new_cost < old_cost {
1929 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1931 // If we're skipping processing a node which was previously
1932 // processed even though we found another path to it with a
1933 // cheaper fee, check that it was because the second path we
1934 // found (which we are processing now) has a lower value
1935 // contribution due to an HTLC minimum limit.
1937 // e.g. take a graph with two paths from node 1 to node 2, one
1938 // through channel A, and one through channel B. Channel A and
1939 // B are both in the to-process heap, with their scores set by
1940 // a higher htlc_minimum than fee.
1941 // Channel A is processed first, and the channels onwards from
1942 // node 1 are added to the to-process heap. Thereafter, we pop
1943 // Channel B off of the heap, note that it has a much more
1944 // restrictive htlc_maximum_msat, and recalculate the fees for
1945 // all of node 1's channels using the new, reduced, amount.
1947 // This would be bogus - we'd be selecting a higher-fee path
1948 // with a lower htlc_maximum_msat instead of the one we'd
1949 // already decided to use.
1950 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1952 value_contribution_msat + path_penalty_msat <
1953 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1962 did_add_update_path_to_src_node
1966 let default_node_features = default_node_features();
1968 // Find ways (channels with destination) to reach a given node and store them
1969 // in the corresponding data structures (routing graph etc).
1970 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1971 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1972 // This data can later be helpful to optimize routing (pay lower fees).
1973 macro_rules! add_entries_to_cheapest_to_target_node {
1974 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1975 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1976 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1977 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1978 let was_processed = elem.was_processed;
1979 elem.was_processed = true;
1982 // Entries are added to dist in add_entry!() when there is a channel from a node.
1983 // Because there are no channels from payee, it will not have a dist entry at this point.
1984 // If we're processing any other node, it is always be the result of a channel from it.
1985 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
1990 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1991 for details in first_channels {
1992 let candidate = CandidateRouteHop::FirstHop { details };
1993 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1994 $next_hops_value_contribution,
1995 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1996 $next_hops_cltv_delta, $next_hops_path_length);
2000 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2003 &default_node_features
2006 if !features.requires_unknown_bits() {
2007 for chan_id in $node.channels.iter() {
2008 let chan = network_channels.get(chan_id).unwrap();
2009 if !chan.features.requires_unknown_bits() {
2010 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2011 if first_hops.is_none() || *source != our_node_id {
2012 if directed_channel.direction().enabled {
2013 let candidate = CandidateRouteHop::PublicHop {
2014 info: directed_channel,
2015 short_channel_id: *chan_id,
2017 add_entry!(candidate, *source, $node_id,
2018 $fee_to_target_msat,
2019 $next_hops_value_contribution,
2020 $next_hops_path_htlc_minimum_msat,
2021 $next_hops_path_penalty_msat,
2022 $next_hops_cltv_delta, $next_hops_path_length);
2033 let mut payment_paths = Vec::<PaymentPath>::new();
2035 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2036 'paths_collection: loop {
2037 // For every new path, start from scratch, except for used_liquidities, which
2038 // helps to avoid reusing previously selected paths in future iterations.
2041 hit_minimum_limit = false;
2043 // If first hop is a private channel and the only way to reach the payee, this is the only
2044 // place where it could be added.
2045 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2046 for details in first_channels {
2047 let candidate = CandidateRouteHop::FirstHop { details };
2048 let added = add_entry!(candidate, our_node_id, payee, 0, path_value_msat,
2049 0, 0u64, 0, 0).is_some();
2050 log_trace!(logger, "{} direct route to payee via {}",
2051 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2055 // Add the payee as a target, so that the payee-to-payer
2056 // search algorithm knows what to start with.
2057 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2058 // The payee is not in our network graph, so nothing to add here.
2059 // There is still a chance of reaching them via last_hops though,
2060 // so don't yet fail the payment here.
2061 // If not, targets.pop() will not even let us enter the loop in step 2.
2064 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
2069 // If a caller provided us with last hops, add them to routing targets. Since this happens
2070 // earlier than general path finding, they will be somewhat prioritized, although currently
2071 // it matters only if the fees are exactly the same.
2072 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2073 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2074 let have_intro_node_in_graph =
2075 // Only add the hops in this route to our candidate set if either
2076 // we have a direct channel to the first hop or the first hop is
2077 // in the regular network graph.
2078 first_hop_targets.get(&intro_node_id).is_some() ||
2079 network_nodes.get(&intro_node_id).is_some();
2080 if !have_intro_node_in_graph { continue }
2081 let candidate = if hint.1.blinded_hops.len() == 1 {
2082 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
2083 } else { CandidateRouteHop::Blinded { hint, hint_idx } };
2084 let mut path_contribution_msat = path_value_msat;
2085 if let Some(hop_used_msat) = add_entry!(candidate, intro_node_id, maybe_dummy_payee_node_id,
2086 0, path_contribution_msat, 0, 0_u64, 0, 0)
2088 path_contribution_msat = hop_used_msat;
2090 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2091 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2093 for details in first_channels {
2094 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2095 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2099 add_entry!(first_hop_candidate, our_node_id, intro_node_id, blinded_path_fee,
2100 path_contribution_msat, candidate.htlc_minimum_msat(), 0_u64,
2101 candidate.cltv_expiry_delta(),
2102 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2106 for route in payment_params.payee.unblinded_route_hints().iter()
2107 .filter(|route| !route.0.is_empty())
2109 let first_hop_in_route = &(route.0)[0];
2110 let have_hop_src_in_graph =
2111 // Only add the hops in this route to our candidate set if either
2112 // we have a direct channel to the first hop or the first hop is
2113 // in the regular network graph.
2114 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
2115 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
2116 if have_hop_src_in_graph {
2117 // We start building the path from reverse, i.e., from payee
2118 // to the first RouteHintHop in the path.
2119 let hop_iter = route.0.iter().rev();
2120 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2121 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2122 let mut hop_used = true;
2123 let mut aggregate_next_hops_fee_msat: u64 = 0;
2124 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2125 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2126 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2127 let mut aggregate_next_hops_path_length: u8 = 0;
2128 let mut aggregate_path_contribution_msat = path_value_msat;
2130 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2131 let source = NodeId::from_pubkey(&hop.src_node_id);
2132 let target = NodeId::from_pubkey(&prev_hop_id);
2133 let candidate = network_channels
2134 .get(&hop.short_channel_id)
2135 .and_then(|channel| channel.as_directed_to(&target))
2136 .map(|(info, _)| CandidateRouteHop::PublicHop {
2138 short_channel_id: hop.short_channel_id,
2140 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
2142 if let Some(hop_used_msat) = add_entry!(candidate, source, target,
2143 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2144 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2145 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2147 aggregate_path_contribution_msat = hop_used_msat;
2149 // If this hop was not used then there is no use checking the preceding
2150 // hops in the RouteHint. We can break by just searching for a direct
2151 // channel between last checked hop and first_hop_targets.
2155 let used_liquidity_msat = used_liquidities
2156 .get(&candidate.id(source < target)).copied()
2158 let channel_usage = ChannelUsage {
2159 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2160 inflight_htlc_msat: used_liquidity_msat,
2161 effective_capacity: candidate.effective_capacity(),
2163 let channel_penalty_msat = scorer.channel_penalty_msat(
2164 hop.short_channel_id, &source, &target, channel_usage, score_params
2166 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2167 .saturating_add(channel_penalty_msat);
2169 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2170 .saturating_add(hop.cltv_expiry_delta as u32);
2172 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2175 // Searching for a direct channel between last checked hop and first_hop_targets
2176 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&prev_hop_id)) {
2177 sort_first_hop_channels(first_channels, &used_liquidities,
2178 recommended_value_msat, our_node_pubkey);
2179 for details in first_channels {
2180 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2181 add_entry!(first_hop_candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
2182 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2183 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2184 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2192 // In the next values of the iterator, the aggregate fees already reflects
2193 // the sum of value sent from payer (final_value_msat) and routing fees
2194 // for the last node in the RouteHint. We need to just add the fees to
2195 // route through the current node so that the preceding node (next iteration)
2197 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2198 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2199 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2201 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
2202 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
2203 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
2204 .checked_add(hop_htlc_minimum_msat_inc);
2205 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
2207 if idx == route.0.len() - 1 {
2208 // The last hop in this iterator is the first hop in
2209 // overall RouteHint.
2210 // If this hop connects to a node with which we have a direct channel,
2211 // ignore the network graph and, if the last hop was added, add our
2212 // direct channel to the candidate set.
2214 // Note that we *must* check if the last hop was added as `add_entry`
2215 // always assumes that the third argument is a node to which we have a
2217 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2218 sort_first_hop_channels(first_channels, &used_liquidities,
2219 recommended_value_msat, our_node_pubkey);
2220 for details in first_channels {
2221 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2222 add_entry!(first_hop_candidate, our_node_id,
2223 NodeId::from_pubkey(&hop.src_node_id),
2224 aggregate_next_hops_fee_msat,
2225 aggregate_path_contribution_msat,
2226 aggregate_next_hops_path_htlc_minimum_msat,
2227 aggregate_next_hops_path_penalty_msat,
2228 aggregate_next_hops_cltv_delta,
2229 aggregate_next_hops_path_length);
2237 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2239 // At this point, targets are filled with the data from first and
2240 // last hops communicated by the caller, and the payment receiver.
2241 let mut found_new_path = false;
2244 // If this loop terminates due the exhaustion of targets, two situations are possible:
2245 // - not enough outgoing liquidity:
2246 // 0 < already_collected_value_msat < final_value_msat
2247 // - enough outgoing liquidity:
2248 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2249 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2250 // paths_collection will be stopped because found_new_path==false.
2251 // This is not necessarily a routing failure.
2252 '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() {
2254 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2255 // traversing the graph and arrange the path out of what we found.
2256 if node_id == our_node_id {
2257 let mut new_entry = dist.remove(&our_node_id).unwrap();
2258 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2261 let mut features_set = false;
2262 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
2263 for details in first_channels {
2264 if let Some(scid) = ordered_hops.last().unwrap().0.candidate.short_channel_id() {
2265 if details.get_outbound_payment_scid().unwrap() == scid {
2266 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2267 features_set = true;
2274 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
2275 if let Some(node_info) = node.announcement_info.as_ref() {
2276 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2278 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2281 // We can fill in features for everything except hops which were
2282 // provided via the invoice we're paying. We could guess based on the
2283 // recipient's features but for now we simply avoid guessing at all.
2287 // Means we succesfully traversed from the payer to the payee, now
2288 // save this path for the payment route. Also, update the liquidity
2289 // remaining on the used hops, so that we take them into account
2290 // while looking for more paths.
2291 if ordered_hops.last().unwrap().0.node_id == maybe_dummy_payee_node_id {
2295 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
2296 Some(payment_hop) => payment_hop,
2297 // We can't arrive at None because, if we ever add an entry to targets,
2298 // we also fill in the entry in dist (see add_entry!).
2299 None => unreachable!(),
2301 // We "propagate" the fees one hop backward (topologically) here,
2302 // so that fees paid for a HTLC forwarding on the current channel are
2303 // associated with the previous channel (where they will be subtracted).
2304 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2305 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2307 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2308 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2310 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2311 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2313 let mut payment_path = PaymentPath {hops: ordered_hops};
2315 // We could have possibly constructed a slightly inconsistent path: since we reduce
2316 // value being transferred along the way, we could have violated htlc_minimum_msat
2317 // on some channels we already passed (assuming dest->source direction). Here, we
2318 // recompute the fees again, so that if that's the case, we match the currently
2319 // underpaid htlc_minimum_msat with fees.
2320 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2321 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
2322 payment_path.update_value_and_recompute_fees(value_contribution_msat);
2324 // Since a path allows to transfer as much value as
2325 // the smallest channel it has ("bottleneck"), we should recompute
2326 // the fees so sender HTLC don't overpay fees when traversing
2327 // larger channels than the bottleneck. This may happen because
2328 // when we were selecting those channels we were not aware how much value
2329 // this path will transfer, and the relative fee for them
2330 // might have been computed considering a larger value.
2331 // Remember that we used these channels so that we don't rely
2332 // on the same liquidity in future paths.
2333 let mut prevented_redundant_path_selection = false;
2334 let prev_hop_iter = core::iter::once(&our_node_id)
2335 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
2336 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
2337 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2338 let used_liquidity_msat = used_liquidities
2339 .entry(hop.candidate.id(*prev_hop < hop.node_id))
2340 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2341 .or_insert(spent_on_hop_msat);
2342 let hop_capacity = hop.candidate.effective_capacity();
2343 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2344 if *used_liquidity_msat == hop_max_msat {
2345 // If this path used all of this channel's available liquidity, we know
2346 // this path will not be selected again in the next loop iteration.
2347 prevented_redundant_path_selection = true;
2349 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2351 if !prevented_redundant_path_selection {
2352 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2353 // we'll probably end up picking the same path again on the next iteration.
2354 // Decrease the available liquidity of a hop in the middle of the path.
2355 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2356 let exhausted = u64::max_value();
2358 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2359 LoggedCandidateHop(victim_candidate));
2360 *used_liquidities.entry(victim_candidate.id(false)).or_default() = exhausted;
2361 *used_liquidities.entry(victim_candidate.id(true)).or_default() = exhausted;
2364 // Track the total amount all our collected paths allow to send so that we know
2365 // when to stop looking for more paths
2366 already_collected_value_msat += value_contribution_msat;
2368 payment_paths.push(payment_path);
2369 found_new_path = true;
2370 break 'path_construction;
2373 // If we found a path back to the payee, we shouldn't try to process it again. This is
2374 // the equivalent of the `elem.was_processed` check in
2375 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2376 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2378 // Otherwise, since the current target node is not us,
2379 // keep "unrolling" the payment graph from payee to payer by
2380 // finding a way to reach the current target from the payer side.
2381 match network_nodes.get(&node_id) {
2384 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2385 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2386 total_cltv_delta, path_length_to_node);
2392 if !found_new_path && channel_saturation_pow_half != 0 {
2393 channel_saturation_pow_half = 0;
2394 continue 'paths_collection;
2396 // If we don't support MPP, no use trying to gather more value ever.
2397 break 'paths_collection;
2401 // Stop either when the recommended value is reached or if no new path was found in this
2403 // In the latter case, making another path finding attempt won't help,
2404 // because we deterministically terminated the search due to low liquidity.
2405 if !found_new_path && channel_saturation_pow_half != 0 {
2406 channel_saturation_pow_half = 0;
2407 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2408 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2409 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2410 break 'paths_collection;
2411 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2412 // Further, if this was our first walk of the graph, and we weren't limited by an
2413 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2414 // limited by an htlc_minimum_msat value, find another path with a higher value,
2415 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2416 // still keeping a lower total fee than this path.
2417 if !hit_minimum_limit {
2418 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2419 break 'paths_collection;
2421 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
2422 path_value_msat = recommended_value_msat;
2426 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2427 num_ignored_cltv_delta_limit + num_ignored_previously_failed + num_ignored_total_fee_limit;
2428 if num_ignored_total > 0 {
2429 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, {} due to maximum total fee limit. Total: {} ignored candidates.", num_ignored_value_contribution, num_ignored_path_length_limit, num_ignored_cltv_delta_limit, num_ignored_previously_failed, num_ignored_total_fee_limit, num_ignored_total);
2433 if payment_paths.len() == 0 {
2434 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2437 if already_collected_value_msat < final_value_msat {
2438 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2442 let mut selected_route = payment_paths;
2444 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2445 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2447 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2448 // the value they contribute towards the payment amount.
2449 // We sort in descending order as we will remove from the front in `retain`, next.
2450 selected_route.sort_unstable_by(|a, b|
2451 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2452 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2455 // We should make sure that at least 1 path left.
2456 let mut paths_left = selected_route.len();
2457 selected_route.retain(|path| {
2458 if paths_left == 1 {
2461 let path_value_msat = path.get_value_msat();
2462 if path_value_msat <= overpaid_value_msat {
2463 overpaid_value_msat -= path_value_msat;
2469 debug_assert!(selected_route.len() > 0);
2471 if overpaid_value_msat != 0 {
2473 // Now, subtract the remaining overpaid value from the most-expensive path.
2474 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2475 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2476 selected_route.sort_unstable_by(|a, b| {
2477 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2478 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2479 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2481 let expensive_payment_path = selected_route.first_mut().unwrap();
2483 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2484 // can't go negative.
2485 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2486 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2490 // Sort by the path itself and combine redundant paths.
2491 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2492 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2494 selected_route.sort_unstable_by_key(|path| {
2495 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2496 debug_assert!(path.hops.len() <= key.len());
2497 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id(true)).zip(key.iter_mut()) {
2502 for idx in 0..(selected_route.len() - 1) {
2503 if idx + 1 >= selected_route.len() { break; }
2504 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id)),
2505 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id))) {
2506 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2507 selected_route[idx].update_value_and_recompute_fees(new_value);
2508 selected_route.remove(idx + 1);
2512 let mut paths = Vec::new();
2513 for payment_path in selected_route {
2514 let mut hops = Vec::with_capacity(payment_path.hops.len());
2515 let mut prev_hop_node_id = our_node_id;
2516 for (hop, node_features) in payment_path.hops.iter()
2517 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2519 let maybe_announced_channel = if let CandidateRouteHop::PublicHop { .. } = hop.candidate {
2520 // If we sourced the hop from the graph we're sure the target node is announced.
2522 } else if let CandidateRouteHop::FirstHop { details } = hop.candidate {
2523 // If this is a first hop we also know if it's announced.
2526 // If we sourced it any other way, we double-check the network graph to see if
2527 // there are announced channels between the endpoints. If so, the hop might be
2528 // referring to any of the announced channels, as its `short_channel_id` might be
2529 // an alias, in which case we don't take any chances here.
2530 network_graph.node(&hop.node_id).map_or(false, |hop_node|
2531 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
2532 .map_or(false, |c| c.as_directed_from(&prev_hop_node_id).is_some()))
2536 hops.push(RouteHop {
2537 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)})?,
2538 node_features: node_features.clone(),
2539 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2540 channel_features: hop.candidate.features(),
2541 fee_msat: hop.fee_msat,
2542 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2543 maybe_announced_channel,
2546 prev_hop_node_id = hop.node_id;
2548 let mut final_cltv_delta = final_cltv_expiry_delta;
2549 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2550 if let Some(blinded_path) = h.candidate.blinded_path() {
2551 final_cltv_delta = h.candidate.cltv_expiry_delta();
2553 hops: blinded_path.blinded_hops.clone(),
2554 blinding_point: blinded_path.blinding_point,
2555 excess_final_cltv_expiry_delta: 0,
2556 final_value_msat: h.fee_msat,
2560 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2561 // applicable for the previous hop.
2562 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2563 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2566 paths.push(Path { hops, blinded_tail });
2568 // Make sure we would never create a route with more paths than we allow.
2569 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2571 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
2572 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
2573 if paths.iter().map(|p| p.fee_msat()).sum::<u64>() > max_total_routing_fee_msat {
2574 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
2575 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
2579 if let Some(node_features) = payment_params.payee.node_features() {
2580 for path in paths.iter_mut() {
2581 path.hops.last_mut().unwrap().node_features = node_features.clone();
2585 let route = Route { paths, route_params: Some(route_params.clone()) };
2586 log_info!(logger, "Got route: {}", log_route!(route));
2590 // When an adversarial intermediary node observes a payment, it may be able to infer its
2591 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2592 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2593 // payment path by adding a randomized 'shadow route' offset to the final hop.
2594 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2595 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2597 let network_channels = network_graph.channels();
2598 let network_nodes = network_graph.nodes();
2600 for path in route.paths.iter_mut() {
2601 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2603 // Remember the last three nodes of the random walk and avoid looping back on them.
2604 // Init with the last three nodes from the actual path, if possible.
2605 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2606 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2607 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2609 // Choose the last publicly known node as the starting point for the random walk.
2610 let mut cur_hop: Option<NodeId> = None;
2611 let mut path_nonce = [0u8; 12];
2612 if let Some(starting_hop) = path.hops.iter().rev()
2613 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2614 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2615 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2618 // Init PRNG with the path-dependant nonce, which is static for private paths.
2619 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2620 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2622 // Pick a random path length in [1 .. 3]
2623 prng.process_in_place(&mut random_path_bytes);
2624 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2626 for random_hop in 0..random_walk_length {
2627 // If we don't find a suitable offset in the public network graph, we default to
2628 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2629 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2631 if let Some(cur_node_id) = cur_hop {
2632 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2633 // Randomly choose the next unvisited hop.
2634 prng.process_in_place(&mut random_path_bytes);
2635 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2636 .checked_rem(cur_node.channels.len())
2637 .and_then(|index| cur_node.channels.get(index))
2638 .and_then(|id| network_channels.get(id)) {
2639 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2640 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2641 nodes_to_avoid[random_hop] = *next_id;
2642 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2643 cur_hop = Some(*next_id);
2650 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2651 .checked_add(random_hop_offset)
2652 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2655 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2656 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2657 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2659 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2660 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2661 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2662 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2663 max_path_offset = cmp::max(
2664 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2665 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2666 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2668 // Add 'shadow' CLTV offset to the final hop
2669 if let Some(tail) = path.blinded_tail.as_mut() {
2670 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2671 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2673 if let Some(last_hop) = path.hops.last_mut() {
2674 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2675 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2680 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2681 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2683 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2684 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2685 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2686 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2687 ) -> Result<Route, LightningError>
2688 where L::Target: Logger, GL::Target: Logger {
2689 let graph_lock = network_graph.read_only();
2690 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
2691 &graph_lock, logger, random_seed_bytes)?;
2692 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2696 fn build_route_from_hops_internal<L: Deref>(
2697 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2698 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
2699 ) -> Result<Route, LightningError> where L::Target: Logger {
2702 our_node_id: NodeId,
2703 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2706 impl ScoreLookUp for HopScorer {
2707 type ScoreParams = ();
2708 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2709 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2711 let mut cur_id = self.our_node_id;
2712 for i in 0..self.hop_ids.len() {
2713 if let Some(next_id) = self.hop_ids[i] {
2714 if cur_id == *source && next_id == *target {
2726 impl<'a> Writeable for HopScorer {
2728 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2733 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2734 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2737 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2738 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2739 for i in 0..hops.len() {
2740 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2743 let scorer = HopScorer { our_node_id, hop_ids };
2745 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
2750 use crate::blinded_path::{BlindedHop, BlindedPath};
2751 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2752 use crate::routing::utxo::UtxoResult;
2753 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2754 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2755 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters};
2756 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2757 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2758 use crate::chain::transaction::OutPoint;
2759 use crate::sign::EntropySource;
2760 use crate::ln::ChannelId;
2761 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2762 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2763 use crate::ln::channelmanager;
2764 use crate::offers::invoice::BlindedPayInfo;
2765 use crate::util::config::UserConfig;
2766 use crate::util::test_utils as ln_test_utils;
2767 use crate::util::chacha20::ChaCha20;
2768 use crate::util::ser::{Readable, Writeable};
2770 use crate::util::ser::Writer;
2772 use bitcoin::hashes::Hash;
2773 use bitcoin::network::constants::Network;
2774 use bitcoin::blockdata::constants::genesis_block;
2775 use bitcoin::blockdata::script::Builder;
2776 use bitcoin::blockdata::opcodes;
2777 use bitcoin::blockdata::transaction::TxOut;
2781 use bitcoin::secp256k1::{PublicKey,SecretKey};
2782 use bitcoin::secp256k1::Secp256k1;
2784 use crate::io::Cursor;
2785 use crate::prelude::*;
2786 use crate::sync::Arc;
2788 use core::convert::TryInto;
2790 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2791 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2792 channelmanager::ChannelDetails {
2793 channel_id: ChannelId::new_zero(),
2794 counterparty: channelmanager::ChannelCounterparty {
2797 unspendable_punishment_reserve: 0,
2798 forwarding_info: None,
2799 outbound_htlc_minimum_msat: None,
2800 outbound_htlc_maximum_msat: None,
2802 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2805 outbound_scid_alias: None,
2806 inbound_scid_alias: None,
2807 channel_value_satoshis: 0,
2809 outbound_capacity_msat,
2810 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2811 next_outbound_htlc_minimum_msat: 0,
2812 inbound_capacity_msat: 42,
2813 unspendable_punishment_reserve: None,
2814 confirmations_required: None,
2815 confirmations: None,
2816 force_close_spend_delay: None,
2817 is_outbound: true, is_channel_ready: true,
2818 is_usable: true, is_public: true,
2819 inbound_htlc_minimum_msat: None,
2820 inbound_htlc_maximum_msat: None,
2822 feerate_sat_per_1000_weight: None,
2823 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
2828 fn simple_route_test() {
2829 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2830 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2831 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2832 let scorer = ln_test_utils::TestScorer::new();
2833 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2834 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2836 // Simple route to 2 via 1
2838 let route_params = RouteParameters::from_payment_params_and_value(
2839 payment_params.clone(), 0);
2840 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2841 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
2842 &Default::default(), &random_seed_bytes) {
2843 assert_eq!(err, "Cannot send a payment of 0 msat");
2844 } else { panic!(); }
2846 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
2847 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2848 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
2849 assert_eq!(route.paths[0].hops.len(), 2);
2851 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2852 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2853 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2854 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2855 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2856 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2858 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2859 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2860 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2861 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2862 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2863 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2867 fn invalid_first_hop_test() {
2868 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2869 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2870 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2871 let scorer = ln_test_utils::TestScorer::new();
2872 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2873 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2875 // Simple route to 2 via 1
2877 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2879 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
2880 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2881 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
2882 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
2883 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2884 } else { panic!(); }
2886 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2887 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
2888 assert_eq!(route.paths[0].hops.len(), 2);
2892 fn htlc_minimum_test() {
2893 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2894 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2895 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2896 let scorer = ln_test_utils::TestScorer::new();
2897 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2898 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2900 // Simple route to 2 via 1
2902 // Disable other paths
2903 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2904 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2905 short_channel_id: 12,
2907 flags: 2, // to disable
2908 cltv_expiry_delta: 0,
2909 htlc_minimum_msat: 0,
2910 htlc_maximum_msat: MAX_VALUE_MSAT,
2912 fee_proportional_millionths: 0,
2913 excess_data: Vec::new()
2915 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2916 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2917 short_channel_id: 3,
2919 flags: 2, // to disable
2920 cltv_expiry_delta: 0,
2921 htlc_minimum_msat: 0,
2922 htlc_maximum_msat: MAX_VALUE_MSAT,
2924 fee_proportional_millionths: 0,
2925 excess_data: Vec::new()
2927 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2928 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2929 short_channel_id: 13,
2931 flags: 2, // to disable
2932 cltv_expiry_delta: 0,
2933 htlc_minimum_msat: 0,
2934 htlc_maximum_msat: MAX_VALUE_MSAT,
2936 fee_proportional_millionths: 0,
2937 excess_data: Vec::new()
2939 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2940 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2941 short_channel_id: 6,
2943 flags: 2, // to disable
2944 cltv_expiry_delta: 0,
2945 htlc_minimum_msat: 0,
2946 htlc_maximum_msat: MAX_VALUE_MSAT,
2948 fee_proportional_millionths: 0,
2949 excess_data: Vec::new()
2951 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2952 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2953 short_channel_id: 7,
2955 flags: 2, // to disable
2956 cltv_expiry_delta: 0,
2957 htlc_minimum_msat: 0,
2958 htlc_maximum_msat: MAX_VALUE_MSAT,
2960 fee_proportional_millionths: 0,
2961 excess_data: Vec::new()
2964 // Check against amount_to_transfer_over_msat.
2965 // Set minimal HTLC of 200_000_000 msat.
2966 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2967 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2968 short_channel_id: 2,
2971 cltv_expiry_delta: 0,
2972 htlc_minimum_msat: 200_000_000,
2973 htlc_maximum_msat: MAX_VALUE_MSAT,
2975 fee_proportional_millionths: 0,
2976 excess_data: Vec::new()
2979 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2981 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2982 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2983 short_channel_id: 4,
2986 cltv_expiry_delta: 0,
2987 htlc_minimum_msat: 0,
2988 htlc_maximum_msat: 199_999_999,
2990 fee_proportional_millionths: 0,
2991 excess_data: Vec::new()
2994 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2995 let route_params = RouteParameters::from_payment_params_and_value(
2996 payment_params, 199_999_999);
2997 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2998 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
2999 &Default::default(), &random_seed_bytes) {
3000 assert_eq!(err, "Failed to find a path to the given destination");
3001 } else { panic!(); }
3003 // Lift the restriction on the first hop.
3004 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3005 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3006 short_channel_id: 2,
3009 cltv_expiry_delta: 0,
3010 htlc_minimum_msat: 0,
3011 htlc_maximum_msat: MAX_VALUE_MSAT,
3013 fee_proportional_millionths: 0,
3014 excess_data: Vec::new()
3017 // A payment above the minimum should pass
3018 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3019 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3020 assert_eq!(route.paths[0].hops.len(), 2);
3024 fn htlc_minimum_overpay_test() {
3025 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3026 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3027 let config = UserConfig::default();
3028 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3029 let scorer = ln_test_utils::TestScorer::new();
3030 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3031 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3033 // A route to node#2 via two paths.
3034 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3035 // Thus, they can't send 60 without overpaying.
3036 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3037 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3038 short_channel_id: 2,
3041 cltv_expiry_delta: 0,
3042 htlc_minimum_msat: 35_000,
3043 htlc_maximum_msat: 40_000,
3045 fee_proportional_millionths: 0,
3046 excess_data: Vec::new()
3048 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3049 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3050 short_channel_id: 12,
3053 cltv_expiry_delta: 0,
3054 htlc_minimum_msat: 35_000,
3055 htlc_maximum_msat: 40_000,
3057 fee_proportional_millionths: 0,
3058 excess_data: Vec::new()
3062 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3063 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3064 short_channel_id: 13,
3067 cltv_expiry_delta: 0,
3068 htlc_minimum_msat: 0,
3069 htlc_maximum_msat: MAX_VALUE_MSAT,
3071 fee_proportional_millionths: 0,
3072 excess_data: Vec::new()
3074 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3075 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3076 short_channel_id: 4,
3079 cltv_expiry_delta: 0,
3080 htlc_minimum_msat: 0,
3081 htlc_maximum_msat: MAX_VALUE_MSAT,
3083 fee_proportional_millionths: 0,
3084 excess_data: Vec::new()
3087 // Disable other paths
3088 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3089 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3090 short_channel_id: 1,
3092 flags: 2, // to disable
3093 cltv_expiry_delta: 0,
3094 htlc_minimum_msat: 0,
3095 htlc_maximum_msat: MAX_VALUE_MSAT,
3097 fee_proportional_millionths: 0,
3098 excess_data: Vec::new()
3101 let route_params = RouteParameters::from_payment_params_and_value(
3102 payment_params.clone(), 60_000);
3103 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3104 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3105 // Overpay fees to hit htlc_minimum_msat.
3106 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3107 // TODO: this could be better balanced to overpay 10k and not 15k.
3108 assert_eq!(overpaid_fees, 15_000);
3110 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3111 // while taking even more fee to match htlc_minimum_msat.
3112 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3113 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3114 short_channel_id: 12,
3117 cltv_expiry_delta: 0,
3118 htlc_minimum_msat: 65_000,
3119 htlc_maximum_msat: 80_000,
3121 fee_proportional_millionths: 0,
3122 excess_data: Vec::new()
3124 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3125 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3126 short_channel_id: 2,
3129 cltv_expiry_delta: 0,
3130 htlc_minimum_msat: 0,
3131 htlc_maximum_msat: MAX_VALUE_MSAT,
3133 fee_proportional_millionths: 0,
3134 excess_data: Vec::new()
3136 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3137 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3138 short_channel_id: 4,
3141 cltv_expiry_delta: 0,
3142 htlc_minimum_msat: 0,
3143 htlc_maximum_msat: MAX_VALUE_MSAT,
3145 fee_proportional_millionths: 100_000,
3146 excess_data: Vec::new()
3149 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3150 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3151 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3152 assert_eq!(route.paths.len(), 1);
3153 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3154 let fees = route.paths[0].hops[0].fee_msat;
3155 assert_eq!(fees, 5_000);
3157 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3158 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3159 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3160 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3161 // the other channel.
3162 assert_eq!(route.paths.len(), 1);
3163 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3164 let fees = route.paths[0].hops[0].fee_msat;
3165 assert_eq!(fees, 5_000);
3169 fn disable_channels_test() {
3170 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3171 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3172 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3173 let scorer = ln_test_utils::TestScorer::new();
3174 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3175 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3177 // // Disable channels 4 and 12 by flags=2
3178 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3179 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3180 short_channel_id: 4,
3182 flags: 2, // to disable
3183 cltv_expiry_delta: 0,
3184 htlc_minimum_msat: 0,
3185 htlc_maximum_msat: MAX_VALUE_MSAT,
3187 fee_proportional_millionths: 0,
3188 excess_data: Vec::new()
3190 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3191 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3192 short_channel_id: 12,
3194 flags: 2, // to disable
3195 cltv_expiry_delta: 0,
3196 htlc_minimum_msat: 0,
3197 htlc_maximum_msat: MAX_VALUE_MSAT,
3199 fee_proportional_millionths: 0,
3200 excess_data: Vec::new()
3203 // If all the channels require some features we don't understand, route should fail
3204 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3205 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3206 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3207 &Default::default(), &random_seed_bytes) {
3208 assert_eq!(err, "Failed to find a path to the given destination");
3209 } else { panic!(); }
3211 // If we specify a channel to node7, that overrides our local channel view and that gets used
3212 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3213 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3214 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3215 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3216 &Default::default(), &random_seed_bytes).unwrap();
3217 assert_eq!(route.paths[0].hops.len(), 2);
3219 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3220 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3221 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3222 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3223 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3224 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3226 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3227 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3228 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3229 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3230 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3231 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3235 fn disable_node_test() {
3236 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3237 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3238 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3239 let scorer = ln_test_utils::TestScorer::new();
3240 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3241 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3243 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3244 let mut unknown_features = NodeFeatures::empty();
3245 unknown_features.set_unknown_feature_required();
3246 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3247 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3248 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3250 // If all nodes require some features we don't understand, route should fail
3251 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3252 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3253 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3254 &Default::default(), &random_seed_bytes) {
3255 assert_eq!(err, "Failed to find a path to the given destination");
3256 } else { panic!(); }
3258 // If we specify a channel to node7, that overrides our local channel view and that gets used
3259 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3260 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3261 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3262 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3263 &Default::default(), &random_seed_bytes).unwrap();
3264 assert_eq!(route.paths[0].hops.len(), 2);
3266 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3267 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3268 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3269 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3270 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3271 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3273 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3274 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3275 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3276 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3277 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3278 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3280 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3281 // naively) assume that the user checked the feature bits on the invoice, which override
3282 // the node_announcement.
3286 fn our_chans_test() {
3287 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3288 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3289 let scorer = ln_test_utils::TestScorer::new();
3290 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3291 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3293 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3294 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3295 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3296 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3297 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3298 assert_eq!(route.paths[0].hops.len(), 3);
3300 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3301 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3302 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3303 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3304 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3305 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3307 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3308 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3309 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3310 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3311 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3312 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3314 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3315 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3316 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3317 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3318 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3319 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3321 // If we specify a channel to node7, that overrides our local channel view and that gets used
3322 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3323 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3324 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3325 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3326 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3327 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3328 &Default::default(), &random_seed_bytes).unwrap();
3329 assert_eq!(route.paths[0].hops.len(), 2);
3331 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3332 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3333 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3334 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3335 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3336 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3338 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3339 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3340 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3341 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3342 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3343 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3346 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3347 let zero_fees = RoutingFees {
3349 proportional_millionths: 0,
3351 vec![RouteHint(vec![RouteHintHop {
3352 src_node_id: nodes[3],
3353 short_channel_id: 8,
3355 cltv_expiry_delta: (8 << 4) | 1,
3356 htlc_minimum_msat: None,
3357 htlc_maximum_msat: None,
3359 ]), RouteHint(vec![RouteHintHop {
3360 src_node_id: nodes[4],
3361 short_channel_id: 9,
3364 proportional_millionths: 0,
3366 cltv_expiry_delta: (9 << 4) | 1,
3367 htlc_minimum_msat: None,
3368 htlc_maximum_msat: None,
3369 }]), RouteHint(vec![RouteHintHop {
3370 src_node_id: nodes[5],
3371 short_channel_id: 10,
3373 cltv_expiry_delta: (10 << 4) | 1,
3374 htlc_minimum_msat: None,
3375 htlc_maximum_msat: None,
3379 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3380 let zero_fees = RoutingFees {
3382 proportional_millionths: 0,
3384 vec![RouteHint(vec![RouteHintHop {
3385 src_node_id: nodes[2],
3386 short_channel_id: 5,
3389 proportional_millionths: 0,
3391 cltv_expiry_delta: (5 << 4) | 1,
3392 htlc_minimum_msat: None,
3393 htlc_maximum_msat: None,
3395 src_node_id: nodes[3],
3396 short_channel_id: 8,
3398 cltv_expiry_delta: (8 << 4) | 1,
3399 htlc_minimum_msat: None,
3400 htlc_maximum_msat: None,
3402 ]), RouteHint(vec![RouteHintHop {
3403 src_node_id: nodes[4],
3404 short_channel_id: 9,
3407 proportional_millionths: 0,
3409 cltv_expiry_delta: (9 << 4) | 1,
3410 htlc_minimum_msat: None,
3411 htlc_maximum_msat: None,
3412 }]), RouteHint(vec![RouteHintHop {
3413 src_node_id: nodes[5],
3414 short_channel_id: 10,
3416 cltv_expiry_delta: (10 << 4) | 1,
3417 htlc_minimum_msat: None,
3418 htlc_maximum_msat: None,
3423 fn partial_route_hint_test() {
3424 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3425 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3426 let scorer = ln_test_utils::TestScorer::new();
3427 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3428 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3430 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3431 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3432 // RouteHint may be partially used by the algo to build the best path.
3434 // First check that last hop can't have its source as the payee.
3435 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3436 src_node_id: nodes[6],
3437 short_channel_id: 8,
3440 proportional_millionths: 0,
3442 cltv_expiry_delta: (8 << 4) | 1,
3443 htlc_minimum_msat: None,
3444 htlc_maximum_msat: None,
3447 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3448 invalid_last_hops.push(invalid_last_hop);
3450 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3451 .with_route_hints(invalid_last_hops).unwrap();
3452 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3453 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3454 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3455 &Default::default(), &random_seed_bytes) {
3456 assert_eq!(err, "Route hint cannot have the payee as the source.");
3457 } else { panic!(); }
3460 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3461 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3462 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3463 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3464 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3465 assert_eq!(route.paths[0].hops.len(), 5);
3467 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3468 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3469 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3470 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3471 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3472 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3474 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3475 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3476 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3477 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3478 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3479 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3481 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3482 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3483 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3484 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3485 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3486 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3488 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3489 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3490 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3491 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3492 // If we have a peer in the node map, we'll use their features here since we don't have
3493 // a way of figuring out their features from the invoice:
3494 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3495 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3497 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3498 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3499 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3500 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3501 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3502 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3505 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3506 let zero_fees = RoutingFees {
3508 proportional_millionths: 0,
3510 vec![RouteHint(vec![RouteHintHop {
3511 src_node_id: nodes[3],
3512 short_channel_id: 8,
3514 cltv_expiry_delta: (8 << 4) | 1,
3515 htlc_minimum_msat: None,
3516 htlc_maximum_msat: None,
3517 }]), RouteHint(vec![
3519 ]), RouteHint(vec![RouteHintHop {
3520 src_node_id: nodes[5],
3521 short_channel_id: 10,
3523 cltv_expiry_delta: (10 << 4) | 1,
3524 htlc_minimum_msat: None,
3525 htlc_maximum_msat: None,
3530 fn ignores_empty_last_hops_test() {
3531 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3532 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3533 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3534 let scorer = ln_test_utils::TestScorer::new();
3535 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3536 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3538 // Test handling of an empty RouteHint passed in Invoice.
3539 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3540 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3541 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3542 assert_eq!(route.paths[0].hops.len(), 5);
3544 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3545 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3546 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3547 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3548 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3549 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3551 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3552 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3553 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3554 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3555 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3556 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3558 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3559 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3560 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3561 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3562 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3563 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3565 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3566 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3567 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3568 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3569 // If we have a peer in the node map, we'll use their features here since we don't have
3570 // a way of figuring out their features from the invoice:
3571 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3572 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3574 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3575 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3576 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3577 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3578 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3579 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3582 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3584 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3585 let zero_fees = RoutingFees {
3587 proportional_millionths: 0,
3589 vec![RouteHint(vec![RouteHintHop {
3590 src_node_id: hint_hops[0],
3591 short_channel_id: 0xff00,
3594 proportional_millionths: 0,
3596 cltv_expiry_delta: (5 << 4) | 1,
3597 htlc_minimum_msat: None,
3598 htlc_maximum_msat: None,
3600 src_node_id: hint_hops[1],
3601 short_channel_id: 0xff01,
3603 cltv_expiry_delta: (8 << 4) | 1,
3604 htlc_minimum_msat: None,
3605 htlc_maximum_msat: None,
3610 fn multi_hint_last_hops_test() {
3611 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3612 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3613 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3614 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3615 let scorer = ln_test_utils::TestScorer::new();
3616 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3617 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3618 // Test through channels 2, 3, 0xff00, 0xff01.
3619 // Test shows that multiple hop hints are considered.
3621 // Disabling channels 6 & 7 by flags=2
3622 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3623 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3624 short_channel_id: 6,
3626 flags: 2, // to disable
3627 cltv_expiry_delta: 0,
3628 htlc_minimum_msat: 0,
3629 htlc_maximum_msat: MAX_VALUE_MSAT,
3631 fee_proportional_millionths: 0,
3632 excess_data: Vec::new()
3634 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3635 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3636 short_channel_id: 7,
3638 flags: 2, // to disable
3639 cltv_expiry_delta: 0,
3640 htlc_minimum_msat: 0,
3641 htlc_maximum_msat: MAX_VALUE_MSAT,
3643 fee_proportional_millionths: 0,
3644 excess_data: Vec::new()
3647 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3648 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3649 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3650 assert_eq!(route.paths[0].hops.len(), 4);
3652 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3653 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3654 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3655 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3656 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3657 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3659 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3660 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3661 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3662 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3663 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3664 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3666 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3667 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3668 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3669 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3670 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3671 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3673 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3674 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3675 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3676 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3677 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3678 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3682 fn private_multi_hint_last_hops_test() {
3683 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3684 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3686 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3687 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3689 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3690 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3691 let scorer = ln_test_utils::TestScorer::new();
3692 // Test through channels 2, 3, 0xff00, 0xff01.
3693 // Test shows that multiple hop hints are considered.
3695 // Disabling channels 6 & 7 by flags=2
3696 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3697 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3698 short_channel_id: 6,
3700 flags: 2, // to disable
3701 cltv_expiry_delta: 0,
3702 htlc_minimum_msat: 0,
3703 htlc_maximum_msat: MAX_VALUE_MSAT,
3705 fee_proportional_millionths: 0,
3706 excess_data: Vec::new()
3708 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3709 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3710 short_channel_id: 7,
3712 flags: 2, // to disable
3713 cltv_expiry_delta: 0,
3714 htlc_minimum_msat: 0,
3715 htlc_maximum_msat: MAX_VALUE_MSAT,
3717 fee_proportional_millionths: 0,
3718 excess_data: Vec::new()
3721 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3722 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3723 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
3724 assert_eq!(route.paths[0].hops.len(), 4);
3726 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3727 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3728 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3729 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3730 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3731 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3733 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3734 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3735 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3736 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3737 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3738 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3740 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3741 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3742 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3743 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3744 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3745 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3747 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3748 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3749 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3750 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3751 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3752 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3755 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3756 let zero_fees = RoutingFees {
3758 proportional_millionths: 0,
3760 vec![RouteHint(vec![RouteHintHop {
3761 src_node_id: nodes[4],
3762 short_channel_id: 11,
3764 cltv_expiry_delta: (11 << 4) | 1,
3765 htlc_minimum_msat: None,
3766 htlc_maximum_msat: None,
3768 src_node_id: nodes[3],
3769 short_channel_id: 8,
3771 cltv_expiry_delta: (8 << 4) | 1,
3772 htlc_minimum_msat: None,
3773 htlc_maximum_msat: None,
3774 }]), RouteHint(vec![RouteHintHop {
3775 src_node_id: nodes[4],
3776 short_channel_id: 9,
3779 proportional_millionths: 0,
3781 cltv_expiry_delta: (9 << 4) | 1,
3782 htlc_minimum_msat: None,
3783 htlc_maximum_msat: None,
3784 }]), RouteHint(vec![RouteHintHop {
3785 src_node_id: nodes[5],
3786 short_channel_id: 10,
3788 cltv_expiry_delta: (10 << 4) | 1,
3789 htlc_minimum_msat: None,
3790 htlc_maximum_msat: None,
3795 fn last_hops_with_public_channel_test() {
3796 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3797 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3798 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
3799 let scorer = ln_test_utils::TestScorer::new();
3800 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3801 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3802 // This test shows that public routes can be present in the invoice
3803 // which would be handled in the same manner.
3805 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3806 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3807 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3808 assert_eq!(route.paths[0].hops.len(), 5);
3810 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3811 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3812 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3813 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3814 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3815 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3817 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3818 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3819 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3820 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3821 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3822 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3824 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3825 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3826 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3827 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3828 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3829 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3831 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3832 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3833 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3834 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3835 // If we have a peer in the node map, we'll use their features here since we don't have
3836 // a way of figuring out their features from the invoice:
3837 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3838 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3840 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3841 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3842 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3843 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3844 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3845 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3849 fn our_chans_last_hop_connect_test() {
3850 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3851 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3852 let scorer = ln_test_utils::TestScorer::new();
3853 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3854 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3856 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3857 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3858 let mut last_hops = last_hops(&nodes);
3859 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3860 .with_route_hints(last_hops.clone()).unwrap();
3861 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3862 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3863 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3864 &Default::default(), &random_seed_bytes).unwrap();
3865 assert_eq!(route.paths[0].hops.len(), 2);
3867 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3868 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3869 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3870 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3871 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3872 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3874 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3875 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3876 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3877 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3878 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3879 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3881 last_hops[0].0[0].fees.base_msat = 1000;
3883 // Revert to via 6 as the fee on 8 goes up
3884 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3885 .with_route_hints(last_hops).unwrap();
3886 let route_params = RouteParameters::from_payment_params_and_value(
3887 payment_params.clone(), 100);
3888 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3889 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3890 assert_eq!(route.paths[0].hops.len(), 4);
3892 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3893 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3894 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
3895 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3896 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3897 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3899 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3900 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3901 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3902 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
3903 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3904 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3906 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
3907 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3908 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3909 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3910 // If we have a peer in the node map, we'll use their features here since we don't have
3911 // a way of figuring out their features from the invoice:
3912 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3913 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3915 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3916 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3917 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3918 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3919 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3920 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3922 // ...but still use 8 for larger payments as 6 has a variable feerate
3923 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
3924 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3925 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3926 assert_eq!(route.paths[0].hops.len(), 5);
3928 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3929 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3930 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3931 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3932 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3933 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3935 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3936 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3937 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3938 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3939 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3940 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3942 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3943 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3944 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3945 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3946 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3947 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3949 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3950 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3951 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
3952 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3953 // If we have a peer in the node map, we'll use their features here since we don't have
3954 // a way of figuring out their features from the invoice:
3955 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3956 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3958 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3959 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3960 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
3961 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3962 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3963 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3966 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> {
3967 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3968 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3969 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3971 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3972 let last_hops = RouteHint(vec![RouteHintHop {
3973 src_node_id: middle_node_id,
3974 short_channel_id: 8,
3977 proportional_millionths: last_hop_fee_prop,
3979 cltv_expiry_delta: (8 << 4) | 1,
3980 htlc_minimum_msat: None,
3981 htlc_maximum_msat: last_hop_htlc_max,
3983 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
3984 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3985 let scorer = ln_test_utils::TestScorer::new();
3986 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3987 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3988 let logger = ln_test_utils::TestLogger::new();
3989 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3990 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
3991 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
3992 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
3993 &random_seed_bytes);
3998 fn unannounced_path_test() {
3999 // We should be able to send a payment to a destination without any help of a routing graph
4000 // if we have a channel with a common counterparty that appears in the first and last hop
4002 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4004 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4005 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4006 assert_eq!(route.paths[0].hops.len(), 2);
4008 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4009 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4010 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4011 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4012 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4013 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4015 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4016 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4017 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4018 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4019 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4020 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4024 fn overflow_unannounced_path_test_liquidity_underflow() {
4025 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4026 // the last-hop had a fee which overflowed a u64, we'd panic.
4027 // This was due to us adding the first-hop from us unconditionally, causing us to think
4028 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4029 // In this test, we previously hit a subtraction underflow due to having less available
4030 // liquidity at the last hop than 0.
4031 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());
4035 fn overflow_unannounced_path_test_feerate_overflow() {
4036 // This tests for the same case as above, except instead of hitting a subtraction
4037 // underflow, we hit a case where the fee charged at a hop overflowed.
4038 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());
4042 fn available_amount_while_routing_test() {
4043 // Tests whether we choose the correct available channel amount while routing.
4045 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4046 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4047 let scorer = ln_test_utils::TestScorer::new();
4048 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4049 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4050 let config = UserConfig::default();
4051 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4053 // We will use a simple single-path route from
4054 // our node to node2 via node0: channels {1, 3}.
4056 // First disable all other paths.
4057 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4058 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4059 short_channel_id: 2,
4062 cltv_expiry_delta: 0,
4063 htlc_minimum_msat: 0,
4064 htlc_maximum_msat: 100_000,
4066 fee_proportional_millionths: 0,
4067 excess_data: Vec::new()
4069 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4070 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4071 short_channel_id: 12,
4074 cltv_expiry_delta: 0,
4075 htlc_minimum_msat: 0,
4076 htlc_maximum_msat: 100_000,
4078 fee_proportional_millionths: 0,
4079 excess_data: Vec::new()
4082 // Make the first channel (#1) very permissive,
4083 // and we will be testing all limits on the second channel.
4084 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4085 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4086 short_channel_id: 1,
4089 cltv_expiry_delta: 0,
4090 htlc_minimum_msat: 0,
4091 htlc_maximum_msat: 1_000_000_000,
4093 fee_proportional_millionths: 0,
4094 excess_data: Vec::new()
4097 // First, let's see if routing works if we have absolutely no idea about the available amount.
4098 // In this case, it should be set to 250_000 sats.
4099 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4100 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4101 short_channel_id: 3,
4104 cltv_expiry_delta: 0,
4105 htlc_minimum_msat: 0,
4106 htlc_maximum_msat: 250_000_000,
4108 fee_proportional_millionths: 0,
4109 excess_data: Vec::new()
4113 // Attempt to route more than available results in a failure.
4114 let route_params = RouteParameters::from_payment_params_and_value(
4115 payment_params.clone(), 250_000_001);
4116 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4117 &our_id, &route_params, &network_graph.read_only(), None,
4118 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4119 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4120 } else { panic!(); }
4124 // Now, attempt to route an exact amount we have should be fine.
4125 let route_params = RouteParameters::from_payment_params_and_value(
4126 payment_params.clone(), 250_000_000);
4127 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4128 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4129 assert_eq!(route.paths.len(), 1);
4130 let path = route.paths.last().unwrap();
4131 assert_eq!(path.hops.len(), 2);
4132 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4133 assert_eq!(path.final_value_msat(), 250_000_000);
4136 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4137 // Disable channel #1 and use another first hop.
4138 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4139 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4140 short_channel_id: 1,
4143 cltv_expiry_delta: 0,
4144 htlc_minimum_msat: 0,
4145 htlc_maximum_msat: 1_000_000_000,
4147 fee_proportional_millionths: 0,
4148 excess_data: Vec::new()
4151 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4152 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4155 // Attempt to route more than available results in a failure.
4156 let route_params = RouteParameters::from_payment_params_and_value(
4157 payment_params.clone(), 200_000_001);
4158 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4159 &our_id, &route_params, &network_graph.read_only(),
4160 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4161 &Default::default(), &random_seed_bytes) {
4162 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4163 } else { panic!(); }
4167 // Now, attempt to route an exact amount we have should be fine.
4168 let route_params = RouteParameters::from_payment_params_and_value(
4169 payment_params.clone(), 200_000_000);
4170 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4171 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4172 &Default::default(), &random_seed_bytes).unwrap();
4173 assert_eq!(route.paths.len(), 1);
4174 let path = route.paths.last().unwrap();
4175 assert_eq!(path.hops.len(), 2);
4176 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4177 assert_eq!(path.final_value_msat(), 200_000_000);
4180 // Enable channel #1 back.
4181 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4182 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4183 short_channel_id: 1,
4186 cltv_expiry_delta: 0,
4187 htlc_minimum_msat: 0,
4188 htlc_maximum_msat: 1_000_000_000,
4190 fee_proportional_millionths: 0,
4191 excess_data: Vec::new()
4195 // Now let's see if routing works if we know only htlc_maximum_msat.
4196 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4197 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4198 short_channel_id: 3,
4201 cltv_expiry_delta: 0,
4202 htlc_minimum_msat: 0,
4203 htlc_maximum_msat: 15_000,
4205 fee_proportional_millionths: 0,
4206 excess_data: Vec::new()
4210 // Attempt to route more than available results in a failure.
4211 let route_params = RouteParameters::from_payment_params_and_value(
4212 payment_params.clone(), 15_001);
4213 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4214 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4215 &scorer, &Default::default(), &random_seed_bytes) {
4216 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4217 } else { panic!(); }
4221 // Now, attempt to route an exact amount we have should be fine.
4222 let route_params = RouteParameters::from_payment_params_and_value(
4223 payment_params.clone(), 15_000);
4224 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4225 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4226 assert_eq!(route.paths.len(), 1);
4227 let path = route.paths.last().unwrap();
4228 assert_eq!(path.hops.len(), 2);
4229 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4230 assert_eq!(path.final_value_msat(), 15_000);
4233 // Now let's see if routing works if we know only capacity from the UTXO.
4235 // We can't change UTXO capacity on the fly, so we'll disable
4236 // the existing channel and add another one with the capacity we need.
4237 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4238 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4239 short_channel_id: 3,
4242 cltv_expiry_delta: 0,
4243 htlc_minimum_msat: 0,
4244 htlc_maximum_msat: MAX_VALUE_MSAT,
4246 fee_proportional_millionths: 0,
4247 excess_data: Vec::new()
4250 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4251 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4252 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4253 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4254 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4256 *chain_monitor.utxo_ret.lock().unwrap() =
4257 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4258 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4260 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4261 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4262 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4263 short_channel_id: 333,
4266 cltv_expiry_delta: (3 << 4) | 1,
4267 htlc_minimum_msat: 0,
4268 htlc_maximum_msat: 15_000,
4270 fee_proportional_millionths: 0,
4271 excess_data: Vec::new()
4273 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4274 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4275 short_channel_id: 333,
4278 cltv_expiry_delta: (3 << 4) | 2,
4279 htlc_minimum_msat: 0,
4280 htlc_maximum_msat: 15_000,
4282 fee_proportional_millionths: 0,
4283 excess_data: Vec::new()
4287 // Attempt to route more than available results in a failure.
4288 let route_params = RouteParameters::from_payment_params_and_value(
4289 payment_params.clone(), 15_001);
4290 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4291 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4292 &scorer, &Default::default(), &random_seed_bytes) {
4293 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4294 } else { panic!(); }
4298 // Now, attempt to route an exact amount we have should be fine.
4299 let route_params = RouteParameters::from_payment_params_and_value(
4300 payment_params.clone(), 15_000);
4301 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4302 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4303 assert_eq!(route.paths.len(), 1);
4304 let path = route.paths.last().unwrap();
4305 assert_eq!(path.hops.len(), 2);
4306 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4307 assert_eq!(path.final_value_msat(), 15_000);
4310 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4311 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4312 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4313 short_channel_id: 333,
4316 cltv_expiry_delta: 0,
4317 htlc_minimum_msat: 0,
4318 htlc_maximum_msat: 10_000,
4320 fee_proportional_millionths: 0,
4321 excess_data: Vec::new()
4325 // Attempt to route more than available results in a failure.
4326 let route_params = RouteParameters::from_payment_params_and_value(
4327 payment_params.clone(), 10_001);
4328 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4329 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4330 &scorer, &Default::default(), &random_seed_bytes) {
4331 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4332 } else { panic!(); }
4336 // Now, attempt to route an exact amount we have should be fine.
4337 let route_params = RouteParameters::from_payment_params_and_value(
4338 payment_params.clone(), 10_000);
4339 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4340 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4341 assert_eq!(route.paths.len(), 1);
4342 let path = route.paths.last().unwrap();
4343 assert_eq!(path.hops.len(), 2);
4344 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4345 assert_eq!(path.final_value_msat(), 10_000);
4350 fn available_liquidity_last_hop_test() {
4351 // Check that available liquidity properly limits the path even when only
4352 // one of the latter hops is limited.
4353 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4354 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4355 let scorer = ln_test_utils::TestScorer::new();
4356 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4357 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4358 let config = UserConfig::default();
4359 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4361 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4362 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4363 // Total capacity: 50 sats.
4365 // Disable other potential paths.
4366 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4367 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4368 short_channel_id: 2,
4371 cltv_expiry_delta: 0,
4372 htlc_minimum_msat: 0,
4373 htlc_maximum_msat: 100_000,
4375 fee_proportional_millionths: 0,
4376 excess_data: Vec::new()
4378 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4379 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4380 short_channel_id: 7,
4383 cltv_expiry_delta: 0,
4384 htlc_minimum_msat: 0,
4385 htlc_maximum_msat: 100_000,
4387 fee_proportional_millionths: 0,
4388 excess_data: Vec::new()
4393 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4394 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4395 short_channel_id: 12,
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()
4405 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4406 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4407 short_channel_id: 13,
4410 cltv_expiry_delta: 0,
4411 htlc_minimum_msat: 0,
4412 htlc_maximum_msat: 100_000,
4414 fee_proportional_millionths: 0,
4415 excess_data: Vec::new()
4418 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4419 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4420 short_channel_id: 6,
4423 cltv_expiry_delta: 0,
4424 htlc_minimum_msat: 0,
4425 htlc_maximum_msat: 50_000,
4427 fee_proportional_millionths: 0,
4428 excess_data: Vec::new()
4430 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4431 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4432 short_channel_id: 11,
4435 cltv_expiry_delta: 0,
4436 htlc_minimum_msat: 0,
4437 htlc_maximum_msat: 100_000,
4439 fee_proportional_millionths: 0,
4440 excess_data: Vec::new()
4443 // Attempt to route more than available results in a failure.
4444 let route_params = RouteParameters::from_payment_params_and_value(
4445 payment_params.clone(), 60_000);
4446 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4447 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4448 &scorer, &Default::default(), &random_seed_bytes) {
4449 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4450 } else { panic!(); }
4454 // Now, attempt to route 49 sats (just a bit below the capacity).
4455 let route_params = RouteParameters::from_payment_params_and_value(
4456 payment_params.clone(), 49_000);
4457 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4458 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4459 assert_eq!(route.paths.len(), 1);
4460 let mut total_amount_paid_msat = 0;
4461 for path in &route.paths {
4462 assert_eq!(path.hops.len(), 4);
4463 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4464 total_amount_paid_msat += path.final_value_msat();
4466 assert_eq!(total_amount_paid_msat, 49_000);
4470 // Attempt to route an exact amount is also fine
4471 let route_params = RouteParameters::from_payment_params_and_value(
4472 payment_params, 50_000);
4473 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4474 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4475 assert_eq!(route.paths.len(), 1);
4476 let mut total_amount_paid_msat = 0;
4477 for path in &route.paths {
4478 assert_eq!(path.hops.len(), 4);
4479 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4480 total_amount_paid_msat += path.final_value_msat();
4482 assert_eq!(total_amount_paid_msat, 50_000);
4487 fn ignore_fee_first_hop_test() {
4488 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4489 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4490 let scorer = ln_test_utils::TestScorer::new();
4491 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4492 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4493 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4495 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4496 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4497 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4498 short_channel_id: 1,
4501 cltv_expiry_delta: 0,
4502 htlc_minimum_msat: 0,
4503 htlc_maximum_msat: 100_000,
4504 fee_base_msat: 1_000_000,
4505 fee_proportional_millionths: 0,
4506 excess_data: Vec::new()
4508 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4509 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4510 short_channel_id: 3,
4513 cltv_expiry_delta: 0,
4514 htlc_minimum_msat: 0,
4515 htlc_maximum_msat: 50_000,
4517 fee_proportional_millionths: 0,
4518 excess_data: Vec::new()
4522 let route_params = RouteParameters::from_payment_params_and_value(
4523 payment_params, 50_000);
4524 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4525 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4526 assert_eq!(route.paths.len(), 1);
4527 let mut total_amount_paid_msat = 0;
4528 for path in &route.paths {
4529 assert_eq!(path.hops.len(), 2);
4530 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4531 total_amount_paid_msat += path.final_value_msat();
4533 assert_eq!(total_amount_paid_msat, 50_000);
4538 fn simple_mpp_route_test() {
4539 let (secp_ctx, _, _, _, _) = build_graph();
4540 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4541 let config = UserConfig::default();
4542 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4543 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4544 do_simple_mpp_route_test(clear_payment_params);
4546 // MPP to a 1-hop blinded path for nodes[2]
4547 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
4548 let blinded_path = BlindedPath {
4549 introduction_node_id: nodes[2],
4550 blinding_point: ln_test_utils::pubkey(42),
4551 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4553 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4555 fee_proportional_millionths: 0,
4556 htlc_minimum_msat: 0,
4557 htlc_maximum_msat: 0,
4558 cltv_expiry_delta: 0,
4559 features: BlindedHopFeatures::empty(),
4561 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4562 .with_bolt12_features(bolt12_features.clone()).unwrap();
4563 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4565 // MPP to 3 2-hop blinded paths
4566 let mut blinded_path_node_0 = blinded_path.clone();
4567 blinded_path_node_0.introduction_node_id = nodes[0];
4568 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4569 let mut node_0_payinfo = blinded_payinfo.clone();
4570 node_0_payinfo.htlc_maximum_msat = 50_000;
4572 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4573 blinded_path_node_7.introduction_node_id = nodes[7];
4574 let mut node_7_payinfo = blinded_payinfo.clone();
4575 node_7_payinfo.htlc_maximum_msat = 60_000;
4577 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4578 blinded_path_node_1.introduction_node_id = nodes[1];
4579 let mut node_1_payinfo = blinded_payinfo.clone();
4580 node_1_payinfo.htlc_maximum_msat = 180_000;
4582 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4584 (node_0_payinfo, blinded_path_node_0),
4585 (node_7_payinfo, blinded_path_node_7),
4586 (node_1_payinfo, blinded_path_node_1)
4588 .with_bolt12_features(bolt12_features).unwrap();
4589 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4593 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4594 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4595 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4596 let scorer = ln_test_utils::TestScorer::new();
4597 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4598 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4600 // We need a route consisting of 3 paths:
4601 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4602 // To achieve this, the amount being transferred should be around
4603 // the total capacity of these 3 paths.
4605 // First, we set limits on these (previously unlimited) channels.
4606 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4608 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4609 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4610 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4611 short_channel_id: 1,
4614 cltv_expiry_delta: 0,
4615 htlc_minimum_msat: 0,
4616 htlc_maximum_msat: 100_000,
4618 fee_proportional_millionths: 0,
4619 excess_data: Vec::new()
4621 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4622 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4623 short_channel_id: 3,
4626 cltv_expiry_delta: 0,
4627 htlc_minimum_msat: 0,
4628 htlc_maximum_msat: 50_000,
4630 fee_proportional_millionths: 0,
4631 excess_data: Vec::new()
4634 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4635 // (total limit 60).
4636 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4637 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4638 short_channel_id: 12,
4641 cltv_expiry_delta: 0,
4642 htlc_minimum_msat: 0,
4643 htlc_maximum_msat: 60_000,
4645 fee_proportional_millionths: 0,
4646 excess_data: Vec::new()
4648 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4649 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4650 short_channel_id: 13,
4653 cltv_expiry_delta: 0,
4654 htlc_minimum_msat: 0,
4655 htlc_maximum_msat: 60_000,
4657 fee_proportional_millionths: 0,
4658 excess_data: Vec::new()
4661 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4662 // (total capacity 180 sats).
4663 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4664 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4665 short_channel_id: 2,
4668 cltv_expiry_delta: 0,
4669 htlc_minimum_msat: 0,
4670 htlc_maximum_msat: 200_000,
4672 fee_proportional_millionths: 0,
4673 excess_data: Vec::new()
4675 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4676 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4677 short_channel_id: 4,
4680 cltv_expiry_delta: 0,
4681 htlc_minimum_msat: 0,
4682 htlc_maximum_msat: 180_000,
4684 fee_proportional_millionths: 0,
4685 excess_data: Vec::new()
4689 // Attempt to route more than available results in a failure.
4690 let route_params = RouteParameters::from_payment_params_and_value(
4691 payment_params.clone(), 300_000);
4692 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4693 &our_id, &route_params, &network_graph.read_only(), None,
4694 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4695 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4696 } else { panic!(); }
4700 // Attempt to route while setting max_path_count to 0 results in a failure.
4701 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4702 let route_params = RouteParameters::from_payment_params_and_value(
4703 zero_payment_params, 100);
4704 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4705 &our_id, &route_params, &network_graph.read_only(), None,
4706 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4707 assert_eq!(err, "Can't find a route with no paths allowed.");
4708 } else { panic!(); }
4712 // Attempt to route while setting max_path_count to 3 results in a failure.
4713 // This is the case because the minimal_value_contribution_msat would require each path
4714 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4715 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4716 let route_params = RouteParameters::from_payment_params_and_value(
4717 fail_payment_params, 250_000);
4718 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4719 &our_id, &route_params, &network_graph.read_only(), None,
4720 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4721 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4722 } else { panic!(); }
4726 // Now, attempt to route 250 sats (just a bit below the capacity).
4727 // Our algorithm should provide us with these 3 paths.
4728 let route_params = RouteParameters::from_payment_params_and_value(
4729 payment_params.clone(), 250_000);
4730 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4731 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4732 assert_eq!(route.paths.len(), 3);
4733 let mut total_amount_paid_msat = 0;
4734 for path in &route.paths {
4735 if let Some(bt) = &path.blinded_tail {
4736 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4738 assert_eq!(path.hops.len(), 2);
4739 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4741 total_amount_paid_msat += path.final_value_msat();
4743 assert_eq!(total_amount_paid_msat, 250_000);
4747 // Attempt to route an exact amount is also fine
4748 let route_params = RouteParameters::from_payment_params_and_value(
4749 payment_params.clone(), 290_000);
4750 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4751 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4752 assert_eq!(route.paths.len(), 3);
4753 let mut total_amount_paid_msat = 0;
4754 for path in &route.paths {
4755 if payment_params.payee.blinded_route_hints().len() != 0 {
4756 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
4757 if let Some(bt) = &path.blinded_tail {
4758 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4759 if bt.hops.len() > 1 {
4760 assert_eq!(path.hops.last().unwrap().pubkey,
4761 payment_params.payee.blinded_route_hints().iter()
4762 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
4763 .map(|(_, p)| p.introduction_node_id).unwrap());
4765 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4768 assert_eq!(path.hops.len(), 2);
4769 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4771 total_amount_paid_msat += path.final_value_msat();
4773 assert_eq!(total_amount_paid_msat, 290_000);
4778 fn long_mpp_route_test() {
4779 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4780 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4781 let scorer = ln_test_utils::TestScorer::new();
4782 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4783 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4784 let config = UserConfig::default();
4785 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4786 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4788 // We need a route consisting of 3 paths:
4789 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4790 // Note that these paths overlap (channels 5, 12, 13).
4791 // We will route 300 sats.
4792 // Each path will have 100 sats capacity, those channels which
4793 // are used twice will have 200 sats capacity.
4795 // Disable other potential paths.
4796 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4797 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4798 short_channel_id: 2,
4801 cltv_expiry_delta: 0,
4802 htlc_minimum_msat: 0,
4803 htlc_maximum_msat: 100_000,
4805 fee_proportional_millionths: 0,
4806 excess_data: Vec::new()
4808 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4809 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4810 short_channel_id: 7,
4813 cltv_expiry_delta: 0,
4814 htlc_minimum_msat: 0,
4815 htlc_maximum_msat: 100_000,
4817 fee_proportional_millionths: 0,
4818 excess_data: Vec::new()
4821 // Path via {node0, node2} is channels {1, 3, 5}.
4822 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4823 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4824 short_channel_id: 1,
4827 cltv_expiry_delta: 0,
4828 htlc_minimum_msat: 0,
4829 htlc_maximum_msat: 100_000,
4831 fee_proportional_millionths: 0,
4832 excess_data: Vec::new()
4834 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4835 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4836 short_channel_id: 3,
4839 cltv_expiry_delta: 0,
4840 htlc_minimum_msat: 0,
4841 htlc_maximum_msat: 100_000,
4843 fee_proportional_millionths: 0,
4844 excess_data: Vec::new()
4847 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4848 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4849 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4850 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4851 short_channel_id: 5,
4854 cltv_expiry_delta: 0,
4855 htlc_minimum_msat: 0,
4856 htlc_maximum_msat: 200_000,
4858 fee_proportional_millionths: 0,
4859 excess_data: Vec::new()
4862 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4863 // Add 100 sats to the capacities of {12, 13}, because these channels
4864 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4865 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4866 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4867 short_channel_id: 12,
4870 cltv_expiry_delta: 0,
4871 htlc_minimum_msat: 0,
4872 htlc_maximum_msat: 200_000,
4874 fee_proportional_millionths: 0,
4875 excess_data: Vec::new()
4877 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4878 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4879 short_channel_id: 13,
4882 cltv_expiry_delta: 0,
4883 htlc_minimum_msat: 0,
4884 htlc_maximum_msat: 200_000,
4886 fee_proportional_millionths: 0,
4887 excess_data: Vec::new()
4890 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4891 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4892 short_channel_id: 6,
4895 cltv_expiry_delta: 0,
4896 htlc_minimum_msat: 0,
4897 htlc_maximum_msat: 100_000,
4899 fee_proportional_millionths: 0,
4900 excess_data: Vec::new()
4902 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4903 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4904 short_channel_id: 11,
4907 cltv_expiry_delta: 0,
4908 htlc_minimum_msat: 0,
4909 htlc_maximum_msat: 100_000,
4911 fee_proportional_millionths: 0,
4912 excess_data: Vec::new()
4915 // Path via {node7, node2} is channels {12, 13, 5}.
4916 // We already limited them to 200 sats (they are used twice for 100 sats).
4917 // Nothing to do here.
4920 // Attempt to route more than available results in a failure.
4921 let route_params = RouteParameters::from_payment_params_and_value(
4922 payment_params.clone(), 350_000);
4923 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4924 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4925 &scorer, &Default::default(), &random_seed_bytes) {
4926 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4927 } else { panic!(); }
4931 // Now, attempt to route 300 sats (exact amount we can route).
4932 // Our algorithm should provide us with these 3 paths, 100 sats each.
4933 let route_params = RouteParameters::from_payment_params_and_value(
4934 payment_params, 300_000);
4935 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4936 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4937 assert_eq!(route.paths.len(), 3);
4939 let mut total_amount_paid_msat = 0;
4940 for path in &route.paths {
4941 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4942 total_amount_paid_msat += path.final_value_msat();
4944 assert_eq!(total_amount_paid_msat, 300_000);
4950 fn mpp_cheaper_route_test() {
4951 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4952 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4953 let scorer = ln_test_utils::TestScorer::new();
4954 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4955 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4956 let config = UserConfig::default();
4957 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4959 // This test checks that if we have two cheaper paths and one more expensive path,
4960 // so that liquidity-wise any 2 of 3 combination is sufficient,
4961 // two cheaper paths will be taken.
4962 // These paths have equal available liquidity.
4964 // We need a combination of 3 paths:
4965 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4966 // Note that these paths overlap (channels 5, 12, 13).
4967 // Each path will have 100 sats capacity, those channels which
4968 // are used twice will have 200 sats capacity.
4970 // Disable other potential paths.
4971 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4972 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4973 short_channel_id: 2,
4976 cltv_expiry_delta: 0,
4977 htlc_minimum_msat: 0,
4978 htlc_maximum_msat: 100_000,
4980 fee_proportional_millionths: 0,
4981 excess_data: Vec::new()
4983 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4984 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4985 short_channel_id: 7,
4988 cltv_expiry_delta: 0,
4989 htlc_minimum_msat: 0,
4990 htlc_maximum_msat: 100_000,
4992 fee_proportional_millionths: 0,
4993 excess_data: Vec::new()
4996 // Path via {node0, node2} is channels {1, 3, 5}.
4997 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4998 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4999 short_channel_id: 1,
5002 cltv_expiry_delta: 0,
5003 htlc_minimum_msat: 0,
5004 htlc_maximum_msat: 100_000,
5006 fee_proportional_millionths: 0,
5007 excess_data: Vec::new()
5009 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5010 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5011 short_channel_id: 3,
5014 cltv_expiry_delta: 0,
5015 htlc_minimum_msat: 0,
5016 htlc_maximum_msat: 100_000,
5018 fee_proportional_millionths: 0,
5019 excess_data: Vec::new()
5022 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5023 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5024 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5025 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5026 short_channel_id: 5,
5029 cltv_expiry_delta: 0,
5030 htlc_minimum_msat: 0,
5031 htlc_maximum_msat: 200_000,
5033 fee_proportional_millionths: 0,
5034 excess_data: Vec::new()
5037 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5038 // Add 100 sats to the capacities of {12, 13}, because these channels
5039 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5040 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5041 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5042 short_channel_id: 12,
5045 cltv_expiry_delta: 0,
5046 htlc_minimum_msat: 0,
5047 htlc_maximum_msat: 200_000,
5049 fee_proportional_millionths: 0,
5050 excess_data: Vec::new()
5052 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5053 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5054 short_channel_id: 13,
5057 cltv_expiry_delta: 0,
5058 htlc_minimum_msat: 0,
5059 htlc_maximum_msat: 200_000,
5061 fee_proportional_millionths: 0,
5062 excess_data: Vec::new()
5065 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5066 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5067 short_channel_id: 6,
5070 cltv_expiry_delta: 0,
5071 htlc_minimum_msat: 0,
5072 htlc_maximum_msat: 100_000,
5073 fee_base_msat: 1_000,
5074 fee_proportional_millionths: 0,
5075 excess_data: Vec::new()
5077 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5078 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5079 short_channel_id: 11,
5082 cltv_expiry_delta: 0,
5083 htlc_minimum_msat: 0,
5084 htlc_maximum_msat: 100_000,
5086 fee_proportional_millionths: 0,
5087 excess_data: Vec::new()
5090 // Path via {node7, node2} is channels {12, 13, 5}.
5091 // We already limited them to 200 sats (they are used twice for 100 sats).
5092 // Nothing to do here.
5095 // Now, attempt to route 180 sats.
5096 // Our algorithm should provide us with these 2 paths.
5097 let route_params = RouteParameters::from_payment_params_and_value(
5098 payment_params, 180_000);
5099 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5100 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5101 assert_eq!(route.paths.len(), 2);
5103 let mut total_value_transferred_msat = 0;
5104 let mut total_paid_msat = 0;
5105 for path in &route.paths {
5106 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5107 total_value_transferred_msat += path.final_value_msat();
5108 for hop in &path.hops {
5109 total_paid_msat += hop.fee_msat;
5112 // If we paid fee, this would be higher.
5113 assert_eq!(total_value_transferred_msat, 180_000);
5114 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5115 assert_eq!(total_fees_paid, 0);
5120 fn fees_on_mpp_route_test() {
5121 // This test makes sure that MPP algorithm properly takes into account
5122 // fees charged on the channels, by making the fees impactful:
5123 // if the fee is not properly accounted for, the behavior is different.
5124 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5125 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5126 let scorer = ln_test_utils::TestScorer::new();
5127 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5128 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5129 let config = UserConfig::default();
5130 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5132 // We need a route consisting of 2 paths:
5133 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5134 // We will route 200 sats, Each path will have 100 sats capacity.
5136 // This test is not particularly stable: e.g.,
5137 // there's a way to route via {node0, node2, node4}.
5138 // It works while pathfinding is deterministic, but can be broken otherwise.
5139 // It's fine to ignore this concern for now.
5141 // Disable other potential paths.
5142 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5143 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5144 short_channel_id: 2,
5147 cltv_expiry_delta: 0,
5148 htlc_minimum_msat: 0,
5149 htlc_maximum_msat: 100_000,
5151 fee_proportional_millionths: 0,
5152 excess_data: Vec::new()
5155 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5156 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5157 short_channel_id: 7,
5160 cltv_expiry_delta: 0,
5161 htlc_minimum_msat: 0,
5162 htlc_maximum_msat: 100_000,
5164 fee_proportional_millionths: 0,
5165 excess_data: Vec::new()
5168 // Path via {node0, node2} is channels {1, 3, 5}.
5169 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5170 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5171 short_channel_id: 1,
5174 cltv_expiry_delta: 0,
5175 htlc_minimum_msat: 0,
5176 htlc_maximum_msat: 100_000,
5178 fee_proportional_millionths: 0,
5179 excess_data: Vec::new()
5181 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5182 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5183 short_channel_id: 3,
5186 cltv_expiry_delta: 0,
5187 htlc_minimum_msat: 0,
5188 htlc_maximum_msat: 100_000,
5190 fee_proportional_millionths: 0,
5191 excess_data: Vec::new()
5194 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5195 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5196 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5197 short_channel_id: 5,
5200 cltv_expiry_delta: 0,
5201 htlc_minimum_msat: 0,
5202 htlc_maximum_msat: 100_000,
5204 fee_proportional_millionths: 0,
5205 excess_data: Vec::new()
5208 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5209 // All channels should be 100 sats capacity. But for the fee experiment,
5210 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5211 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5212 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5213 // so no matter how large are other channels,
5214 // the whole path will be limited by 100 sats with just these 2 conditions:
5215 // - channel 12 capacity is 250 sats
5216 // - fee for channel 6 is 150 sats
5217 // Let's test this by enforcing these 2 conditions and removing other limits.
5218 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5219 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5220 short_channel_id: 12,
5223 cltv_expiry_delta: 0,
5224 htlc_minimum_msat: 0,
5225 htlc_maximum_msat: 250_000,
5227 fee_proportional_millionths: 0,
5228 excess_data: Vec::new()
5230 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5231 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5232 short_channel_id: 13,
5235 cltv_expiry_delta: 0,
5236 htlc_minimum_msat: 0,
5237 htlc_maximum_msat: MAX_VALUE_MSAT,
5239 fee_proportional_millionths: 0,
5240 excess_data: Vec::new()
5243 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5244 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5245 short_channel_id: 6,
5248 cltv_expiry_delta: 0,
5249 htlc_minimum_msat: 0,
5250 htlc_maximum_msat: MAX_VALUE_MSAT,
5251 fee_base_msat: 150_000,
5252 fee_proportional_millionths: 0,
5253 excess_data: Vec::new()
5255 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5256 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5257 short_channel_id: 11,
5260 cltv_expiry_delta: 0,
5261 htlc_minimum_msat: 0,
5262 htlc_maximum_msat: MAX_VALUE_MSAT,
5264 fee_proportional_millionths: 0,
5265 excess_data: Vec::new()
5269 // Attempt to route more than available results in a failure.
5270 let route_params = RouteParameters::from_payment_params_and_value(
5271 payment_params.clone(), 210_000);
5272 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5273 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5274 &scorer, &Default::default(), &random_seed_bytes) {
5275 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5276 } else { panic!(); }
5280 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5281 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5282 max_total_routing_fee_msat: Some(149_999) };
5283 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5284 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5285 &scorer, &(), &random_seed_bytes) {
5286 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5287 } else { panic!(); }
5291 // Now, attempt to route 200 sats (exact amount we can route).
5292 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5293 max_total_routing_fee_msat: Some(150_000) };
5294 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5295 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5296 assert_eq!(route.paths.len(), 2);
5298 let mut total_amount_paid_msat = 0;
5299 for path in &route.paths {
5300 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5301 total_amount_paid_msat += path.final_value_msat();
5303 assert_eq!(total_amount_paid_msat, 200_000);
5304 assert_eq!(route.get_total_fees(), 150_000);
5309 fn mpp_with_last_hops() {
5310 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5311 // via a single last-hop route hint, we'd fail to route if we first collected routes
5312 // totaling close but not quite enough to fund the full payment.
5314 // This was because we considered last-hop hints to have exactly the sought payment amount
5315 // instead of the amount we were trying to collect, needlessly limiting our path searching
5316 // at the very first hop.
5318 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5319 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5320 // to only have the remaining to-collect amount in available liquidity.
5322 // This bug appeared in production in some specific channel configurations.
5323 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5324 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5325 let scorer = ln_test_utils::TestScorer::new();
5326 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5327 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5328 let config = UserConfig::default();
5329 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5330 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5331 src_node_id: nodes[2],
5332 short_channel_id: 42,
5333 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5334 cltv_expiry_delta: 42,
5335 htlc_minimum_msat: None,
5336 htlc_maximum_msat: None,
5337 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5339 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5340 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5341 // would first use the no-fee route and then fail to find a path along the second route as
5342 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5343 // under 5% of our payment amount.
5344 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5345 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5346 short_channel_id: 1,
5349 cltv_expiry_delta: (5 << 4) | 5,
5350 htlc_minimum_msat: 0,
5351 htlc_maximum_msat: 99_000,
5352 fee_base_msat: u32::max_value(),
5353 fee_proportional_millionths: u32::max_value(),
5354 excess_data: Vec::new()
5356 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5357 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5358 short_channel_id: 2,
5361 cltv_expiry_delta: (5 << 4) | 3,
5362 htlc_minimum_msat: 0,
5363 htlc_maximum_msat: 99_000,
5364 fee_base_msat: u32::max_value(),
5365 fee_proportional_millionths: u32::max_value(),
5366 excess_data: Vec::new()
5368 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5370 short_channel_id: 4,
5373 cltv_expiry_delta: (4 << 4) | 1,
5374 htlc_minimum_msat: 0,
5375 htlc_maximum_msat: MAX_VALUE_MSAT,
5377 fee_proportional_millionths: 0,
5378 excess_data: Vec::new()
5380 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5382 short_channel_id: 13,
5384 flags: 0|2, // Channel disabled
5385 cltv_expiry_delta: (13 << 4) | 1,
5386 htlc_minimum_msat: 0,
5387 htlc_maximum_msat: MAX_VALUE_MSAT,
5389 fee_proportional_millionths: 2000000,
5390 excess_data: Vec::new()
5393 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5395 let route_params = RouteParameters::from_payment_params_and_value(
5396 payment_params, 100_000);
5397 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5398 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5399 assert_eq!(route.paths.len(), 2);
5400 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5401 // Paths are manually ordered ordered by SCID, so:
5402 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5403 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5404 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5405 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5406 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5407 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5408 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5409 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5410 assert_eq!(route.get_total_fees(), 1);
5411 assert_eq!(route.get_total_amount(), 100_000);
5415 fn drop_lowest_channel_mpp_route_test() {
5416 // This test checks that low-capacity channel is dropped when after
5417 // path finding we realize that we found more capacity than we need.
5418 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5419 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5420 let scorer = ln_test_utils::TestScorer::new();
5421 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5422 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5423 let config = UserConfig::default();
5424 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5425 .with_max_channel_saturation_power_of_half(0);
5427 // We need a route consisting of 3 paths:
5428 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5430 // The first and the second paths should be sufficient, but the third should be
5431 // cheaper, so that we select it but drop later.
5433 // First, we set limits on these (previously unlimited) channels.
5434 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5436 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5437 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5438 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5439 short_channel_id: 1,
5442 cltv_expiry_delta: 0,
5443 htlc_minimum_msat: 0,
5444 htlc_maximum_msat: 100_000,
5446 fee_proportional_millionths: 0,
5447 excess_data: Vec::new()
5449 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5450 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5451 short_channel_id: 3,
5454 cltv_expiry_delta: 0,
5455 htlc_minimum_msat: 0,
5456 htlc_maximum_msat: 50_000,
5458 fee_proportional_millionths: 0,
5459 excess_data: Vec::new()
5462 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5463 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5464 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5465 short_channel_id: 12,
5468 cltv_expiry_delta: 0,
5469 htlc_minimum_msat: 0,
5470 htlc_maximum_msat: 60_000,
5472 fee_proportional_millionths: 0,
5473 excess_data: Vec::new()
5475 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5476 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5477 short_channel_id: 13,
5480 cltv_expiry_delta: 0,
5481 htlc_minimum_msat: 0,
5482 htlc_maximum_msat: 60_000,
5484 fee_proportional_millionths: 0,
5485 excess_data: Vec::new()
5488 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5489 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5490 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5491 short_channel_id: 2,
5494 cltv_expiry_delta: 0,
5495 htlc_minimum_msat: 0,
5496 htlc_maximum_msat: 20_000,
5498 fee_proportional_millionths: 0,
5499 excess_data: Vec::new()
5501 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5502 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5503 short_channel_id: 4,
5506 cltv_expiry_delta: 0,
5507 htlc_minimum_msat: 0,
5508 htlc_maximum_msat: 20_000,
5510 fee_proportional_millionths: 0,
5511 excess_data: Vec::new()
5515 // Attempt to route more than available results in a failure.
5516 let route_params = RouteParameters::from_payment_params_and_value(
5517 payment_params.clone(), 150_000);
5518 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5519 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5520 &scorer, &Default::default(), &random_seed_bytes) {
5521 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5522 } else { panic!(); }
5526 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5527 // Our algorithm should provide us with these 3 paths.
5528 let route_params = RouteParameters::from_payment_params_and_value(
5529 payment_params.clone(), 125_000);
5530 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5531 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5532 assert_eq!(route.paths.len(), 3);
5533 let mut total_amount_paid_msat = 0;
5534 for path in &route.paths {
5535 assert_eq!(path.hops.len(), 2);
5536 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5537 total_amount_paid_msat += path.final_value_msat();
5539 assert_eq!(total_amount_paid_msat, 125_000);
5543 // Attempt to route without the last small cheap channel
5544 let route_params = RouteParameters::from_payment_params_and_value(
5545 payment_params, 90_000);
5546 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5547 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5548 assert_eq!(route.paths.len(), 2);
5549 let mut total_amount_paid_msat = 0;
5550 for path in &route.paths {
5551 assert_eq!(path.hops.len(), 2);
5552 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5553 total_amount_paid_msat += path.final_value_msat();
5555 assert_eq!(total_amount_paid_msat, 90_000);
5560 fn min_criteria_consistency() {
5561 // Test that we don't use an inconsistent metric between updating and walking nodes during
5562 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5563 // was updated with a different criterion from the heap sorting, resulting in loops in
5564 // calculated paths. We test for that specific case here.
5566 // We construct a network that looks like this:
5568 // node2 -1(3)2- node3
5572 // node1 -1(5)2- node4 -1(1)2- node6
5578 // We create a loop on the side of our real path - our destination is node 6, with a
5579 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5580 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5581 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5582 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5583 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5584 // "previous hop" being set to node 3, creating a loop in the path.
5585 let secp_ctx = Secp256k1::new();
5586 let logger = Arc::new(ln_test_utils::TestLogger::new());
5587 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5588 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5589 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5590 let scorer = ln_test_utils::TestScorer::new();
5591 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5592 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5593 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5595 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5596 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5597 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5598 short_channel_id: 6,
5601 cltv_expiry_delta: (6 << 4) | 0,
5602 htlc_minimum_msat: 0,
5603 htlc_maximum_msat: MAX_VALUE_MSAT,
5605 fee_proportional_millionths: 0,
5606 excess_data: Vec::new()
5608 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5610 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5611 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5612 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5613 short_channel_id: 5,
5616 cltv_expiry_delta: (5 << 4) | 0,
5617 htlc_minimum_msat: 0,
5618 htlc_maximum_msat: MAX_VALUE_MSAT,
5620 fee_proportional_millionths: 0,
5621 excess_data: Vec::new()
5623 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5625 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5626 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5627 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5628 short_channel_id: 4,
5631 cltv_expiry_delta: (4 << 4) | 0,
5632 htlc_minimum_msat: 0,
5633 htlc_maximum_msat: MAX_VALUE_MSAT,
5635 fee_proportional_millionths: 0,
5636 excess_data: Vec::new()
5638 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5640 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5641 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5642 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5643 short_channel_id: 3,
5646 cltv_expiry_delta: (3 << 4) | 0,
5647 htlc_minimum_msat: 0,
5648 htlc_maximum_msat: MAX_VALUE_MSAT,
5650 fee_proportional_millionths: 0,
5651 excess_data: Vec::new()
5653 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5655 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5656 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5657 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5658 short_channel_id: 2,
5661 cltv_expiry_delta: (2 << 4) | 0,
5662 htlc_minimum_msat: 0,
5663 htlc_maximum_msat: MAX_VALUE_MSAT,
5665 fee_proportional_millionths: 0,
5666 excess_data: Vec::new()
5669 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5670 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5671 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5672 short_channel_id: 1,
5675 cltv_expiry_delta: (1 << 4) | 0,
5676 htlc_minimum_msat: 100,
5677 htlc_maximum_msat: MAX_VALUE_MSAT,
5679 fee_proportional_millionths: 0,
5680 excess_data: Vec::new()
5682 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5685 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5686 let route_params = RouteParameters::from_payment_params_and_value(
5687 payment_params, 10_000);
5688 let route = get_route(&our_id, &route_params, &network.read_only(), None,
5689 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5690 assert_eq!(route.paths.len(), 1);
5691 assert_eq!(route.paths[0].hops.len(), 3);
5693 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5694 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5695 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5696 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5697 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5698 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5700 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5701 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5702 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5703 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5704 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5705 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5707 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5708 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5709 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5710 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5711 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5712 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5718 fn exact_fee_liquidity_limit() {
5719 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5720 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5721 // we calculated fees on a higher value, resulting in us ignoring such paths.
5722 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5723 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5724 let scorer = ln_test_utils::TestScorer::new();
5725 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5726 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5727 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5729 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5731 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5732 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5733 short_channel_id: 2,
5736 cltv_expiry_delta: 0,
5737 htlc_minimum_msat: 0,
5738 htlc_maximum_msat: 85_000,
5740 fee_proportional_millionths: 0,
5741 excess_data: Vec::new()
5744 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5746 short_channel_id: 12,
5749 cltv_expiry_delta: (4 << 4) | 1,
5750 htlc_minimum_msat: 0,
5751 htlc_maximum_msat: 270_000,
5753 fee_proportional_millionths: 1000000,
5754 excess_data: Vec::new()
5758 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5759 // 200% fee charged channel 13 in the 1-to-2 direction.
5760 let route_params = RouteParameters::from_payment_params_and_value(
5761 payment_params, 90_000);
5762 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5763 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5764 assert_eq!(route.paths.len(), 1);
5765 assert_eq!(route.paths[0].hops.len(), 2);
5767 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5768 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5769 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5770 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5771 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5772 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5774 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5775 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5776 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5777 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5778 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5779 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5784 fn htlc_max_reduction_below_min() {
5785 // Test that if, while walking the graph, we reduce the value being sent to meet an
5786 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5787 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5788 // resulting in us thinking there is no possible path, even if other paths exist.
5789 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5790 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5791 let scorer = ln_test_utils::TestScorer::new();
5792 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5793 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5794 let config = UserConfig::default();
5795 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5797 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5798 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5799 // then try to send 90_000.
5800 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5801 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5802 short_channel_id: 2,
5805 cltv_expiry_delta: 0,
5806 htlc_minimum_msat: 0,
5807 htlc_maximum_msat: 80_000,
5809 fee_proportional_millionths: 0,
5810 excess_data: Vec::new()
5812 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5813 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5814 short_channel_id: 4,
5817 cltv_expiry_delta: (4 << 4) | 1,
5818 htlc_minimum_msat: 90_000,
5819 htlc_maximum_msat: MAX_VALUE_MSAT,
5821 fee_proportional_millionths: 0,
5822 excess_data: Vec::new()
5826 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5827 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5828 // expensive) channels 12-13 path.
5829 let route_params = RouteParameters::from_payment_params_and_value(
5830 payment_params, 90_000);
5831 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5832 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5833 assert_eq!(route.paths.len(), 1);
5834 assert_eq!(route.paths[0].hops.len(), 2);
5836 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5837 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5838 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5839 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5840 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5841 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5843 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5844 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5845 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5846 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5847 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5848 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5853 fn multiple_direct_first_hops() {
5854 // Previously we'd only ever considered one first hop path per counterparty.
5855 // However, as we don't restrict users to one channel per peer, we really need to support
5856 // looking at all first hop paths.
5857 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5858 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5859 // route over multiple channels with the same first hop.
5860 let secp_ctx = Secp256k1::new();
5861 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5862 let logger = Arc::new(ln_test_utils::TestLogger::new());
5863 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5864 let scorer = ln_test_utils::TestScorer::new();
5865 let config = UserConfig::default();
5866 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5867 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5868 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5871 let route_params = RouteParameters::from_payment_params_and_value(
5872 payment_params.clone(), 100_000);
5873 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5874 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5875 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5876 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5877 assert_eq!(route.paths.len(), 1);
5878 assert_eq!(route.paths[0].hops.len(), 1);
5880 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5881 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5882 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5885 let route_params = RouteParameters::from_payment_params_and_value(
5886 payment_params.clone(), 100_000);
5887 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5888 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5889 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5890 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5891 assert_eq!(route.paths.len(), 2);
5892 assert_eq!(route.paths[0].hops.len(), 1);
5893 assert_eq!(route.paths[1].hops.len(), 1);
5895 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5896 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5898 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5899 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5901 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5902 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5906 // If we have a bunch of outbound channels to the same node, where most are not
5907 // sufficient to pay the full payment, but one is, we should default to just using the
5908 // one single channel that has sufficient balance, avoiding MPP.
5910 // If we have several options above the 3xpayment value threshold, we should pick the
5911 // smallest of them, avoiding further fragmenting our available outbound balance to
5913 let route_params = RouteParameters::from_payment_params_and_value(
5914 payment_params, 100_000);
5915 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5916 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5917 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5918 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5919 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5920 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5921 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5922 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5923 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5924 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5925 assert_eq!(route.paths.len(), 1);
5926 assert_eq!(route.paths[0].hops.len(), 1);
5928 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5929 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5930 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5935 fn prefers_shorter_route_with_higher_fees() {
5936 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5937 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5938 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5940 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5941 let scorer = ln_test_utils::TestScorer::new();
5942 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5943 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5944 let route_params = RouteParameters::from_payment_params_and_value(
5945 payment_params.clone(), 100);
5946 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
5947 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5948 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5950 assert_eq!(route.get_total_fees(), 100);
5951 assert_eq!(route.get_total_amount(), 100);
5952 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5954 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5955 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5956 let scorer = FixedPenaltyScorer::with_penalty(100);
5957 let route_params = RouteParameters::from_payment_params_and_value(
5958 payment_params, 100);
5959 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
5960 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5961 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5963 assert_eq!(route.get_total_fees(), 300);
5964 assert_eq!(route.get_total_amount(), 100);
5965 assert_eq!(path, vec![2, 4, 7, 10]);
5968 struct BadChannelScorer {
5969 short_channel_id: u64,
5973 impl Writeable for BadChannelScorer {
5974 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5976 impl ScoreLookUp for BadChannelScorer {
5977 type ScoreParams = ();
5978 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5979 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5983 struct BadNodeScorer {
5988 impl Writeable for BadNodeScorer {
5989 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5992 impl ScoreLookUp for BadNodeScorer {
5993 type ScoreParams = ();
5994 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5995 if *target == self.node_id { u64::max_value() } else { 0 }
6000 fn avoids_routing_through_bad_channels_and_nodes() {
6001 let (secp_ctx, network, _, _, logger) = build_graph();
6002 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6003 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6004 let network_graph = network.read_only();
6006 // A path to nodes[6] exists when no penalties are applied to any channel.
6007 let scorer = ln_test_utils::TestScorer::new();
6008 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6009 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6010 let route_params = RouteParameters::from_payment_params_and_value(
6011 payment_params, 100);
6012 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6013 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6014 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6016 assert_eq!(route.get_total_fees(), 100);
6017 assert_eq!(route.get_total_amount(), 100);
6018 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6020 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6021 let scorer = BadChannelScorer { short_channel_id: 6 };
6022 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6023 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6024 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6026 assert_eq!(route.get_total_fees(), 300);
6027 assert_eq!(route.get_total_amount(), 100);
6028 assert_eq!(path, vec![2, 4, 7, 10]);
6030 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6031 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6032 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6033 &scorer, &Default::default(), &random_seed_bytes) {
6034 Err(LightningError { err, .. } ) => {
6035 assert_eq!(err, "Failed to find a path to the given destination");
6037 Ok(_) => panic!("Expected error"),
6042 fn total_fees_single_path() {
6044 paths: vec![Path { hops: vec![
6046 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6047 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6048 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6051 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6052 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6053 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6056 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6057 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6058 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6060 ], blinded_tail: None }],
6064 assert_eq!(route.get_total_fees(), 250);
6065 assert_eq!(route.get_total_amount(), 225);
6069 fn total_fees_multi_path() {
6071 paths: vec![Path { hops: vec![
6073 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6074 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6075 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6078 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6079 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6080 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6082 ], blinded_tail: None }, Path { hops: vec![
6084 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6085 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6086 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6089 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6090 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6091 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6093 ], blinded_tail: None }],
6097 assert_eq!(route.get_total_fees(), 200);
6098 assert_eq!(route.get_total_amount(), 300);
6102 fn total_empty_route_no_panic() {
6103 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6104 // would both panic if the route was completely empty. We test to ensure they return 0
6105 // here, even though its somewhat nonsensical as a route.
6106 let route = Route { paths: Vec::new(), route_params: None };
6108 assert_eq!(route.get_total_fees(), 0);
6109 assert_eq!(route.get_total_amount(), 0);
6113 fn limits_total_cltv_delta() {
6114 let (secp_ctx, network, _, _, logger) = build_graph();
6115 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6116 let network_graph = network.read_only();
6118 let scorer = ln_test_utils::TestScorer::new();
6120 // Make sure that generally there is at least one route available
6121 let feasible_max_total_cltv_delta = 1008;
6122 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6123 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6124 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6125 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6126 let route_params = RouteParameters::from_payment_params_and_value(
6127 feasible_payment_params, 100);
6128 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6129 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6130 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6131 assert_ne!(path.len(), 0);
6133 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6134 let fail_max_total_cltv_delta = 23;
6135 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6136 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6137 let route_params = RouteParameters::from_payment_params_and_value(
6138 fail_payment_params, 100);
6139 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6140 &Default::default(), &random_seed_bytes)
6142 Err(LightningError { err, .. } ) => {
6143 assert_eq!(err, "Failed to find a path to the given destination");
6145 Ok(_) => panic!("Expected error"),
6150 fn avoids_recently_failed_paths() {
6151 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6152 // randomly inserting channels into it until we can't find a route anymore.
6153 let (secp_ctx, network, _, _, logger) = build_graph();
6154 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6155 let network_graph = network.read_only();
6157 let scorer = ln_test_utils::TestScorer::new();
6158 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6159 .with_max_path_count(1);
6160 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6161 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6163 // We should be able to find a route initially, and then after we fail a few random
6164 // channels eventually we won't be able to any longer.
6165 let route_params = RouteParameters::from_payment_params_and_value(
6166 payment_params.clone(), 100);
6167 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6168 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6170 let route_params = RouteParameters::from_payment_params_and_value(
6171 payment_params.clone(), 100);
6172 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6173 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6175 for chan in route.paths[0].hops.iter() {
6176 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6178 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6179 % route.paths[0].hops.len();
6180 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6186 fn limits_path_length() {
6187 let (secp_ctx, network, _, _, logger) = build_line_graph();
6188 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6189 let network_graph = network.read_only();
6191 let scorer = ln_test_utils::TestScorer::new();
6192 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6193 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6195 // First check we can actually create a long route on this graph.
6196 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6197 let route_params = RouteParameters::from_payment_params_and_value(
6198 feasible_payment_params, 100);
6199 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6200 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6201 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6202 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6204 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6205 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6206 let route_params = RouteParameters::from_payment_params_and_value(
6207 fail_payment_params, 100);
6208 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6209 &Default::default(), &random_seed_bytes)
6211 Err(LightningError { err, .. } ) => {
6212 assert_eq!(err, "Failed to find a path to the given destination");
6214 Ok(_) => panic!("Expected error"),
6219 fn adds_and_limits_cltv_offset() {
6220 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6221 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6223 let scorer = ln_test_utils::TestScorer::new();
6225 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6226 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6227 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6228 let route_params = RouteParameters::from_payment_params_and_value(
6229 payment_params.clone(), 100);
6230 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6231 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6232 assert_eq!(route.paths.len(), 1);
6234 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6236 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6237 let mut route_default = route.clone();
6238 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6239 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6240 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6241 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6242 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6244 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6245 let mut route_limited = route.clone();
6246 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6247 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6248 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6249 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6250 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6254 fn adds_plausible_cltv_offset() {
6255 let (secp_ctx, network, _, _, logger) = build_graph();
6256 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6257 let network_graph = network.read_only();
6258 let network_nodes = network_graph.nodes();
6259 let network_channels = network_graph.channels();
6260 let scorer = ln_test_utils::TestScorer::new();
6261 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6262 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6263 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6265 let route_params = RouteParameters::from_payment_params_and_value(
6266 payment_params.clone(), 100);
6267 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6268 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6269 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6271 let mut path_plausibility = vec![];
6273 for p in route.paths {
6274 // 1. Select random observation point
6275 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6276 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6278 prng.process_in_place(&mut random_bytes);
6279 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6280 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6282 // 2. Calculate what CLTV expiry delta we would observe there
6283 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6285 // 3. Starting from the observation point, find candidate paths
6286 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6287 candidates.push_back((observation_point, vec![]));
6289 let mut found_plausible_candidate = false;
6291 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6292 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6293 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6294 found_plausible_candidate = true;
6295 break 'candidate_loop;
6299 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6300 for channel_id in &cur_node.channels {
6301 if let Some(channel_info) = network_channels.get(&channel_id) {
6302 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6303 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6304 if cur_path_cltv_deltas.iter().sum::<u32>()
6305 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6306 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6307 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6308 candidates.push_back((*next_id, new_path_cltv_deltas));
6316 path_plausibility.push(found_plausible_candidate);
6318 assert!(path_plausibility.iter().all(|x| *x));
6322 fn builds_correct_path_from_hops() {
6323 let (secp_ctx, network, _, _, logger) = build_graph();
6324 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6325 let network_graph = network.read_only();
6327 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6328 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6330 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6331 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6332 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6333 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6334 Arc::clone(&logger), &random_seed_bytes).unwrap();
6335 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6336 assert_eq!(hops.len(), route.paths[0].hops.len());
6337 for (idx, hop_pubkey) in hops.iter().enumerate() {
6338 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6343 fn avoids_saturating_channels() {
6344 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6345 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6346 let decay_params = ProbabilisticScoringDecayParameters::default();
6347 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6349 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6350 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6351 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6352 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6353 short_channel_id: 4,
6356 cltv_expiry_delta: (4 << 4) | 1,
6357 htlc_minimum_msat: 0,
6358 htlc_maximum_msat: 250_000_000,
6360 fee_proportional_millionths: 0,
6361 excess_data: Vec::new()
6363 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6364 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6365 short_channel_id: 13,
6368 cltv_expiry_delta: (13 << 4) | 1,
6369 htlc_minimum_msat: 0,
6370 htlc_maximum_msat: 250_000_000,
6372 fee_proportional_millionths: 0,
6373 excess_data: Vec::new()
6376 let config = UserConfig::default();
6377 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6378 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6379 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6380 // 100,000 sats is less than the available liquidity on each channel, set above.
6381 let route_params = RouteParameters::from_payment_params_and_value(
6382 payment_params, 100_000_000);
6383 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6384 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6385 assert_eq!(route.paths.len(), 2);
6386 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6387 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6390 #[cfg(not(feature = "no-std"))]
6391 pub(super) fn random_init_seed() -> u64 {
6392 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6393 use core::hash::{BuildHasher, Hasher};
6394 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6395 println!("Using seed of {}", seed);
6400 #[cfg(not(feature = "no-std"))]
6401 fn generate_routes() {
6402 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6404 let logger = ln_test_utils::TestLogger::new();
6405 let graph = match super::bench_utils::read_network_graph(&logger) {
6413 let params = ProbabilisticScoringFeeParameters::default();
6414 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6415 let features = super::Bolt11InvoiceFeatures::empty();
6417 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6421 #[cfg(not(feature = "no-std"))]
6422 fn generate_routes_mpp() {
6423 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6425 let logger = ln_test_utils::TestLogger::new();
6426 let graph = match super::bench_utils::read_network_graph(&logger) {
6434 let params = ProbabilisticScoringFeeParameters::default();
6435 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6436 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6438 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6442 #[cfg(not(feature = "no-std"))]
6443 fn generate_large_mpp_routes() {
6444 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6446 let logger = ln_test_utils::TestLogger::new();
6447 let graph = match super::bench_utils::read_network_graph(&logger) {
6455 let params = ProbabilisticScoringFeeParameters::default();
6456 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6457 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6459 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6463 fn honors_manual_penalties() {
6464 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6465 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6467 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6468 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6470 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6471 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6473 // First check set manual penalties are returned by the scorer.
6474 let usage = ChannelUsage {
6476 inflight_htlc_msat: 0,
6477 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6479 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6480 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6481 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
6483 // Then check we can get a normal route
6484 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6485 let route_params = RouteParameters::from_payment_params_and_value(
6486 payment_params, 100);
6487 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6488 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6489 assert!(route.is_ok());
6491 // Then check that we can't get a route if we ban an intermediate node.
6492 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6493 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6494 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6495 assert!(route.is_err());
6497 // Finally make sure we can route again, when we remove the ban.
6498 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6499 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6500 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6501 assert!(route.is_ok());
6505 fn abide_by_route_hint_max_htlc() {
6506 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6507 // params in the final route.
6508 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6509 let netgraph = network_graph.read_only();
6510 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6511 let scorer = ln_test_utils::TestScorer::new();
6512 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6513 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6514 let config = UserConfig::default();
6516 let max_htlc_msat = 50_000;
6517 let route_hint_1 = RouteHint(vec![RouteHintHop {
6518 src_node_id: nodes[2],
6519 short_channel_id: 42,
6522 proportional_millionths: 0,
6524 cltv_expiry_delta: 10,
6525 htlc_minimum_msat: None,
6526 htlc_maximum_msat: Some(max_htlc_msat),
6528 let dest_node_id = ln_test_utils::pubkey(42);
6529 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6530 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6531 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6533 // Make sure we'll error if our route hints don't have enough liquidity according to their
6534 // htlc_maximum_msat.
6535 let route_params = RouteParameters::from_payment_params_and_value(
6536 payment_params, max_htlc_msat + 1);
6537 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6538 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
6541 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6542 } else { panic!(); }
6544 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6545 let mut route_hint_2 = route_hint_1.clone();
6546 route_hint_2.0[0].short_channel_id = 43;
6547 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6548 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6549 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6550 let route_params = RouteParameters::from_payment_params_and_value(
6551 payment_params, max_htlc_msat + 1);
6552 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
6553 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6554 assert_eq!(route.paths.len(), 2);
6555 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6556 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6560 fn direct_channel_to_hints_with_max_htlc() {
6561 // Check that if we have a first hop channel peer that's connected to multiple provided route
6562 // hints, that we properly split the payment between the route hints if needed.
6563 let logger = Arc::new(ln_test_utils::TestLogger::new());
6564 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6565 let scorer = ln_test_utils::TestScorer::new();
6566 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6567 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6568 let config = UserConfig::default();
6570 let our_node_id = ln_test_utils::pubkey(42);
6571 let intermed_node_id = ln_test_utils::pubkey(43);
6572 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6574 let amt_msat = 900_000;
6575 let max_htlc_msat = 500_000;
6576 let route_hint_1 = RouteHint(vec![RouteHintHop {
6577 src_node_id: intermed_node_id,
6578 short_channel_id: 44,
6581 proportional_millionths: 0,
6583 cltv_expiry_delta: 10,
6584 htlc_minimum_msat: None,
6585 htlc_maximum_msat: Some(max_htlc_msat),
6587 src_node_id: intermed_node_id,
6588 short_channel_id: 45,
6591 proportional_millionths: 0,
6593 cltv_expiry_delta: 10,
6594 htlc_minimum_msat: None,
6595 // Check that later route hint max htlcs don't override earlier ones
6596 htlc_maximum_msat: Some(max_htlc_msat - 50),
6598 let mut route_hint_2 = route_hint_1.clone();
6599 route_hint_2.0[0].short_channel_id = 46;
6600 route_hint_2.0[1].short_channel_id = 47;
6601 let dest_node_id = ln_test_utils::pubkey(44);
6602 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6603 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6604 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6606 let route_params = RouteParameters::from_payment_params_and_value(
6607 payment_params, amt_msat);
6608 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6609 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6610 &Default::default(), &random_seed_bytes).unwrap();
6611 assert_eq!(route.paths.len(), 2);
6612 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6613 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6614 assert_eq!(route.get_total_amount(), amt_msat);
6616 // Re-run but with two first hop channels connected to the same route hint peers that must be
6618 let first_hops = vec![
6619 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6620 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6622 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6623 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6624 &Default::default(), &random_seed_bytes).unwrap();
6625 assert_eq!(route.paths.len(), 2);
6626 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6627 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6628 assert_eq!(route.get_total_amount(), amt_msat);
6630 // Make sure this works for blinded route hints.
6631 let blinded_path = BlindedPath {
6632 introduction_node_id: intermed_node_id,
6633 blinding_point: ln_test_utils::pubkey(42),
6635 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6636 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6639 let blinded_payinfo = BlindedPayInfo {
6641 fee_proportional_millionths: 0,
6642 htlc_minimum_msat: 1,
6643 htlc_maximum_msat: max_htlc_msat,
6644 cltv_expiry_delta: 10,
6645 features: BlindedHopFeatures::empty(),
6647 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6648 let payment_params = PaymentParameters::blinded(vec![
6649 (blinded_payinfo.clone(), blinded_path.clone()),
6650 (blinded_payinfo.clone(), blinded_path.clone())])
6651 .with_bolt12_features(bolt12_features).unwrap();
6652 let route_params = RouteParameters::from_payment_params_and_value(
6653 payment_params, amt_msat);
6654 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6655 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6656 &Default::default(), &random_seed_bytes).unwrap();
6657 assert_eq!(route.paths.len(), 2);
6658 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6659 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6660 assert_eq!(route.get_total_amount(), amt_msat);
6664 fn blinded_route_ser() {
6665 let blinded_path_1 = BlindedPath {
6666 introduction_node_id: ln_test_utils::pubkey(42),
6667 blinding_point: ln_test_utils::pubkey(43),
6669 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6670 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6673 let blinded_path_2 = BlindedPath {
6674 introduction_node_id: ln_test_utils::pubkey(46),
6675 blinding_point: ln_test_utils::pubkey(47),
6677 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6678 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6681 // (De)serialize a Route with 1 blinded path out of two total paths.
6682 let mut route = Route { paths: vec![Path {
6683 hops: vec![RouteHop {
6684 pubkey: ln_test_utils::pubkey(50),
6685 node_features: NodeFeatures::empty(),
6686 short_channel_id: 42,
6687 channel_features: ChannelFeatures::empty(),
6689 cltv_expiry_delta: 0,
6690 maybe_announced_channel: true,
6692 blinded_tail: Some(BlindedTail {
6693 hops: blinded_path_1.blinded_hops,
6694 blinding_point: blinded_path_1.blinding_point,
6695 excess_final_cltv_expiry_delta: 40,
6696 final_value_msat: 100,
6698 hops: vec![RouteHop {
6699 pubkey: ln_test_utils::pubkey(51),
6700 node_features: NodeFeatures::empty(),
6701 short_channel_id: 43,
6702 channel_features: ChannelFeatures::empty(),
6704 cltv_expiry_delta: 0,
6705 maybe_announced_channel: true,
6706 }], blinded_tail: None }],
6709 let encoded_route = route.encode();
6710 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6711 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6712 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6714 // (De)serialize a Route with two paths, each containing a blinded tail.
6715 route.paths[1].blinded_tail = Some(BlindedTail {
6716 hops: blinded_path_2.blinded_hops,
6717 blinding_point: blinded_path_2.blinding_point,
6718 excess_final_cltv_expiry_delta: 41,
6719 final_value_msat: 101,
6721 let encoded_route = route.encode();
6722 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6723 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6724 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6728 fn blinded_path_inflight_processing() {
6729 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6730 // account for the blinded tail's final amount_msat.
6731 let mut inflight_htlcs = InFlightHtlcs::new();
6732 let blinded_path = BlindedPath {
6733 introduction_node_id: ln_test_utils::pubkey(43),
6734 blinding_point: ln_test_utils::pubkey(48),
6735 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
6738 hops: vec![RouteHop {
6739 pubkey: ln_test_utils::pubkey(42),
6740 node_features: NodeFeatures::empty(),
6741 short_channel_id: 42,
6742 channel_features: ChannelFeatures::empty(),
6744 cltv_expiry_delta: 0,
6745 maybe_announced_channel: false,
6748 pubkey: blinded_path.introduction_node_id,
6749 node_features: NodeFeatures::empty(),
6750 short_channel_id: 43,
6751 channel_features: ChannelFeatures::empty(),
6753 cltv_expiry_delta: 0,
6754 maybe_announced_channel: false,
6756 blinded_tail: Some(BlindedTail {
6757 hops: blinded_path.blinded_hops,
6758 blinding_point: blinded_path.blinding_point,
6759 excess_final_cltv_expiry_delta: 0,
6760 final_value_msat: 200,
6763 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
6764 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
6765 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
6769 fn blinded_path_cltv_shadow_offset() {
6770 // Make sure we add a shadow offset when sending to blinded paths.
6771 let blinded_path = BlindedPath {
6772 introduction_node_id: ln_test_utils::pubkey(43),
6773 blinding_point: ln_test_utils::pubkey(44),
6775 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
6776 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
6779 let mut route = Route { paths: vec![Path {
6780 hops: vec![RouteHop {
6781 pubkey: ln_test_utils::pubkey(42),
6782 node_features: NodeFeatures::empty(),
6783 short_channel_id: 42,
6784 channel_features: ChannelFeatures::empty(),
6786 cltv_expiry_delta: 0,
6787 maybe_announced_channel: false,
6790 pubkey: blinded_path.introduction_node_id,
6791 node_features: NodeFeatures::empty(),
6792 short_channel_id: 43,
6793 channel_features: ChannelFeatures::empty(),
6795 cltv_expiry_delta: 0,
6796 maybe_announced_channel: false,
6799 blinded_tail: Some(BlindedTail {
6800 hops: blinded_path.blinded_hops,
6801 blinding_point: blinded_path.blinding_point,
6802 excess_final_cltv_expiry_delta: 0,
6803 final_value_msat: 200,
6805 }], route_params: None};
6807 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
6808 let (_, network_graph, _, _, _) = build_line_graph();
6809 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
6810 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
6811 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
6815 fn simple_blinded_route_hints() {
6816 do_simple_blinded_route_hints(1);
6817 do_simple_blinded_route_hints(2);
6818 do_simple_blinded_route_hints(3);
6821 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
6822 // Check that we can generate a route to a blinded path with the expected hops.
6823 let (secp_ctx, network, _, _, logger) = build_graph();
6824 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6825 let network_graph = network.read_only();
6827 let scorer = ln_test_utils::TestScorer::new();
6828 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6829 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6831 let mut blinded_path = BlindedPath {
6832 introduction_node_id: nodes[2],
6833 blinding_point: ln_test_utils::pubkey(42),
6834 blinded_hops: Vec::with_capacity(num_blinded_hops),
6836 for i in 0..num_blinded_hops {
6837 blinded_path.blinded_hops.push(
6838 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
6841 let blinded_payinfo = BlindedPayInfo {
6843 fee_proportional_millionths: 500,
6844 htlc_minimum_msat: 1000,
6845 htlc_maximum_msat: 100_000_000,
6846 cltv_expiry_delta: 15,
6847 features: BlindedHopFeatures::empty(),
6850 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
6851 let route_params = RouteParameters::from_payment_params_and_value(
6852 payment_params, 1001);
6853 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6854 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6855 assert_eq!(route.paths.len(), 1);
6856 assert_eq!(route.paths[0].hops.len(), 2);
6858 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
6859 assert_eq!(tail.hops, blinded_path.blinded_hops);
6860 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
6861 assert_eq!(tail.final_value_msat, 1001);
6863 let final_hop = route.paths[0].hops.last().unwrap();
6864 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
6865 if tail.hops.len() > 1 {
6866 assert_eq!(final_hop.fee_msat,
6867 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
6868 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
6870 assert_eq!(final_hop.fee_msat, 0);
6871 assert_eq!(final_hop.cltv_expiry_delta, 0);
6876 fn blinded_path_routing_errors() {
6877 // Check that we can generate a route to a blinded path with the expected hops.
6878 let (secp_ctx, network, _, _, logger) = build_graph();
6879 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6880 let network_graph = network.read_only();
6882 let scorer = ln_test_utils::TestScorer::new();
6883 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6884 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6886 let mut invalid_blinded_path = BlindedPath {
6887 introduction_node_id: nodes[2],
6888 blinding_point: ln_test_utils::pubkey(42),
6890 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
6893 let blinded_payinfo = BlindedPayInfo {
6895 fee_proportional_millionths: 500,
6896 htlc_minimum_msat: 1000,
6897 htlc_maximum_msat: 100_000_000,
6898 cltv_expiry_delta: 15,
6899 features: BlindedHopFeatures::empty(),
6902 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
6903 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
6904 let payment_params = PaymentParameters::blinded(vec![
6905 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
6906 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
6907 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6908 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6909 &scorer, &Default::default(), &random_seed_bytes)
6911 Err(LightningError { err, .. }) => {
6912 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
6914 _ => panic!("Expected error")
6917 invalid_blinded_path.introduction_node_id = our_id;
6918 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
6919 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6920 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6921 &Default::default(), &random_seed_bytes)
6923 Err(LightningError { err, .. }) => {
6924 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
6926 _ => panic!("Expected error")
6929 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
6930 invalid_blinded_path.blinded_hops.clear();
6931 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
6932 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6933 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6934 &Default::default(), &random_seed_bytes)
6936 Err(LightningError { err, .. }) => {
6937 assert_eq!(err, "0-hop blinded path provided");
6939 _ => panic!("Expected error")
6944 fn matching_intro_node_paths_provided() {
6945 // Check that if multiple blinded paths with the same intro node are provided in payment
6946 // parameters, we'll return the correct paths in the resulting MPP route.
6947 let (secp_ctx, network, _, _, logger) = build_graph();
6948 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6949 let network_graph = network.read_only();
6951 let scorer = ln_test_utils::TestScorer::new();
6952 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6953 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6954 let config = UserConfig::default();
6956 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6957 let blinded_path_1 = BlindedPath {
6958 introduction_node_id: nodes[2],
6959 blinding_point: ln_test_utils::pubkey(42),
6961 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6962 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6965 let blinded_payinfo_1 = BlindedPayInfo {
6967 fee_proportional_millionths: 0,
6968 htlc_minimum_msat: 0,
6969 htlc_maximum_msat: 30_000,
6970 cltv_expiry_delta: 0,
6971 features: BlindedHopFeatures::empty(),
6974 let mut blinded_path_2 = blinded_path_1.clone();
6975 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
6976 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
6977 blinded_payinfo_2.htlc_maximum_msat = 70_000;
6979 let blinded_hints = vec![
6980 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
6981 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
6983 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
6984 .with_bolt12_features(bolt12_features.clone()).unwrap();
6986 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
6987 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6988 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6989 assert_eq!(route.paths.len(), 2);
6990 let mut total_amount_paid_msat = 0;
6991 for path in route.paths.into_iter() {
6992 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6993 if let Some(bt) = &path.blinded_tail {
6994 assert_eq!(bt.blinding_point,
6995 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
6996 .map(|(_, bp)| bp.blinding_point).unwrap());
6997 } else { panic!(); }
6998 total_amount_paid_msat += path.final_value_msat();
7000 assert_eq!(total_amount_paid_msat, 100_000);
7004 fn direct_to_intro_node() {
7005 // This previously caused a debug panic in the router when asserting
7006 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7007 // direct channels we failed to account for the fee charged for use of the blinded path.
7010 // node0 -1(1)2 - node1
7011 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7012 // doesn't account for the blinded path fee.
7014 let secp_ctx = Secp256k1::new();
7015 let logger = Arc::new(ln_test_utils::TestLogger::new());
7016 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7017 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7018 let scorer = ln_test_utils::TestScorer::new();
7019 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7020 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7022 let amt_msat = 10_000_000;
7023 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7024 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7025 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7026 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7027 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
7028 short_channel_id: 1,
7031 cltv_expiry_delta: 42,
7032 htlc_minimum_msat: 1_000,
7033 htlc_maximum_msat: 10_000_000,
7035 fee_proportional_millionths: 0,
7036 excess_data: Vec::new()
7038 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7039 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
7040 short_channel_id: 1,
7043 cltv_expiry_delta: 42,
7044 htlc_minimum_msat: 1_000,
7045 htlc_maximum_msat: 10_000_000,
7047 fee_proportional_millionths: 0,
7048 excess_data: Vec::new()
7050 let first_hops = vec![
7051 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7053 let blinded_path = BlindedPath {
7054 introduction_node_id: nodes[1],
7055 blinding_point: ln_test_utils::pubkey(42),
7057 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7058 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7061 let blinded_payinfo = BlindedPayInfo {
7062 fee_base_msat: 1000,
7063 fee_proportional_millionths: 0,
7064 htlc_minimum_msat: 1000,
7065 htlc_maximum_msat: MAX_VALUE_MSAT,
7066 cltv_expiry_delta: 0,
7067 features: BlindedHopFeatures::empty(),
7069 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7071 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7073 let netgraph = network_graph.read_only();
7074 let route_params = RouteParameters::from_payment_params_and_value(
7075 payment_params.clone(), amt_msat);
7076 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7077 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7078 &Default::default(), &random_seed_bytes) {
7079 assert_eq!(err, "Failed to find a path to the given destination");
7080 } else { panic!("Expected error") }
7082 // Sending an exact amount accounting for the blinded path fee works.
7083 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7084 let route_params = RouteParameters::from_payment_params_and_value(
7085 payment_params, amt_minus_blinded_path_fee);
7086 let route = get_route(&nodes[0], &route_params, &netgraph,
7087 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7088 &Default::default(), &random_seed_bytes).unwrap();
7089 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7090 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7094 fn direct_to_matching_intro_nodes() {
7095 // This previously caused us to enter `unreachable` code in the following situation:
7096 // 1. We add a route candidate for intro_node contributing a high amount
7097 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7098 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7099 // amount, and update our route candidate for intro_node for the lower amount
7100 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7101 // lower contribution amount, but fail (this was previously caused by failure to account for
7102 // blinded path fees when adding first_hop<>intro_node candidates)
7103 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7104 // candidate still thinks its path is contributing the original higher amount. This caused us
7105 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7107 let secp_ctx = Secp256k1::new();
7108 let logger = Arc::new(ln_test_utils::TestLogger::new());
7109 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7110 let scorer = ln_test_utils::TestScorer::new();
7111 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7112 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7113 let config = UserConfig::default();
7115 // Values are taken from the fuzz input that uncovered this panic.
7116 let amt_msat = 21_7020_5185_1403_2640;
7117 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7118 let first_hops = vec![
7119 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7120 18446744073709551615)];
7122 let blinded_path = BlindedPath {
7123 introduction_node_id: nodes[1],
7124 blinding_point: ln_test_utils::pubkey(42),
7126 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7127 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7130 let blinded_payinfo = BlindedPayInfo {
7131 fee_base_msat: 5046_2720,
7132 fee_proportional_millionths: 0,
7133 htlc_minimum_msat: 4503_5996_2737_0496,
7134 htlc_maximum_msat: 45_0359_9627_3704_9600,
7135 cltv_expiry_delta: 0,
7136 features: BlindedHopFeatures::empty(),
7138 let mut blinded_hints = vec![
7139 (blinded_payinfo.clone(), blinded_path.clone()),
7140 (blinded_payinfo.clone(), blinded_path.clone()),
7142 blinded_hints[1].0.fee_base_msat = 419_4304;
7143 blinded_hints[1].0.fee_proportional_millionths = 257;
7144 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7145 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7146 blinded_hints[1].0.cltv_expiry_delta = 0;
7148 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7149 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7150 .with_bolt12_features(bolt12_features.clone()).unwrap();
7152 let netgraph = network_graph.read_only();
7153 let route_params = RouteParameters::from_payment_params_and_value(
7154 payment_params, amt_msat);
7155 let route = get_route(&nodes[0], &route_params, &netgraph,
7156 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7157 &Default::default(), &random_seed_bytes).unwrap();
7158 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7159 assert_eq!(route.get_total_amount(), amt_msat);
7163 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
7164 pub(crate) mod bench_utils {
7168 use bitcoin::hashes::Hash;
7169 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
7171 use crate::chain::transaction::OutPoint;
7172 use crate::routing::scoring::ScoreUpdate;
7173 use crate::sign::{EntropySource, KeysManager};
7174 use crate::ln::ChannelId;
7175 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
7176 use crate::ln::features::Bolt11InvoiceFeatures;
7177 use crate::routing::gossip::NetworkGraph;
7178 use crate::util::config::UserConfig;
7179 use crate::util::ser::ReadableArgs;
7180 use crate::util::test_utils::TestLogger;
7182 /// Tries to open a network graph file, or panics with a URL to fetch it.
7183 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
7184 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
7185 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
7186 .or_else(|_| { // Fall back to guessing based on the binary location
7187 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
7188 let mut path = std::env::current_exe().unwrap();
7189 path.pop(); // lightning-...
7191 path.pop(); // debug
7192 path.pop(); // target
7193 path.push("lightning");
7194 path.push("net_graph-2023-01-18.bin");
7197 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
7198 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
7199 let mut path = std::env::current_exe().unwrap();
7200 path.pop(); // bench...
7202 path.pop(); // debug
7203 path.pop(); // target
7204 path.pop(); // bench
7205 path.push("lightning");
7206 path.push("net_graph-2023-01-18.bin");
7209 .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");
7210 #[cfg(require_route_graph_test)]
7211 return Ok(res.unwrap());
7212 #[cfg(not(require_route_graph_test))]
7216 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
7217 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
7220 pub(crate) fn payer_pubkey() -> PublicKey {
7221 let secp_ctx = Secp256k1::new();
7222 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
7226 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
7228 channel_id: ChannelId::new_zero(),
7229 counterparty: ChannelCounterparty {
7230 features: channelmanager::provided_init_features(&UserConfig::default()),
7232 unspendable_punishment_reserve: 0,
7233 forwarding_info: None,
7234 outbound_htlc_minimum_msat: None,
7235 outbound_htlc_maximum_msat: None,
7237 funding_txo: Some(OutPoint {
7238 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
7241 short_channel_id: Some(1),
7242 inbound_scid_alias: None,
7243 outbound_scid_alias: None,
7244 channel_value_satoshis: 10_000_000_000,
7246 outbound_capacity_msat: 10_000_000_000,
7247 next_outbound_htlc_minimum_msat: 0,
7248 next_outbound_htlc_limit_msat: 10_000_000_000,
7249 inbound_capacity_msat: 0,
7250 unspendable_punishment_reserve: None,
7251 confirmations_required: None,
7252 confirmations: None,
7253 force_close_spend_delay: None,
7255 is_channel_ready: true,
7258 inbound_htlc_minimum_msat: None,
7259 inbound_htlc_maximum_msat: None,
7261 feerate_sat_per_1000_weight: None,
7262 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
7266 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
7267 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
7268 starting_amount: u64, route_count: usize,
7269 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
7270 let payer = payer_pubkey();
7271 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7272 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7274 let nodes = graph.read_only().nodes().clone();
7275 let mut route_endpoints = Vec::new();
7276 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
7277 // with some routes we picked being un-routable.
7278 for _ in 0..route_count * 3 / 2 {
7280 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7281 let src = PublicKey::from_slice(nodes.unordered_keys()
7282 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
7283 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7284 let dst = PublicKey::from_slice(nodes.unordered_keys()
7285 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
7286 let params = PaymentParameters::from_node_id(dst, 42)
7287 .with_bolt11_features(features.clone()).unwrap();
7288 let first_hop = first_hop(src);
7289 let amt_msat = starting_amount + seed % 1_000_000;
7290 let route_params = RouteParameters::from_payment_params_and_value(
7291 params.clone(), amt_msat);
7293 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
7294 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
7296 // ...and seed the scorer with success and failure data...
7297 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7298 let mut score_amt = seed % 1_000_000_000;
7300 // Generate fail/success paths for a wider range of potential amounts with
7301 // MPP enabled to give us a chance to apply penalties for more potential
7303 let mpp_features = channelmanager::provided_invoice_features(&UserConfig::default());
7304 let params = PaymentParameters::from_node_id(dst, 42)
7305 .with_bolt11_features(mpp_features).unwrap();
7306 let route_params = RouteParameters::from_payment_params_and_value(
7307 params.clone(), score_amt);
7308 let route_res = get_route(&payer, &route_params, &graph.read_only(),
7309 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
7310 &random_seed_bytes);
7311 if let Ok(route) = route_res {
7312 for path in route.paths {
7313 if seed & 0x80 == 0 {
7314 scorer.payment_path_successful(&path);
7316 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
7317 scorer.payment_path_failed(&path, short_channel_id);
7319 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7323 // If we couldn't find a path with a higer amount, reduce and try again.
7327 route_endpoints.push((first_hop, params, amt_msat));
7333 // Because we've changed channel scores, it's possible we'll take different routes to the
7334 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
7335 // requires a too-high CLTV delta.
7336 route_endpoints.retain(|(first_hop, params, amt_msat)| {
7337 let route_params = RouteParameters::from_payment_params_and_value(
7338 params.clone(), *amt_msat);
7339 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
7340 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
7342 route_endpoints.truncate(route_count);
7343 assert_eq!(route_endpoints.len(), route_count);
7351 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
7352 use crate::sign::{EntropySource, KeysManager};
7353 use crate::ln::channelmanager;
7354 use crate::ln::features::Bolt11InvoiceFeatures;
7355 use crate::routing::gossip::NetworkGraph;
7356 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
7357 use crate::util::config::UserConfig;
7358 use crate::util::logger::{Logger, Record};
7359 use crate::util::test_utils::TestLogger;
7361 use criterion::Criterion;
7363 struct DummyLogger {}
7364 impl Logger for DummyLogger {
7365 fn log(&self, _record: &Record) {}
7368 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7369 let logger = TestLogger::new();
7370 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7371 let scorer = FixedPenaltyScorer::with_penalty(0);
7372 generate_routes(bench, &network_graph, scorer, &Default::default(),
7373 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
7376 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7377 let logger = TestLogger::new();
7378 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7379 let scorer = FixedPenaltyScorer::with_penalty(0);
7380 generate_routes(bench, &network_graph, scorer, &Default::default(),
7381 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7382 "generate_mpp_routes_with_zero_penalty_scorer");
7385 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7386 let logger = TestLogger::new();
7387 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7388 let params = ProbabilisticScoringFeeParameters::default();
7389 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7390 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
7391 "generate_routes_with_probabilistic_scorer");
7394 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7395 let logger = TestLogger::new();
7396 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7397 let params = ProbabilisticScoringFeeParameters::default();
7398 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7399 generate_routes(bench, &network_graph, scorer, ¶ms,
7400 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7401 "generate_mpp_routes_with_probabilistic_scorer");
7404 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7405 let logger = TestLogger::new();
7406 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7407 let params = ProbabilisticScoringFeeParameters::default();
7408 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7409 generate_routes(bench, &network_graph, scorer, ¶ms,
7410 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
7411 "generate_large_mpp_routes_with_probabilistic_scorer");
7414 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
7415 let logger = TestLogger::new();
7416 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7417 let mut params = ProbabilisticScoringFeeParameters::default();
7418 params.linear_success_probability = false;
7419 let scorer = ProbabilisticScorer::new(
7420 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7421 generate_routes(bench, &network_graph, scorer, ¶ms,
7422 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7423 "generate_routes_with_nonlinear_probabilistic_scorer");
7426 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
7427 let logger = TestLogger::new();
7428 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7429 let mut params = ProbabilisticScoringFeeParameters::default();
7430 params.linear_success_probability = false;
7431 let scorer = ProbabilisticScorer::new(
7432 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7433 generate_routes(bench, &network_graph, scorer, ¶ms,
7434 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7435 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
7438 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
7439 let logger = TestLogger::new();
7440 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7441 let mut params = ProbabilisticScoringFeeParameters::default();
7442 params.linear_success_probability = false;
7443 let scorer = ProbabilisticScorer::new(
7444 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7445 generate_routes(bench, &network_graph, scorer, ¶ms,
7446 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
7447 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
7450 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
7451 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
7452 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
7453 bench_name: &'static str,
7455 let payer = bench_utils::payer_pubkey();
7456 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7457 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7459 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
7460 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
7462 // ...then benchmark finding paths between the nodes we learned.
7464 bench.bench_function(bench_name, |b| b.iter(|| {
7465 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
7466 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
7467 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
7468 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());