1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The router finds paths within a [`NetworkGraph`] for a payment.
12 use bitcoin::secp256k1::PublicKey;
13 use bitcoin::hashes::Hash;
14 use bitcoin::hashes::sha256::Hash as Sha256;
16 use crate::blinded_path::{BlindedHop, BlindedPath};
17 use crate::ln::PaymentHash;
18 use crate::ln::channelmanager::{ChannelDetails, PaymentId};
19 use crate::ln::features::{Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
20 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
21 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice};
22 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
23 use crate::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp};
24 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
25 use crate::util::logger::{Level, Logger};
26 use crate::util::chacha20::ChaCha20;
29 use crate::prelude::*;
30 use crate::sync::Mutex;
31 use alloc::collections::BinaryHeap;
35 /// A [`Router`] implemented using [`find_route`].
36 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> where
38 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
42 random_seed_bytes: Mutex<[u8; 32]>,
47 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> DefaultRouter<G, L, S, SP, Sc> where
49 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
51 /// Creates a new router.
52 pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32], scorer: S, score_params: SP) -> Self {
53 let random_seed_bytes = Mutex::new(random_seed_bytes);
54 Self { network_graph, logger, random_seed_bytes, scorer, score_params }
58 impl< G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> Router for DefaultRouter<G, L, S, SP, Sc> where
60 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
65 params: &RouteParameters,
66 first_hops: Option<&[&ChannelDetails]>,
67 inflight_htlcs: InFlightHtlcs
68 ) -> Result<Route, LightningError> {
69 let random_seed_bytes = {
70 let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
71 *locked_random_seed_bytes = Sha256::hash(&*locked_random_seed_bytes).into_inner();
72 *locked_random_seed_bytes
75 payer, params, &self.network_graph, first_hops, &*self.logger,
76 &ScorerAccountingForInFlightHtlcs::new(self.scorer.read_lock(), &inflight_htlcs),
83 /// A trait defining behavior for routing a payment.
85 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
87 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
88 /// and [`RouteParameters::final_value_msat`], respectively.
90 &self, payer: &PublicKey, route_params: &RouteParameters,
91 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
92 ) -> Result<Route, LightningError>;
93 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
95 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
96 /// and [`RouteParameters::final_value_msat`], respectively.
98 /// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
100 fn find_route_with_id(
101 &self, payer: &PublicKey, route_params: &RouteParameters,
102 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
103 _payment_hash: PaymentHash, _payment_id: PaymentId
104 ) -> Result<Route, LightningError> {
105 self.find_route(payer, route_params, first_hops, inflight_htlcs)
109 /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
111 /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
114 /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
115 pub struct ScorerAccountingForInFlightHtlcs<'a, SP: Sized, Sc: 'a + ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> {
117 // Maps a channel's short channel id and its direction to the liquidity used up.
118 inflight_htlcs: &'a InFlightHtlcs,
120 impl<'a, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> ScorerAccountingForInFlightHtlcs<'a, SP, Sc, S> {
121 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
122 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
123 ScorerAccountingForInFlightHtlcs {
131 impl<'a, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> Writeable for ScorerAccountingForInFlightHtlcs<'a, SP, Sc, S> {
132 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.scorer.write(writer) }
135 impl<'a, SP: Sized, Sc: 'a + ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, SP, Sc, S> {
136 type ScoreParams = Sc::ScoreParams;
137 fn channel_penalty_msat(&self, short_channel_id: u64, source: &NodeId, target: &NodeId, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
138 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
139 source, target, short_channel_id
141 let usage = ChannelUsage {
142 inflight_htlc_msat: usage.inflight_htlc_msat + used_liquidity,
146 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
148 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
153 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
154 /// in-use channel liquidity.
156 pub struct InFlightHtlcs(
157 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
158 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
159 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
161 HashMap<(u64, bool), u64>
165 /// Constructs an empty `InFlightHtlcs`.
166 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
168 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
169 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
170 if path.hops.is_empty() { return };
172 let mut cumulative_msat = 0;
173 if let Some(tail) = &path.blinded_tail {
174 cumulative_msat += tail.final_value_msat;
177 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
178 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
179 // the router excludes the payer node. In the following lines, the payer's information is
180 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
181 // in our sliding window of two.
182 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
183 .map(|hop| hop.pubkey)
184 .chain(core::iter::once(payer_node_id));
186 // Taking the reversed vector from above, we zip it with just the reversed hops list to
187 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
188 // the total amount sent.
189 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
190 cumulative_msat += next_hop.fee_msat;
192 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
193 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
194 .or_insert(cumulative_msat);
198 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
200 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
202 .entry((channel_scid, source < target))
203 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
204 .or_insert(used_msat);
207 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
209 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
210 self.0.get(&(channel_scid, source < target)).map(|v| *v)
214 impl Writeable for InFlightHtlcs {
215 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
218 impl Readable for InFlightHtlcs {
219 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
220 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
221 Ok(Self(infight_map))
225 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
226 /// that leads to it.
227 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
228 pub struct RouteHop {
229 /// The node_id of the node at this hop.
230 pub pubkey: PublicKey,
231 /// The node_announcement features of the node at this hop. For the last hop, these may be
232 /// amended to match the features present in the invoice this node generated.
233 pub node_features: NodeFeatures,
234 /// The channel that should be used from the previous hop to reach this node.
235 pub short_channel_id: u64,
236 /// The channel_announcement features of the channel that should be used from the previous hop
237 /// to reach this node.
238 pub channel_features: ChannelFeatures,
239 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
240 /// If this is the last hop in [`Path::hops`]:
241 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
242 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
244 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
246 /// The CLTV delta added for this hop.
247 /// If this is the last hop in [`Path::hops`]:
248 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
249 /// * otherwise, this is the CLTV delta expected at the destination
251 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
252 pub cltv_expiry_delta: u32,
253 /// Indicates whether this hop is possibly announced in the public network graph.
255 /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
256 /// either know for sure it's announced in the public graph, or if any public channels exist
257 /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
258 /// the channel to be unannounced.
260 /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
261 pub maybe_announced_channel: bool,
264 impl_writeable_tlv_based!(RouteHop, {
265 (0, pubkey, required),
266 (1, maybe_announced_channel, (default_value, true)),
267 (2, node_features, required),
268 (4, short_channel_id, required),
269 (6, channel_features, required),
270 (8, fee_msat, required),
271 (10, cltv_expiry_delta, required),
274 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
275 /// their [`Bolt12Invoice`].
277 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
278 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
279 pub struct BlindedTail {
280 /// The hops of the [`BlindedPath`] provided by the recipient.
282 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
283 pub hops: Vec<BlindedHop>,
284 /// The blinding point of the [`BlindedPath`] provided by the recipient.
286 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
287 pub blinding_point: PublicKey,
288 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
289 /// inferring the destination. May be 0.
290 pub excess_final_cltv_expiry_delta: u32,
291 /// The total amount paid on this [`Path`], excluding the fees.
292 pub final_value_msat: u64,
295 impl_writeable_tlv_based!(BlindedTail, {
296 (0, hops, required_vec),
297 (2, blinding_point, required),
298 (4, excess_final_cltv_expiry_delta, required),
299 (6, final_value_msat, required),
302 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
303 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
304 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
306 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
307 pub hops: Vec<RouteHop>,
308 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
309 pub blinded_tail: Option<BlindedTail>,
313 /// Gets the fees for a given path, excluding any excess paid to the recipient.
314 pub fn fee_msat(&self) -> u64 {
315 match &self.blinded_tail {
316 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
318 // Do not count last hop of each path since that's the full value of the payment
319 self.hops.split_last().map_or(0,
320 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
325 /// Gets the total amount paid on this [`Path`], excluding the fees.
326 pub fn final_value_msat(&self) -> u64 {
327 match &self.blinded_tail {
328 Some(blinded_tail) => blinded_tail.final_value_msat,
329 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
333 /// Gets the final hop's CLTV expiry delta.
334 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
335 match &self.blinded_tail {
337 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
342 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
343 /// it can take multiple paths. Each path is composed of one or more hops through the network.
344 #[derive(Clone, Hash, PartialEq, Eq)]
346 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
347 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
349 pub paths: Vec<Path>,
350 /// The `route_params` parameter passed to [`find_route`].
352 /// This is used by `ChannelManager` to track information which may be required for retries.
354 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
355 pub route_params: Option<RouteParameters>,
359 /// Returns the total amount of fees paid on this [`Route`].
361 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
362 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
363 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
365 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
366 pub fn get_total_fees(&self) -> u64 {
367 let overpaid_value_msat = self.route_params.as_ref()
368 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
369 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
372 /// Returns the total amount paid on this [`Route`], excluding the fees.
374 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
375 /// we had to reach the [`htlc_minimum_msat`] limits.
377 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
378 pub fn get_total_amount(&self) -> u64 {
379 self.paths.iter().map(|path| path.final_value_msat()).sum()
383 const SERIALIZATION_VERSION: u8 = 1;
384 const MIN_SERIALIZATION_VERSION: u8 = 1;
386 impl Writeable for Route {
387 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
388 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
389 (self.paths.len() as u64).write(writer)?;
390 let mut blinded_tails = Vec::new();
391 for path in self.paths.iter() {
392 (path.hops.len() as u8).write(writer)?;
393 for (idx, hop) in path.hops.iter().enumerate() {
395 if let Some(blinded_tail) = &path.blinded_tail {
396 if blinded_tails.is_empty() {
397 blinded_tails = Vec::with_capacity(path.hops.len());
399 blinded_tails.push(None);
402 blinded_tails.push(Some(blinded_tail));
403 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
406 write_tlv_fields!(writer, {
407 // For compatibility with LDK versions prior to 0.0.117, we take the individual
408 // RouteParameters' fields and reconstruct them on read.
409 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
410 (2, blinded_tails, optional_vec),
411 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
412 (5, self.route_params.as_ref().map(|p| p.max_total_routing_fee_msat), option),
418 impl Readable for Route {
419 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
420 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
421 let path_count: u64 = Readable::read(reader)?;
422 if path_count == 0 { return Err(DecodeError::InvalidValue); }
423 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
424 let mut min_final_cltv_expiry_delta = u32::max_value();
425 for _ in 0..path_count {
426 let hop_count: u8 = Readable::read(reader)?;
427 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
428 for _ in 0..hop_count {
429 hops.push(Readable::read(reader)?);
431 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
432 min_final_cltv_expiry_delta =
433 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
434 paths.push(Path { hops, blinded_tail: None });
436 _init_and_read_len_prefixed_tlv_fields!(reader, {
437 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
438 (2, blinded_tails, optional_vec),
439 (3, final_value_msat, option),
440 (5, max_total_routing_fee_msat, option)
442 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
443 if blinded_tails.len() != 0 {
444 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
445 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
446 path.blinded_tail = blinded_tail_opt;
450 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
451 let route_params = match (payment_params, final_value_msat) {
452 (Some(payment_params), Some(final_value_msat)) => {
453 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
458 Ok(Route { paths, route_params })
462 /// Parameters needed to find a [`Route`].
464 /// Passed to [`find_route`] and [`build_route_from_hops`].
465 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
466 pub struct RouteParameters {
467 /// The parameters of the failed payment path.
468 pub payment_params: PaymentParameters,
470 /// The amount in msats sent on the failed payment path.
471 pub final_value_msat: u64,
473 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
475 /// This limit also applies to the total fees that may arise while retrying failed payment
478 /// Default value: `None`
479 pub max_total_routing_fee_msat: Option<u64>,
482 impl RouteParameters {
483 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
484 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
485 Self { payment_params, final_value_msat, max_total_routing_fee_msat: None }
489 impl Writeable for RouteParameters {
490 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
491 write_tlv_fields!(writer, {
492 (0, self.payment_params, required),
493 (1, self.max_total_routing_fee_msat, option),
494 (2, self.final_value_msat, required),
495 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
496 // `RouteParameters` directly. For compatibility, we write it here.
497 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
503 impl Readable for RouteParameters {
504 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
505 _init_and_read_len_prefixed_tlv_fields!(reader, {
506 (0, payment_params, (required: ReadableArgs, 0)),
507 (1, max_total_routing_fee_msat, option),
508 (2, final_value_msat, required),
509 (4, final_cltv_delta, option),
511 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
512 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
513 if final_cltv_expiry_delta == &0 {
514 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
519 final_value_msat: final_value_msat.0.unwrap(),
520 max_total_routing_fee_msat,
525 /// Maximum total CTLV difference we allow for a full payment path.
526 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
528 /// Maximum number of paths we allow an (MPP) payment to have.
529 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
530 // limits, but for now more than 10 paths likely carries too much one-path failure.
531 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
533 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
535 // The median hop CLTV expiry delta currently seen in the network.
536 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
538 // During routing, we only consider paths shorter than our maximum length estimate.
539 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
540 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
541 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
543 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
544 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
545 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
546 // (payment_secret and total_msat) = 93 bytes for the final hop.
547 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
548 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
549 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
551 /// Information used to route a payment.
552 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
553 pub struct PaymentParameters {
554 /// Information about the payee, such as their features and route hints for their channels.
557 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
558 pub expiry_time: Option<u64>,
560 /// The maximum total CLTV delta we accept for the route.
561 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
562 pub max_total_cltv_expiry_delta: u32,
564 /// The maximum number of paths that may be used by (MPP) payments.
565 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
566 pub max_path_count: u8,
568 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
569 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
570 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
571 /// increasing failure probability for those paths.
573 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
574 /// restriction have been found. While paths which meet this criteria will be searched for, it
575 /// is ultimately up to the scorer to select them over other paths.
577 /// A value of 0 will allow payments up to and including a channel's total announced usable
578 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
581 pub max_channel_saturation_power_of_half: u8,
583 /// A list of SCIDs which this payment was previously attempted over and which caused the
584 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
586 pub previously_failed_channels: Vec<u64>,
589 impl Writeable for PaymentParameters {
590 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
591 let mut clear_hints = &vec![];
592 let mut blinded_hints = &vec![];
594 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
595 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
597 write_tlv_fields!(writer, {
598 (0, self.payee.node_id(), option),
599 (1, self.max_total_cltv_expiry_delta, required),
600 (2, self.payee.features(), option),
601 (3, self.max_path_count, required),
602 (4, *clear_hints, required_vec),
603 (5, self.max_channel_saturation_power_of_half, required),
604 (6, self.expiry_time, option),
605 (7, self.previously_failed_channels, required_vec),
606 (8, *blinded_hints, optional_vec),
607 (9, self.payee.final_cltv_expiry_delta(), option),
613 impl ReadableArgs<u32> for PaymentParameters {
614 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
615 _init_and_read_len_prefixed_tlv_fields!(reader, {
616 (0, payee_pubkey, option),
617 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
618 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
619 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
620 (4, clear_route_hints, required_vec),
621 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
622 (6, expiry_time, option),
623 (7, previously_failed_channels, optional_vec),
624 (8, blinded_route_hints, optional_vec),
625 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
627 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
628 let payee = if blinded_route_hints.len() != 0 {
629 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
631 route_hints: blinded_route_hints,
632 features: features.and_then(|f: Features| f.bolt12()),
636 route_hints: clear_route_hints,
637 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
638 features: features.and_then(|f| f.bolt11()),
639 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
643 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
644 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
646 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
648 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
654 impl PaymentParameters {
655 /// Creates a payee with the node id of the given `pubkey`.
657 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
659 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
661 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
663 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
664 max_path_count: DEFAULT_MAX_PATH_COUNT,
665 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
666 previously_failed_channels: Vec::new(),
670 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
672 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
675 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
676 /// whether your router will be allowed to find a multi-part route for this payment. If you
677 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
678 /// [`RecipientOnionFields::secret_only`].
680 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
681 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
682 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
683 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
684 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
687 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
688 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
689 /// [`PaymentParameters::expiry_time`].
690 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
691 Self::blinded(invoice.payment_paths().to_vec())
692 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
693 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
696 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
697 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
699 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
701 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
702 max_path_count: DEFAULT_MAX_PATH_COUNT,
703 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
704 previously_failed_channels: Vec::new(),
708 /// Includes the payee's features. Errors if the parameters were not initialized with
709 /// [`PaymentParameters::from_bolt12_invoice`].
711 /// This is not exported to bindings users since bindings don't support move semantics
712 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
714 Payee::Clear { .. } => Err(()),
715 Payee::Blinded { route_hints, .. } =>
716 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
720 /// Includes the payee's features. Errors if the parameters were initialized with
721 /// [`PaymentParameters::from_bolt12_invoice`].
723 /// This is not exported to bindings users since bindings don't support move semantics
724 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
726 Payee::Blinded { .. } => Err(()),
727 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
729 payee: Payee::Clear {
730 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
736 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
737 /// [`PaymentParameters::from_bolt12_invoice`].
739 /// This is not exported to bindings users since bindings don't support move semantics
740 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
742 Payee::Blinded { .. } => Err(()),
743 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
745 payee: Payee::Clear {
746 route_hints, node_id, features, final_cltv_expiry_delta,
752 /// Includes a payment expiration in seconds relative to the UNIX epoch.
754 /// This is not exported to bindings users since bindings don't support move semantics
755 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
756 Self { expiry_time: Some(expiry_time), ..self }
759 /// Includes a limit for the total CLTV expiry delta which is considered during routing
761 /// This is not exported to bindings users since bindings don't support move semantics
762 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
763 Self { max_total_cltv_expiry_delta, ..self }
766 /// Includes a limit for the maximum number of payment paths that may be used.
768 /// This is not exported to bindings users since bindings don't support move semantics
769 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
770 Self { max_path_count, ..self }
773 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
774 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
776 /// This is not exported to bindings users since bindings don't support move semantics
777 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
778 Self { max_channel_saturation_power_of_half, ..self }
782 /// The recipient of a payment, differing based on whether they've hidden their identity with route
784 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
786 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
787 /// will be included in the final [`Route`].
789 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
791 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
792 /// Features supported by the payee.
794 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
796 features: Option<Bolt12InvoiceFeatures>,
798 /// The recipient included these route hints in their BOLT11 invoice.
800 /// The node id of the payee.
802 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
803 route_hints: Vec<RouteHint>,
804 /// Features supported by the payee.
806 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
807 /// does not contain any features.
809 /// [`for_keysend`]: PaymentParameters::for_keysend
810 features: Option<Bolt11InvoiceFeatures>,
811 /// The minimum CLTV delta at the end of the route. This value must not be zero.
812 final_cltv_expiry_delta: u32,
817 fn node_id(&self) -> Option<PublicKey> {
819 Self::Clear { node_id, .. } => Some(*node_id),
823 fn node_features(&self) -> Option<NodeFeatures> {
825 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
826 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
829 fn supports_basic_mpp(&self) -> bool {
831 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
832 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
835 fn features(&self) -> Option<FeaturesRef> {
837 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
838 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
841 fn final_cltv_expiry_delta(&self) -> Option<u32> {
843 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
847 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
849 Self::Blinded { route_hints, .. } => &route_hints[..],
850 Self::Clear { .. } => &[]
854 fn unblinded_route_hints(&self) -> &[RouteHint] {
856 Self::Blinded { .. } => &[],
857 Self::Clear { route_hints, .. } => &route_hints[..]
862 enum FeaturesRef<'a> {
863 Bolt11(&'a Bolt11InvoiceFeatures),
864 Bolt12(&'a Bolt12InvoiceFeatures),
867 Bolt11(Bolt11InvoiceFeatures),
868 Bolt12(Bolt12InvoiceFeatures),
872 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
874 Self::Bolt12(f) => Some(f),
878 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
880 Self::Bolt11(f) => Some(f),
886 impl<'a> Writeable for FeaturesRef<'a> {
887 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
889 Self::Bolt11(f) => Ok(f.write(w)?),
890 Self::Bolt12(f) => Ok(f.write(w)?),
895 impl ReadableArgs<bool> for Features {
896 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
897 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
898 Ok(Self::Bolt12(Readable::read(reader)?))
902 /// A list of hops along a payment path terminating with a channel to the recipient.
903 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
904 pub struct RouteHint(pub Vec<RouteHintHop>);
906 impl Writeable for RouteHint {
907 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
908 (self.0.len() as u64).write(writer)?;
909 for hop in self.0.iter() {
916 impl Readable for RouteHint {
917 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
918 let hop_count: u64 = Readable::read(reader)?;
919 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
920 for _ in 0..hop_count {
921 hops.push(Readable::read(reader)?);
927 /// A channel descriptor for a hop along a payment path.
928 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
929 pub struct RouteHintHop {
930 /// The node_id of the non-target end of the route
931 pub src_node_id: PublicKey,
932 /// The short_channel_id of this channel
933 pub short_channel_id: u64,
934 /// The fees which must be paid to use this channel
935 pub fees: RoutingFees,
936 /// The difference in CLTV values between this node and the next node.
937 pub cltv_expiry_delta: u16,
938 /// The minimum value, in msat, which must be relayed to the next hop.
939 pub htlc_minimum_msat: Option<u64>,
940 /// The maximum value in msat available for routing with a single HTLC.
941 pub htlc_maximum_msat: Option<u64>,
944 impl_writeable_tlv_based!(RouteHintHop, {
945 (0, src_node_id, required),
946 (1, htlc_minimum_msat, option),
947 (2, short_channel_id, required),
948 (3, htlc_maximum_msat, option),
950 (6, cltv_expiry_delta, required),
953 #[derive(Eq, PartialEq)]
954 struct RouteGraphNode {
956 lowest_fee_to_node: u64,
957 total_cltv_delta: u32,
958 // The maximum value a yet-to-be-constructed payment path might flow through this node.
959 // This value is upper-bounded by us by:
960 // - how much is needed for a path being constructed
961 // - how much value can channels following this node (up to the destination) can contribute,
962 // considering their capacity and fees
963 value_contribution_msat: u64,
964 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
965 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
966 path_htlc_minimum_msat: u64,
967 /// All penalties incurred from this hop on the way to the destination, as calculated using
969 path_penalty_msat: u64,
970 /// The number of hops walked up to this node.
971 path_length_to_node: u8,
974 impl cmp::Ord for RouteGraphNode {
975 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
976 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
977 .saturating_add(other.path_penalty_msat);
978 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
979 .saturating_add(self.path_penalty_msat);
980 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
984 impl cmp::PartialOrd for RouteGraphNode {
985 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
986 Some(self.cmp(other))
990 /// A wrapper around the various hop representations.
992 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
993 #[derive(Clone, Debug)]
994 enum CandidateRouteHop<'a> {
995 /// A hop from the payer, where the outbound liquidity is known.
997 details: &'a ChannelDetails,
999 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
1001 info: DirectedChannelInfo<'a>,
1002 short_channel_id: u64,
1004 /// A hop to the payee found in the BOLT 11 payment invoice, though not necessarily a direct
1007 hint: &'a RouteHintHop,
1009 /// The payee's identity is concealed behind blinded paths provided in a BOLT 12 invoice.
1011 hint: &'a (BlindedPayInfo, BlindedPath),
1014 /// Similar to [`Self::Blinded`], but the path here has 1 blinded hop. `BlindedPayInfo` provided
1015 /// for 1-hop blinded paths is ignored because it is meant to apply to the hops *between* the
1016 /// introduction node and the destination. Useful for tracking that we need to include a blinded
1017 /// path at the end of our [`Route`].
1019 hint: &'a (BlindedPayInfo, BlindedPath),
1024 impl<'a> CandidateRouteHop<'a> {
1025 fn short_channel_id(&self) -> Option<u64> {
1027 CandidateRouteHop::FirstHop { details } => Some(details.get_outbound_payment_scid().unwrap()),
1028 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
1029 CandidateRouteHop::PrivateHop { hint } => Some(hint.short_channel_id),
1030 CandidateRouteHop::Blinded { .. } => None,
1031 CandidateRouteHop::OneHopBlinded { .. } => None,
1035 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1036 fn features(&self) -> ChannelFeatures {
1038 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
1039 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
1040 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
1041 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
1042 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
1046 fn cltv_expiry_delta(&self) -> u32 {
1048 CandidateRouteHop::FirstHop { .. } => 0,
1049 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1050 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
1051 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1052 CandidateRouteHop::OneHopBlinded { .. } => 0,
1056 fn htlc_minimum_msat(&self) -> u64 {
1058 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_minimum_msat,
1059 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1060 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
1061 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1062 CandidateRouteHop::OneHopBlinded { .. } => 0,
1066 fn fees(&self) -> RoutingFees {
1068 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1069 base_msat: 0, proportional_millionths: 0,
1071 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1072 CandidateRouteHop::PrivateHop { hint } => hint.fees,
1073 CandidateRouteHop::Blinded { hint, .. } => {
1075 base_msat: hint.0.fee_base_msat,
1076 proportional_millionths: hint.0.fee_proportional_millionths
1079 CandidateRouteHop::OneHopBlinded { .. } =>
1080 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1084 fn effective_capacity(&self) -> EffectiveCapacity {
1086 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
1087 liquidity_msat: details.next_outbound_htlc_limit_msat,
1089 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1090 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }} =>
1091 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1092 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }} =>
1093 EffectiveCapacity::Infinite,
1094 CandidateRouteHop::Blinded { hint, .. } =>
1095 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1096 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1100 fn id(&self, channel_direction: bool /* src_node_id < target_node_id */) -> CandidateHopId {
1102 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1103 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1104 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), channel_direction)),
1107 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1109 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1117 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1118 enum CandidateHopId {
1119 /// Contains (scid, src_node_id < target_node_id)
1121 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1126 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1127 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1129 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1130 EffectiveCapacity::Infinite => u64::max_value(),
1131 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1132 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1133 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1134 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1135 // expected to have been generated from up-to-date capacity information.
1136 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1137 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1138 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1142 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1143 -> bool where I1::Item: PartialEq<I2::Item> {
1145 let a = iter_a.next();
1146 let b = iter_b.next();
1147 if a.is_none() && b.is_none() { return true; }
1148 if a.is_none() || b.is_none() { return false; }
1149 if a.unwrap().ne(&b.unwrap()) { return false; }
1153 /// It's useful to keep track of the hops associated with the fees required to use them,
1154 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1155 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1156 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1158 struct PathBuildingHop<'a> {
1159 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
1160 // is a larger refactor and will require careful performance analysis.
1162 candidate: CandidateRouteHop<'a>,
1165 /// All the fees paid *after* this channel on the way to the destination
1166 next_hops_fee_msat: u64,
1167 /// Fee paid for the use of the current channel (see candidate.fees()).
1168 /// The value will be actually deducted from the counterparty balance on the previous link.
1169 hop_use_fee_msat: u64,
1170 /// Used to compare channels when choosing the for routing.
1171 /// Includes paying for the use of a hop and the following hops, as well as
1172 /// an estimated cost of reaching this hop.
1173 /// Might get stale when fees are recomputed. Primarily for internal use.
1174 total_fee_msat: u64,
1175 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1176 /// walk and may be invalid thereafter.
1177 path_htlc_minimum_msat: u64,
1178 /// All penalties incurred from this channel on the way to the destination, as calculated using
1179 /// channel scoring.
1180 path_penalty_msat: u64,
1181 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1182 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1183 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1184 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1185 /// avoid processing them again.
1186 was_processed: bool,
1187 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1188 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1189 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1190 // value_contribution_msat, which requires tracking it here. See comments below where it is
1191 // used for more info.
1192 value_contribution_msat: u64,
1195 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1196 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1197 let mut debug_struct = f.debug_struct("PathBuildingHop");
1199 .field("node_id", &self.node_id)
1200 .field("short_channel_id", &self.candidate.short_channel_id())
1201 .field("total_fee_msat", &self.total_fee_msat)
1202 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1203 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1204 .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)))
1205 .field("path_penalty_msat", &self.path_penalty_msat)
1206 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1207 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1208 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1209 let debug_struct = debug_struct
1210 .field("value_contribution_msat", &self.value_contribution_msat);
1211 debug_struct.finish()
1215 // Instantiated with a list of hops with correct data in them collected during path finding,
1216 // an instance of this struct should be further modified only via given methods.
1218 struct PaymentPath<'a> {
1219 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1222 impl<'a> PaymentPath<'a> {
1223 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1224 fn get_value_msat(&self) -> u64 {
1225 self.hops.last().unwrap().0.fee_msat
1228 fn get_path_penalty_msat(&self) -> u64 {
1229 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1232 fn get_total_fee_paid_msat(&self) -> u64 {
1233 if self.hops.len() < 1 {
1237 // Can't use next_hops_fee_msat because it gets outdated.
1238 for (i, (hop, _)) in self.hops.iter().enumerate() {
1239 if i != self.hops.len() - 1 {
1240 result += hop.fee_msat;
1246 fn get_cost_msat(&self) -> u64 {
1247 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1250 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1251 // to change fees may result in an inconsistency.
1253 // Sometimes we call this function right after constructing a path which is inconsistent in
1254 // that it the value being transferred has decreased while we were doing path finding, leading
1255 // to the fees being paid not lining up with the actual limits.
1257 // Note that this function is not aware of the available_liquidity limit, and thus does not
1258 // support increasing the value being transferred beyond what was selected during the initial
1260 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
1261 let mut total_fee_paid_msat = 0 as u64;
1262 for i in (0..self.hops.len()).rev() {
1263 let last_hop = i == self.hops.len() - 1;
1265 // For non-last-hop, this value will represent the fees paid on the current hop. It
1266 // will consist of the fees for the use of the next hop, and extra fees to match
1267 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1268 let mut cur_hop_fees_msat = 0;
1270 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1273 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1274 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1275 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1276 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1277 // set it too high just to maliciously take more fees by exploiting this
1278 // match htlc_minimum_msat logic.
1279 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1280 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1281 // Note that there is a risk that *previous hops* (those closer to us, as we go
1282 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1284 // This might make us end up with a broken route, although this should be super-rare
1285 // in practice, both because of how healthy channels look like, and how we pick
1286 // channels in add_entry.
1287 // Also, this can't be exploited more heavily than *announce a free path and fail
1289 cur_hop_transferred_amount_msat += extra_fees_msat;
1290 total_fee_paid_msat += extra_fees_msat;
1291 cur_hop_fees_msat += extra_fees_msat;
1295 // Final hop is a special case: it usually has just value_msat (by design), but also
1296 // it still could overpay for the htlc_minimum_msat.
1297 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1299 // Propagate updated fees for the use of the channels to one hop back, where they
1300 // will be actually paid (fee_msat). The last hop is handled above separately.
1301 cur_hop.fee_msat = cur_hop_fees_msat;
1304 // Fee for the use of the current hop which will be deducted on the previous hop.
1305 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1306 // this channel is free for us.
1308 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1309 cur_hop.hop_use_fee_msat = new_fee;
1310 total_fee_paid_msat += new_fee;
1312 // It should not be possible because this function is called only to reduce the
1313 // value. In that case, compute_fee was already called with the same fees for
1314 // larger amount and there was no overflow.
1323 /// Calculate the fees required to route the given amount over a channel with the given fees.
1324 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1325 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1326 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1330 /// Calculate the fees required to route the given amount over a channel with the given fees,
1331 /// saturating to [`u64::max_value`].
1332 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1333 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1334 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1335 .saturating_add(channel_fees.base_msat as u64)
1338 /// The default `features` we assume for a node in a route, when no `features` are known about that
1341 /// Default features are:
1342 /// * variable_length_onion_optional
1343 fn default_node_features() -> NodeFeatures {
1344 let mut features = NodeFeatures::empty();
1345 features.set_variable_length_onion_optional();
1349 struct LoggedPayeePubkey(Option<PublicKey>);
1350 impl fmt::Display for LoggedPayeePubkey {
1351 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1354 "payee node id ".fmt(f)?;
1358 "blinded payee".fmt(f)
1364 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1365 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1366 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1368 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1369 "blinded route hint with introduction node id ".fmt(f)?;
1370 hint.1.introduction_node_id.fmt(f)?;
1371 " and blinding point ".fmt(f)?;
1372 hint.1.blinding_point.fmt(f)
1374 CandidateRouteHop::FirstHop { .. } => {
1375 "first hop with SCID ".fmt(f)?;
1376 self.0.short_channel_id().unwrap().fmt(f)
1378 CandidateRouteHop::PrivateHop { .. } => {
1379 "route hint with SCID ".fmt(f)?;
1380 self.0.short_channel_id().unwrap().fmt(f)
1384 self.0.short_channel_id().unwrap().fmt(f)
1391 fn sort_first_hop_channels(
1392 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1393 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1395 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1396 // most like to use.
1398 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1399 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1402 // Second, because simply always sorting in descending order would always use our largest
1403 // available outbound capacity, needlessly fragmenting our available channel capacities,
1404 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1405 // which have enough, but not too much, capacity for the payment.
1407 // Available outbound balances factor in liquidity already reserved for previously found paths.
1408 channels.sort_unstable_by(|chan_a, chan_b| {
1409 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1410 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1411 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1412 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1413 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1414 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1415 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1416 // Sort in descending order
1417 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1419 // Sort in ascending order
1420 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1425 /// Finds a route from us (payer) to the given target node (payee).
1427 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1428 /// in the given [`RouteParameters::payment_params`].
1429 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1431 /// Private routing paths between a public node and the target may be included in the `payee` field
1432 /// of [`RouteParameters::payment_params`].
1434 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1435 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1436 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1438 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1439 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1440 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1444 /// Panics if first_hops contains channels without `short_channel_id`s;
1445 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1447 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1448 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1449 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1450 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1451 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1452 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1453 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1454 ) -> Result<Route, LightningError>
1455 where L::Target: Logger, GL::Target: Logger {
1456 let graph_lock = network_graph.read_only();
1457 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1458 scorer, score_params, random_seed_bytes)?;
1459 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1463 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1464 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1465 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1466 _random_seed_bytes: &[u8; 32]
1467 ) -> Result<Route, LightningError>
1468 where L::Target: Logger {
1470 let payment_params = &route_params.payment_params;
1471 let final_value_msat = route_params.final_value_msat;
1472 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1473 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1474 // so use a dummy id for this in the blinded case.
1475 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1476 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1477 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1478 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1479 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1481 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1482 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1485 if final_value_msat > MAX_VALUE_MSAT {
1486 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1489 if final_value_msat == 0 {
1490 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1493 match &payment_params.payee {
1494 Payee::Clear { route_hints, node_id, .. } => {
1495 for route in route_hints.iter() {
1496 for hop in &route.0 {
1497 if hop.src_node_id == *node_id {
1498 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1503 Payee::Blinded { route_hints, .. } => {
1504 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1505 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});
1507 for (_, blinded_path) in route_hints.iter() {
1508 if blinded_path.blinded_hops.len() == 0 {
1509 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1510 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1511 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1512 } else if blinded_path.blinded_hops.len() == 1 &&
1513 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1514 && p.introduction_node_id != blinded_path.introduction_node_id)
1516 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1521 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1522 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1523 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});
1526 // The general routing idea is the following:
1527 // 1. Fill first/last hops communicated by the caller.
1528 // 2. Attempt to construct a path from payer to payee for transferring
1529 // any ~sufficient (described later) value.
1530 // If succeed, remember which channels were used and how much liquidity they have available,
1531 // so that future paths don't rely on the same liquidity.
1532 // 3. Proceed to the next step if:
1533 // - we hit the recommended target value;
1534 // - OR if we could not construct a new path. Any next attempt will fail too.
1535 // Otherwise, repeat step 2.
1536 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1537 // (not recommended value).
1538 // 5. If yes, proceed. If not, fail routing.
1539 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1540 // transferred up to the transfer target value.
1541 // 7. Reduce the value of the last path until we are sending only the target value.
1542 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1543 // them so that we're not sending two HTLCs along the same path.
1545 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1546 // distance from the payee
1548 // We are not a faithful Dijkstra's implementation because we can change values which impact
1549 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1550 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1551 // the value we are currently attempting to send over a path, we simply reduce the value being
1552 // sent along the path for any hops after that channel. This may imply that later fees (which
1553 // we've already tabulated) are lower because a smaller value is passing through the channels
1554 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1555 // channels which were selected earlier (and which may still be used for other paths without a
1556 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1559 // One potentially problematic case for this algorithm would be if there are many
1560 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1561 // graph walking), we may never find a path which is not liquidity-limited and has lower
1562 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1563 // Because we only consider paths with at least 5% of the total value being sent, the damage
1564 // from such a case should be limited, however this could be further reduced in the future by
1565 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1566 // limits for the purposes of fee calculation.
1568 // Alternatively, we could store more detailed path information in the heap (targets, below)
1569 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1570 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1571 // and practically (as we would need to store dynamically-allocated path information in heap
1572 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1573 // results of such an algorithm would likely be biased towards lower-value paths.
1575 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1576 // outside of our current search value, running a path search more times to gather candidate
1577 // paths at different values. While this may be acceptable, further path searches may increase
1578 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1579 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1580 // the same time, remaining generic across different payment values.
1582 let network_channels = network_graph.channels();
1583 let network_nodes = network_graph.nodes();
1585 if payment_params.max_path_count == 0 {
1586 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1589 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1590 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1592 let allow_mpp = if payment_params.max_path_count == 1 {
1594 } else if payment_params.payee.supports_basic_mpp() {
1596 } else if let Some(payee) = payee_node_id_opt {
1597 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1598 |info| info.features.supports_basic_mpp()))
1601 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1602 LoggedPayeePubkey(payment_params.payee.node_id()), if allow_mpp { "with" } else { "without" },
1603 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1606 // Prepare the data we'll use for payee-to-payer search by
1607 // inserting first hops suggested by the caller as targets.
1608 // Our search will then attempt to reach them while traversing from the payee node.
1609 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1610 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1611 if let Some(hops) = first_hops {
1613 if chan.get_outbound_payment_scid().is_none() {
1614 panic!("first_hops should be filled in with usable channels, not pending ones");
1616 if chan.counterparty.node_id == *our_node_pubkey {
1617 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1620 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1621 .or_insert(Vec::new())
1624 if first_hop_targets.is_empty() {
1625 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1629 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1630 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1631 // adding duplicate entries when we find a better path to a given node.
1632 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1634 // Map from node_id to information about the best current path to that node, including feerate
1636 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1638 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1639 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1640 // htlc_minimum with extra fees while still finding a cheaper path.
1641 let mut hit_minimum_limit;
1643 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1644 // We start with a path_value of the exact amount we want, and if that generates a route we may
1645 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1646 // amount we want in total across paths, selecting the best subset at the end.
1647 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1648 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1649 let mut path_value_msat = final_value_msat;
1651 // Routing Fragmentation Mitigation heuristic:
1653 // Routing fragmentation across many payment paths increases the overall routing
1654 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1655 // Taking too many smaller paths also increases the chance of payment failure.
1656 // Thus to avoid this effect, we require from our collected links to provide
1657 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1658 // This requirement is currently set to be 1/max_path_count of the payment
1659 // value to ensure we only ever return routes that do not violate this limit.
1660 let minimal_value_contribution_msat: u64 = if allow_mpp {
1661 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1666 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1667 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1668 // drop the requirement by setting this to 0.
1669 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1671 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1672 // determine if the channel can be used by additional MPP paths or to inform path finding
1673 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1674 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1676 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1677 HashMap::with_capacity(network_nodes.len());
1679 // Keeping track of how much value we already collected across other paths. Helps to decide
1680 // when we want to stop looking for new paths.
1681 let mut already_collected_value_msat = 0;
1683 for (_, channels) in first_hop_targets.iter_mut() {
1684 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1688 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1689 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1691 // Remember how many candidates we ignored to allow for some logging afterwards.
1692 let mut num_ignored_value_contribution = 0;
1693 let mut num_ignored_path_length_limit = 0;
1694 let mut num_ignored_cltv_delta_limit = 0;
1695 let mut num_ignored_previously_failed = 0;
1697 macro_rules! add_entry {
1698 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1699 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1700 // since that value has to be transferred over this channel.
1701 // Returns whether this channel caused an update to `targets`.
1702 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1703 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1704 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1705 // We "return" whether we updated the path at the end, and how much we can route via
1706 // this channel, via this:
1707 let mut did_add_update_path_to_src_node = None;
1708 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1709 // practice these cases should be caught earlier:
1710 // - for regular channels at channel announcement (TODO)
1711 // - for first and last hops early in get_route
1712 if $src_node_id != $dest_node_id {
1713 let scid_opt = $candidate.short_channel_id();
1714 let effective_capacity = $candidate.effective_capacity();
1715 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1717 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1718 // It may be misleading because we might later choose to reduce the value transferred
1719 // over these channels, and the channel which was insufficient might become sufficient.
1720 // Worst case: we drop a good channel here because it can't cover the high following
1721 // fees caused by one expensive channel, but then this channel could have been used
1722 // if the amount being transferred over this path is lower.
1723 // We do this for now, but this is a subject for removal.
1724 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1725 let used_liquidity_msat = used_liquidities
1726 .get(&$candidate.id($src_node_id < $dest_node_id))
1727 .map_or(0, |used_liquidity_msat| {
1728 available_value_contribution_msat = available_value_contribution_msat
1729 .saturating_sub(*used_liquidity_msat);
1730 *used_liquidity_msat
1733 // Verify the liquidity offered by this channel complies to the minimal contribution.
1734 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1735 // Do not consider candidate hops that would exceed the maximum path length.
1736 let path_length_to_node = $next_hops_path_length + 1;
1737 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1739 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1740 // In order to already account for some of the privacy enhancing random CLTV
1741 // expiry delta offset we add on top later, we subtract a rough estimate
1742 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1743 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1744 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1745 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1746 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1747 .saturating_add($candidate.cltv_expiry_delta());
1748 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1750 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1751 // Includes paying fees for the use of the following channels.
1752 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1753 Some(result) => result,
1754 // Can't overflow due to how the values were computed right above.
1755 None => unreachable!(),
1757 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1758 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1759 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1761 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1762 let may_overpay_to_meet_path_minimum_msat =
1763 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1764 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1765 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1766 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1768 let payment_failed_on_this_channel = scid_opt.map_or(false,
1769 |scid| payment_params.previously_failed_channels.contains(&scid));
1771 let should_log_candidate = match $candidate {
1772 CandidateRouteHop::FirstHop { .. } => true,
1773 CandidateRouteHop::PrivateHop { .. } => true,
1774 CandidateRouteHop::Blinded { .. } => true,
1778 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1779 // bother considering this channel. If retrying with recommended_value_msat may
1780 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1781 // around again with a higher amount.
1782 if !contributes_sufficient_value {
1783 if should_log_candidate {
1784 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
1786 num_ignored_value_contribution += 1;
1787 } else if exceeds_max_path_length {
1788 if should_log_candidate {
1789 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
1791 num_ignored_path_length_limit += 1;
1792 } else if exceeds_cltv_delta_limit {
1793 if should_log_candidate {
1794 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
1796 num_ignored_cltv_delta_limit += 1;
1797 } else if payment_failed_on_this_channel {
1798 if should_log_candidate {
1799 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
1801 num_ignored_previously_failed += 1;
1802 } else if may_overpay_to_meet_path_minimum_msat {
1803 hit_minimum_limit = true;
1804 } else if over_path_minimum_msat {
1805 // Note that low contribution here (limited by available_liquidity_msat)
1806 // might violate htlc_minimum_msat on the hops which are next along the
1807 // payment path (upstream to the payee). To avoid that, we recompute
1808 // path fees knowing the final path contribution after constructing it.
1809 let path_htlc_minimum_msat = cmp::max(
1810 compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1811 .saturating_add($next_hops_path_htlc_minimum_msat),
1812 $candidate.htlc_minimum_msat());
1813 let hm_entry = dist.entry($src_node_id);
1814 let old_entry = hm_entry.or_insert_with(|| {
1815 // If there was previously no known way to access the source node
1816 // (recall it goes payee-to-payer) of short_channel_id, first add a
1817 // semi-dummy record just to compute the fees to reach the source node.
1818 // This will affect our decision on selecting short_channel_id
1819 // as a way to reach the $dest_node_id.
1821 node_id: $dest_node_id.clone(),
1822 candidate: $candidate.clone(),
1824 next_hops_fee_msat: u64::max_value(),
1825 hop_use_fee_msat: u64::max_value(),
1826 total_fee_msat: u64::max_value(),
1827 path_htlc_minimum_msat,
1828 path_penalty_msat: u64::max_value(),
1829 was_processed: false,
1830 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1831 value_contribution_msat,
1835 #[allow(unused_mut)] // We only use the mut in cfg(test)
1836 let mut should_process = !old_entry.was_processed;
1837 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1839 // In test/fuzzing builds, we do extra checks to make sure the skipping
1840 // of already-seen nodes only happens in cases we expect (see below).
1841 if !should_process { should_process = true; }
1845 let mut hop_use_fee_msat = 0;
1846 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1848 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1849 // will have the same effective-fee
1850 if $src_node_id != our_node_id {
1851 // Note that `u64::max_value` means we'll always fail the
1852 // `old_entry.total_fee_msat > total_fee_msat` check below
1853 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1854 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1857 let channel_usage = ChannelUsage {
1858 amount_msat: amount_to_transfer_over_msat,
1859 inflight_htlc_msat: used_liquidity_msat,
1862 let channel_penalty_msat = scid_opt.map_or(0,
1863 |scid| scorer.channel_penalty_msat(scid, &$src_node_id, &$dest_node_id,
1864 channel_usage, score_params));
1865 let path_penalty_msat = $next_hops_path_penalty_msat
1866 .saturating_add(channel_penalty_msat);
1867 let new_graph_node = RouteGraphNode {
1868 node_id: $src_node_id,
1869 lowest_fee_to_node: total_fee_msat,
1870 total_cltv_delta: hop_total_cltv_delta,
1871 value_contribution_msat,
1872 path_htlc_minimum_msat,
1874 path_length_to_node,
1877 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1878 // if this way is cheaper than the already known
1879 // (considering the cost to "reach" this channel from the route destination,
1880 // the cost of using this channel,
1881 // and the cost of routing to the source node of this channel).
1882 // Also, consider that htlc_minimum_msat_difference, because we might end up
1883 // paying it. Consider the following exploit:
1884 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1885 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1886 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1887 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1889 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1890 // but it may require additional tracking - we don't want to double-count
1891 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1892 // can't use something that may decrease on future hops.
1893 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1894 .saturating_add(old_entry.path_penalty_msat);
1895 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1896 .saturating_add(path_penalty_msat);
1898 if !old_entry.was_processed && new_cost < old_cost {
1899 targets.push(new_graph_node);
1900 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1901 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1902 old_entry.total_fee_msat = total_fee_msat;
1903 old_entry.node_id = $dest_node_id.clone();
1904 old_entry.candidate = $candidate.clone();
1905 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1906 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1907 old_entry.path_penalty_msat = path_penalty_msat;
1908 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1910 old_entry.value_contribution_msat = value_contribution_msat;
1912 did_add_update_path_to_src_node = Some(value_contribution_msat);
1913 } else if old_entry.was_processed && new_cost < old_cost {
1914 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1916 // If we're skipping processing a node which was previously
1917 // processed even though we found another path to it with a
1918 // cheaper fee, check that it was because the second path we
1919 // found (which we are processing now) has a lower value
1920 // contribution due to an HTLC minimum limit.
1922 // e.g. take a graph with two paths from node 1 to node 2, one
1923 // through channel A, and one through channel B. Channel A and
1924 // B are both in the to-process heap, with their scores set by
1925 // a higher htlc_minimum than fee.
1926 // Channel A is processed first, and the channels onwards from
1927 // node 1 are added to the to-process heap. Thereafter, we pop
1928 // Channel B off of the heap, note that it has a much more
1929 // restrictive htlc_maximum_msat, and recalculate the fees for
1930 // all of node 1's channels using the new, reduced, amount.
1932 // This would be bogus - we'd be selecting a higher-fee path
1933 // with a lower htlc_maximum_msat instead of the one we'd
1934 // already decided to use.
1935 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1937 value_contribution_msat + path_penalty_msat <
1938 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1946 did_add_update_path_to_src_node
1950 let default_node_features = default_node_features();
1952 // Find ways (channels with destination) to reach a given node and store them
1953 // in the corresponding data structures (routing graph etc).
1954 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1955 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1956 // This data can later be helpful to optimize routing (pay lower fees).
1957 macro_rules! add_entries_to_cheapest_to_target_node {
1958 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1959 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1960 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1961 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1962 let was_processed = elem.was_processed;
1963 elem.was_processed = true;
1966 // Entries are added to dist in add_entry!() when there is a channel from a node.
1967 // Because there are no channels from payee, it will not have a dist entry at this point.
1968 // If we're processing any other node, it is always be the result of a channel from it.
1969 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
1974 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1975 for details in first_channels {
1976 let candidate = CandidateRouteHop::FirstHop { details };
1977 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1978 $next_hops_value_contribution,
1979 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1980 $next_hops_cltv_delta, $next_hops_path_length);
1984 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1987 &default_node_features
1990 if !features.requires_unknown_bits() {
1991 for chan_id in $node.channels.iter() {
1992 let chan = network_channels.get(chan_id).unwrap();
1993 if !chan.features.requires_unknown_bits() {
1994 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1995 if first_hops.is_none() || *source != our_node_id {
1996 if directed_channel.direction().enabled {
1997 let candidate = CandidateRouteHop::PublicHop {
1998 info: directed_channel,
1999 short_channel_id: *chan_id,
2001 add_entry!(candidate, *source, $node_id,
2002 $fee_to_target_msat,
2003 $next_hops_value_contribution,
2004 $next_hops_path_htlc_minimum_msat,
2005 $next_hops_path_penalty_msat,
2006 $next_hops_cltv_delta, $next_hops_path_length);
2017 let mut payment_paths = Vec::<PaymentPath>::new();
2019 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2020 'paths_collection: loop {
2021 // For every new path, start from scratch, except for used_liquidities, which
2022 // helps to avoid reusing previously selected paths in future iterations.
2025 hit_minimum_limit = false;
2027 // If first hop is a private channel and the only way to reach the payee, this is the only
2028 // place where it could be added.
2029 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2030 for details in first_channels {
2031 let candidate = CandidateRouteHop::FirstHop { details };
2032 let added = add_entry!(candidate, our_node_id, payee, 0, path_value_msat,
2033 0, 0u64, 0, 0).is_some();
2034 log_trace!(logger, "{} direct route to payee via {}",
2035 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2039 // Add the payee as a target, so that the payee-to-payer
2040 // search algorithm knows what to start with.
2041 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2042 // The payee is not in our network graph, so nothing to add here.
2043 // There is still a chance of reaching them via last_hops though,
2044 // so don't yet fail the payment here.
2045 // If not, targets.pop() will not even let us enter the loop in step 2.
2048 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
2053 // If a caller provided us with last hops, add them to routing targets. Since this happens
2054 // earlier than general path finding, they will be somewhat prioritized, although currently
2055 // it matters only if the fees are exactly the same.
2056 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2057 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2058 let have_intro_node_in_graph =
2059 // Only add the hops in this route to our candidate set if either
2060 // we have a direct channel to the first hop or the first hop is
2061 // in the regular network graph.
2062 first_hop_targets.get(&intro_node_id).is_some() ||
2063 network_nodes.get(&intro_node_id).is_some();
2064 if !have_intro_node_in_graph { continue }
2065 let candidate = if hint.1.blinded_hops.len() == 1 {
2066 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
2067 } else { CandidateRouteHop::Blinded { hint, hint_idx } };
2068 let mut path_contribution_msat = path_value_msat;
2069 if let Some(hop_used_msat) = add_entry!(candidate, intro_node_id, maybe_dummy_payee_node_id,
2070 0, path_contribution_msat, 0, 0_u64, 0, 0)
2072 path_contribution_msat = hop_used_msat;
2074 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2075 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2077 for details in first_channels {
2078 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2079 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2083 add_entry!(first_hop_candidate, our_node_id, intro_node_id, blinded_path_fee,
2084 path_contribution_msat, candidate.htlc_minimum_msat(), 0_u64,
2085 candidate.cltv_expiry_delta(),
2086 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2090 for route in payment_params.payee.unblinded_route_hints().iter()
2091 .filter(|route| !route.0.is_empty())
2093 let first_hop_in_route = &(route.0)[0];
2094 let have_hop_src_in_graph =
2095 // Only add the hops in this route to our candidate set if either
2096 // we have a direct channel to the first hop or the first hop is
2097 // in the regular network graph.
2098 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
2099 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
2100 if have_hop_src_in_graph {
2101 // We start building the path from reverse, i.e., from payee
2102 // to the first RouteHintHop in the path.
2103 let hop_iter = route.0.iter().rev();
2104 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2105 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2106 let mut hop_used = true;
2107 let mut aggregate_next_hops_fee_msat: u64 = 0;
2108 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2109 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2110 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2111 let mut aggregate_next_hops_path_length: u8 = 0;
2112 let mut aggregate_path_contribution_msat = path_value_msat;
2114 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2115 let source = NodeId::from_pubkey(&hop.src_node_id);
2116 let target = NodeId::from_pubkey(&prev_hop_id);
2117 let candidate = network_channels
2118 .get(&hop.short_channel_id)
2119 .and_then(|channel| channel.as_directed_to(&target))
2120 .map(|(info, _)| CandidateRouteHop::PublicHop {
2122 short_channel_id: hop.short_channel_id,
2124 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
2126 if let Some(hop_used_msat) = add_entry!(candidate, source, target,
2127 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2128 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2129 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2131 aggregate_path_contribution_msat = hop_used_msat;
2133 // If this hop was not used then there is no use checking the preceding
2134 // hops in the RouteHint. We can break by just searching for a direct
2135 // channel between last checked hop and first_hop_targets.
2139 let used_liquidity_msat = used_liquidities
2140 .get(&candidate.id(source < target)).copied()
2142 let channel_usage = ChannelUsage {
2143 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2144 inflight_htlc_msat: used_liquidity_msat,
2145 effective_capacity: candidate.effective_capacity(),
2147 let channel_penalty_msat = scorer.channel_penalty_msat(
2148 hop.short_channel_id, &source, &target, channel_usage, score_params
2150 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2151 .saturating_add(channel_penalty_msat);
2153 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2154 .saturating_add(hop.cltv_expiry_delta as u32);
2156 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2159 // Searching for a direct channel between last checked hop and first_hop_targets
2160 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&prev_hop_id)) {
2161 sort_first_hop_channels(first_channels, &used_liquidities,
2162 recommended_value_msat, our_node_pubkey);
2163 for details in first_channels {
2164 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2165 add_entry!(first_hop_candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
2166 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2167 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2168 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2176 // In the next values of the iterator, the aggregate fees already reflects
2177 // the sum of value sent from payer (final_value_msat) and routing fees
2178 // for the last node in the RouteHint. We need to just add the fees to
2179 // route through the current node so that the preceding node (next iteration)
2181 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2182 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2183 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2185 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
2186 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
2187 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
2188 .checked_add(hop_htlc_minimum_msat_inc);
2189 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
2191 if idx == route.0.len() - 1 {
2192 // The last hop in this iterator is the first hop in
2193 // overall RouteHint.
2194 // If this hop connects to a node with which we have a direct channel,
2195 // ignore the network graph and, if the last hop was added, add our
2196 // direct channel to the candidate set.
2198 // Note that we *must* check if the last hop was added as `add_entry`
2199 // always assumes that the third argument is a node to which we have a
2201 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2202 sort_first_hop_channels(first_channels, &used_liquidities,
2203 recommended_value_msat, our_node_pubkey);
2204 for details in first_channels {
2205 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2206 add_entry!(first_hop_candidate, our_node_id,
2207 NodeId::from_pubkey(&hop.src_node_id),
2208 aggregate_next_hops_fee_msat,
2209 aggregate_path_contribution_msat,
2210 aggregate_next_hops_path_htlc_minimum_msat,
2211 aggregate_next_hops_path_penalty_msat,
2212 aggregate_next_hops_cltv_delta,
2213 aggregate_next_hops_path_length);
2221 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2223 // At this point, targets are filled with the data from first and
2224 // last hops communicated by the caller, and the payment receiver.
2225 let mut found_new_path = false;
2228 // If this loop terminates due the exhaustion of targets, two situations are possible:
2229 // - not enough outgoing liquidity:
2230 // 0 < already_collected_value_msat < final_value_msat
2231 // - enough outgoing liquidity:
2232 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2233 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2234 // paths_collection will be stopped because found_new_path==false.
2235 // This is not necessarily a routing failure.
2236 '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() {
2238 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2239 // traversing the graph and arrange the path out of what we found.
2240 if node_id == our_node_id {
2241 let mut new_entry = dist.remove(&our_node_id).unwrap();
2242 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2245 let mut features_set = false;
2246 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
2247 for details in first_channels {
2248 if let Some(scid) = ordered_hops.last().unwrap().0.candidate.short_channel_id() {
2249 if details.get_outbound_payment_scid().unwrap() == scid {
2250 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2251 features_set = true;
2258 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
2259 if let Some(node_info) = node.announcement_info.as_ref() {
2260 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2262 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2265 // We can fill in features for everything except hops which were
2266 // provided via the invoice we're paying. We could guess based on the
2267 // recipient's features but for now we simply avoid guessing at all.
2271 // Means we succesfully traversed from the payer to the payee, now
2272 // save this path for the payment route. Also, update the liquidity
2273 // remaining on the used hops, so that we take them into account
2274 // while looking for more paths.
2275 if ordered_hops.last().unwrap().0.node_id == maybe_dummy_payee_node_id {
2279 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
2280 Some(payment_hop) => payment_hop,
2281 // We can't arrive at None because, if we ever add an entry to targets,
2282 // we also fill in the entry in dist (see add_entry!).
2283 None => unreachable!(),
2285 // We "propagate" the fees one hop backward (topologically) here,
2286 // so that fees paid for a HTLC forwarding on the current channel are
2287 // associated with the previous channel (where they will be subtracted).
2288 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2289 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2291 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2292 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2294 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2295 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2297 let mut payment_path = PaymentPath {hops: ordered_hops};
2299 // We could have possibly constructed a slightly inconsistent path: since we reduce
2300 // value being transferred along the way, we could have violated htlc_minimum_msat
2301 // on some channels we already passed (assuming dest->source direction). Here, we
2302 // recompute the fees again, so that if that's the case, we match the currently
2303 // underpaid htlc_minimum_msat with fees.
2304 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2305 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
2306 payment_path.update_value_and_recompute_fees(value_contribution_msat);
2308 // Since a path allows to transfer as much value as
2309 // the smallest channel it has ("bottleneck"), we should recompute
2310 // the fees so sender HTLC don't overpay fees when traversing
2311 // larger channels than the bottleneck. This may happen because
2312 // when we were selecting those channels we were not aware how much value
2313 // this path will transfer, and the relative fee for them
2314 // might have been computed considering a larger value.
2315 // Remember that we used these channels so that we don't rely
2316 // on the same liquidity in future paths.
2317 let mut prevented_redundant_path_selection = false;
2318 let prev_hop_iter = core::iter::once(&our_node_id)
2319 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
2320 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
2321 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2322 let used_liquidity_msat = used_liquidities
2323 .entry(hop.candidate.id(*prev_hop < hop.node_id))
2324 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2325 .or_insert(spent_on_hop_msat);
2326 let hop_capacity = hop.candidate.effective_capacity();
2327 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2328 if *used_liquidity_msat == hop_max_msat {
2329 // If this path used all of this channel's available liquidity, we know
2330 // this path will not be selected again in the next loop iteration.
2331 prevented_redundant_path_selection = true;
2333 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2335 if !prevented_redundant_path_selection {
2336 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2337 // we'll probably end up picking the same path again on the next iteration.
2338 // Decrease the available liquidity of a hop in the middle of the path.
2339 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2340 let exhausted = u64::max_value();
2341 log_trace!(logger, "Disabling route candidate {} for future path building iterations to
2342 avoid duplicates.", LoggedCandidateHop(victim_candidate));
2343 *used_liquidities.entry(victim_candidate.id(false)).or_default() = exhausted;
2344 *used_liquidities.entry(victim_candidate.id(true)).or_default() = exhausted;
2347 // Track the total amount all our collected paths allow to send so that we know
2348 // when to stop looking for more paths
2349 already_collected_value_msat += value_contribution_msat;
2351 payment_paths.push(payment_path);
2352 found_new_path = true;
2353 break 'path_construction;
2356 // If we found a path back to the payee, we shouldn't try to process it again. This is
2357 // the equivalent of the `elem.was_processed` check in
2358 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2359 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2361 // Otherwise, since the current target node is not us,
2362 // keep "unrolling" the payment graph from payee to payer by
2363 // finding a way to reach the current target from the payer side.
2364 match network_nodes.get(&node_id) {
2367 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2368 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2369 total_cltv_delta, path_length_to_node);
2375 if !found_new_path && channel_saturation_pow_half != 0 {
2376 channel_saturation_pow_half = 0;
2377 continue 'paths_collection;
2379 // If we don't support MPP, no use trying to gather more value ever.
2380 break 'paths_collection;
2384 // Stop either when the recommended value is reached or if no new path was found in this
2386 // In the latter case, making another path finding attempt won't help,
2387 // because we deterministically terminated the search due to low liquidity.
2388 if !found_new_path && channel_saturation_pow_half != 0 {
2389 channel_saturation_pow_half = 0;
2390 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2391 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2392 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2393 break 'paths_collection;
2394 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2395 // Further, if this was our first walk of the graph, and we weren't limited by an
2396 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2397 // limited by an htlc_minimum_msat value, find another path with a higher value,
2398 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2399 // still keeping a lower total fee than this path.
2400 if !hit_minimum_limit {
2401 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2402 break 'paths_collection;
2404 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
2405 path_value_msat = recommended_value_msat;
2409 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2410 num_ignored_cltv_delta_limit + num_ignored_previously_failed;
2411 if num_ignored_total > 0 {
2412 log_trace!(logger, "Ignored {} candidate hops due to insufficient value contribution, {} due to path length limit, {} due to CLTV delta limit, {} due to previous payment failure. Total: {} ignored candidates.", num_ignored_value_contribution, num_ignored_path_length_limit, num_ignored_cltv_delta_limit, num_ignored_previously_failed, num_ignored_total);
2416 if payment_paths.len() == 0 {
2417 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2420 if already_collected_value_msat < final_value_msat {
2421 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2425 let mut selected_route = payment_paths;
2427 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2428 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2430 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2431 // the value they contribute towards the payment amount.
2432 // We sort in descending order as we will remove from the front in `retain`, next.
2433 selected_route.sort_unstable_by(|a, b|
2434 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2435 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2438 // We should make sure that at least 1 path left.
2439 let mut paths_left = selected_route.len();
2440 selected_route.retain(|path| {
2441 if paths_left == 1 {
2444 let path_value_msat = path.get_value_msat();
2445 if path_value_msat <= overpaid_value_msat {
2446 overpaid_value_msat -= path_value_msat;
2452 debug_assert!(selected_route.len() > 0);
2454 if overpaid_value_msat != 0 {
2456 // Now, subtract the remaining overpaid value from the most-expensive path.
2457 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2458 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2459 selected_route.sort_unstable_by(|a, b| {
2460 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2461 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2462 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2464 let expensive_payment_path = selected_route.first_mut().unwrap();
2466 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2467 // can't go negative.
2468 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2469 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2473 // Sort by the path itself and combine redundant paths.
2474 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2475 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2477 selected_route.sort_unstable_by_key(|path| {
2478 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2479 debug_assert!(path.hops.len() <= key.len());
2480 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id(true)).zip(key.iter_mut()) {
2485 for idx in 0..(selected_route.len() - 1) {
2486 if idx + 1 >= selected_route.len() { break; }
2487 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id)),
2488 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id))) {
2489 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2490 selected_route[idx].update_value_and_recompute_fees(new_value);
2491 selected_route.remove(idx + 1);
2495 let mut paths = Vec::new();
2496 for payment_path in selected_route {
2497 let mut hops = Vec::with_capacity(payment_path.hops.len());
2498 let mut prev_hop_node_id = our_node_id;
2499 for (hop, node_features) in payment_path.hops.iter()
2500 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2502 let maybe_announced_channel = if let CandidateRouteHop::PublicHop { .. } = hop.candidate {
2503 // If we sourced the hop from the graph we're sure the target node is announced.
2505 } else if let CandidateRouteHop::FirstHop { details } = hop.candidate {
2506 // If this is a first hop we also know if it's announced.
2509 // If we sourced it any other way, we double-check the network graph to see if
2510 // there are announced channels between the endpoints. If so, the hop might be
2511 // referring to any of the announced channels, as its `short_channel_id` might be
2512 // an alias, in which case we don't take any chances here.
2513 network_graph.node(&hop.node_id).map_or(false, |hop_node|
2514 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
2515 .map_or(false, |c| c.as_directed_from(&prev_hop_node_id).is_some()))
2519 hops.push(RouteHop {
2520 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)})?,
2521 node_features: node_features.clone(),
2522 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2523 channel_features: hop.candidate.features(),
2524 fee_msat: hop.fee_msat,
2525 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2526 maybe_announced_channel,
2529 prev_hop_node_id = hop.node_id;
2531 let mut final_cltv_delta = final_cltv_expiry_delta;
2532 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2533 if let Some(blinded_path) = h.candidate.blinded_path() {
2534 final_cltv_delta = h.candidate.cltv_expiry_delta();
2536 hops: blinded_path.blinded_hops.clone(),
2537 blinding_point: blinded_path.blinding_point,
2538 excess_final_cltv_expiry_delta: 0,
2539 final_value_msat: h.fee_msat,
2543 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2544 // applicable for the previous hop.
2545 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2546 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2549 paths.push(Path { hops, blinded_tail });
2551 // Make sure we would never create a route with more paths than we allow.
2552 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2554 if let Some(node_features) = payment_params.payee.node_features() {
2555 for path in paths.iter_mut() {
2556 path.hops.last_mut().unwrap().node_features = node_features.clone();
2560 let route = Route { paths, route_params: Some(route_params.clone()) };
2561 log_info!(logger, "Got route: {}", log_route!(route));
2565 // When an adversarial intermediary node observes a payment, it may be able to infer its
2566 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2567 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2568 // payment path by adding a randomized 'shadow route' offset to the final hop.
2569 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2570 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2572 let network_channels = network_graph.channels();
2573 let network_nodes = network_graph.nodes();
2575 for path in route.paths.iter_mut() {
2576 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2578 // Remember the last three nodes of the random walk and avoid looping back on them.
2579 // Init with the last three nodes from the actual path, if possible.
2580 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2581 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2582 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2584 // Choose the last publicly known node as the starting point for the random walk.
2585 let mut cur_hop: Option<NodeId> = None;
2586 let mut path_nonce = [0u8; 12];
2587 if let Some(starting_hop) = path.hops.iter().rev()
2588 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2589 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2590 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2593 // Init PRNG with the path-dependant nonce, which is static for private paths.
2594 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2595 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2597 // Pick a random path length in [1 .. 3]
2598 prng.process_in_place(&mut random_path_bytes);
2599 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2601 for random_hop in 0..random_walk_length {
2602 // If we don't find a suitable offset in the public network graph, we default to
2603 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2604 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2606 if let Some(cur_node_id) = cur_hop {
2607 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2608 // Randomly choose the next unvisited hop.
2609 prng.process_in_place(&mut random_path_bytes);
2610 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2611 .checked_rem(cur_node.channels.len())
2612 .and_then(|index| cur_node.channels.get(index))
2613 .and_then(|id| network_channels.get(id)) {
2614 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2615 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2616 nodes_to_avoid[random_hop] = *next_id;
2617 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2618 cur_hop = Some(*next_id);
2625 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2626 .checked_add(random_hop_offset)
2627 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2630 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2631 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2632 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2634 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2635 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2636 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2637 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2638 max_path_offset = cmp::max(
2639 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2640 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2641 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2643 // Add 'shadow' CLTV offset to the final hop
2644 if let Some(tail) = path.blinded_tail.as_mut() {
2645 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2646 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2648 if let Some(last_hop) = path.hops.last_mut() {
2649 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2650 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2655 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2656 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2658 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2659 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2660 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2661 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2662 ) -> Result<Route, LightningError>
2663 where L::Target: Logger, GL::Target: Logger {
2664 let graph_lock = network_graph.read_only();
2665 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
2666 &graph_lock, logger, random_seed_bytes)?;
2667 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2671 fn build_route_from_hops_internal<L: Deref>(
2672 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2673 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
2674 ) -> Result<Route, LightningError> where L::Target: Logger {
2677 our_node_id: NodeId,
2678 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2681 impl ScoreLookUp for HopScorer {
2682 type ScoreParams = ();
2683 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2684 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2686 let mut cur_id = self.our_node_id;
2687 for i in 0..self.hop_ids.len() {
2688 if let Some(next_id) = self.hop_ids[i] {
2689 if cur_id == *source && next_id == *target {
2701 impl<'a> Writeable for HopScorer {
2703 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2708 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2709 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2712 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2713 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2714 for i in 0..hops.len() {
2715 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2718 let scorer = HopScorer { our_node_id, hop_ids };
2720 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &(), random_seed_bytes)
2725 use crate::blinded_path::{BlindedHop, BlindedPath};
2726 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2727 use crate::routing::utxo::UtxoResult;
2728 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2729 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2730 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters};
2731 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2732 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2733 use crate::chain::transaction::OutPoint;
2734 use crate::sign::EntropySource;
2735 use crate::ln::ChannelId;
2736 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2737 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2738 use crate::ln::channelmanager;
2739 use crate::offers::invoice::BlindedPayInfo;
2740 use crate::util::config::UserConfig;
2741 use crate::util::test_utils as ln_test_utils;
2742 use crate::util::chacha20::ChaCha20;
2743 use crate::util::ser::{Readable, Writeable};
2745 use crate::util::ser::Writer;
2747 use bitcoin::hashes::Hash;
2748 use bitcoin::network::constants::Network;
2749 use bitcoin::blockdata::constants::genesis_block;
2750 use bitcoin::blockdata::script::Builder;
2751 use bitcoin::blockdata::opcodes;
2752 use bitcoin::blockdata::transaction::TxOut;
2756 use bitcoin::secp256k1::{PublicKey,SecretKey};
2757 use bitcoin::secp256k1::Secp256k1;
2759 use crate::io::Cursor;
2760 use crate::prelude::*;
2761 use crate::sync::Arc;
2763 use core::convert::TryInto;
2765 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2766 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2767 channelmanager::ChannelDetails {
2768 channel_id: ChannelId::new_zero(),
2769 counterparty: channelmanager::ChannelCounterparty {
2772 unspendable_punishment_reserve: 0,
2773 forwarding_info: None,
2774 outbound_htlc_minimum_msat: None,
2775 outbound_htlc_maximum_msat: None,
2777 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2780 outbound_scid_alias: None,
2781 inbound_scid_alias: None,
2782 channel_value_satoshis: 0,
2784 outbound_capacity_msat,
2785 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2786 next_outbound_htlc_minimum_msat: 0,
2787 inbound_capacity_msat: 42,
2788 unspendable_punishment_reserve: None,
2789 confirmations_required: None,
2790 confirmations: None,
2791 force_close_spend_delay: None,
2792 is_outbound: true, is_channel_ready: true,
2793 is_usable: true, is_public: true,
2794 inbound_htlc_minimum_msat: None,
2795 inbound_htlc_maximum_msat: None,
2797 feerate_sat_per_1000_weight: None,
2798 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
2803 fn simple_route_test() {
2804 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2805 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2806 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2807 let scorer = ln_test_utils::TestScorer::new();
2808 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2809 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2811 // Simple route to 2 via 1
2813 let route_params = RouteParameters::from_payment_params_and_value(
2814 payment_params.clone(), 0);
2815 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2816 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer, &(),
2817 &random_seed_bytes) {
2818 assert_eq!(err, "Cannot send a payment of 0 msat");
2819 } else { panic!(); }
2821 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
2822 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2823 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2824 assert_eq!(route.paths[0].hops.len(), 2);
2826 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2827 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2828 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2829 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2830 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2831 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2833 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2834 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2835 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2836 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2837 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2838 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2842 fn invalid_first_hop_test() {
2843 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2844 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2845 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2846 let scorer = ln_test_utils::TestScorer::new();
2847 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2848 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2850 // Simple route to 2 via 1
2852 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2854 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
2855 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2856 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
2857 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2858 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2859 } else { panic!(); }
2861 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2862 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2863 assert_eq!(route.paths[0].hops.len(), 2);
2867 fn htlc_minimum_test() {
2868 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2869 let (our_privkey, our_id, privkeys, 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 // Disable other paths
2878 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2879 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2880 short_channel_id: 12,
2882 flags: 2, // to disable
2883 cltv_expiry_delta: 0,
2884 htlc_minimum_msat: 0,
2885 htlc_maximum_msat: MAX_VALUE_MSAT,
2887 fee_proportional_millionths: 0,
2888 excess_data: Vec::new()
2890 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2891 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2892 short_channel_id: 3,
2894 flags: 2, // to disable
2895 cltv_expiry_delta: 0,
2896 htlc_minimum_msat: 0,
2897 htlc_maximum_msat: MAX_VALUE_MSAT,
2899 fee_proportional_millionths: 0,
2900 excess_data: Vec::new()
2902 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2903 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2904 short_channel_id: 13,
2906 flags: 2, // to disable
2907 cltv_expiry_delta: 0,
2908 htlc_minimum_msat: 0,
2909 htlc_maximum_msat: MAX_VALUE_MSAT,
2911 fee_proportional_millionths: 0,
2912 excess_data: Vec::new()
2914 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2915 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2916 short_channel_id: 6,
2918 flags: 2, // to disable
2919 cltv_expiry_delta: 0,
2920 htlc_minimum_msat: 0,
2921 htlc_maximum_msat: MAX_VALUE_MSAT,
2923 fee_proportional_millionths: 0,
2924 excess_data: Vec::new()
2926 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2927 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2928 short_channel_id: 7,
2930 flags: 2, // to disable
2931 cltv_expiry_delta: 0,
2932 htlc_minimum_msat: 0,
2933 htlc_maximum_msat: MAX_VALUE_MSAT,
2935 fee_proportional_millionths: 0,
2936 excess_data: Vec::new()
2939 // Check against amount_to_transfer_over_msat.
2940 // Set minimal HTLC of 200_000_000 msat.
2941 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2942 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2943 short_channel_id: 2,
2946 cltv_expiry_delta: 0,
2947 htlc_minimum_msat: 200_000_000,
2948 htlc_maximum_msat: MAX_VALUE_MSAT,
2950 fee_proportional_millionths: 0,
2951 excess_data: Vec::new()
2954 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2956 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2957 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2958 short_channel_id: 4,
2961 cltv_expiry_delta: 0,
2962 htlc_minimum_msat: 0,
2963 htlc_maximum_msat: 199_999_999,
2965 fee_proportional_millionths: 0,
2966 excess_data: Vec::new()
2969 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2970 let route_params = RouteParameters::from_payment_params_and_value(
2971 payment_params, 199_999_999);
2972 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2973 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer, &(),
2974 &random_seed_bytes) {
2975 assert_eq!(err, "Failed to find a path to the given destination");
2976 } else { panic!(); }
2978 // Lift the restriction on the first hop.
2979 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2980 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2981 short_channel_id: 2,
2984 cltv_expiry_delta: 0,
2985 htlc_minimum_msat: 0,
2986 htlc_maximum_msat: MAX_VALUE_MSAT,
2988 fee_proportional_millionths: 0,
2989 excess_data: Vec::new()
2992 // A payment above the minimum should pass
2993 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2994 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2995 assert_eq!(route.paths[0].hops.len(), 2);
2999 fn htlc_minimum_overpay_test() {
3000 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3001 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3002 let config = UserConfig::default();
3003 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3004 let scorer = ln_test_utils::TestScorer::new();
3005 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3006 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3008 // A route to node#2 via two paths.
3009 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3010 // Thus, they can't send 60 without overpaying.
3011 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3012 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3013 short_channel_id: 2,
3016 cltv_expiry_delta: 0,
3017 htlc_minimum_msat: 35_000,
3018 htlc_maximum_msat: 40_000,
3020 fee_proportional_millionths: 0,
3021 excess_data: Vec::new()
3023 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3024 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3025 short_channel_id: 12,
3028 cltv_expiry_delta: 0,
3029 htlc_minimum_msat: 35_000,
3030 htlc_maximum_msat: 40_000,
3032 fee_proportional_millionths: 0,
3033 excess_data: Vec::new()
3037 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3038 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3039 short_channel_id: 13,
3042 cltv_expiry_delta: 0,
3043 htlc_minimum_msat: 0,
3044 htlc_maximum_msat: MAX_VALUE_MSAT,
3046 fee_proportional_millionths: 0,
3047 excess_data: Vec::new()
3049 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3050 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3051 short_channel_id: 4,
3054 cltv_expiry_delta: 0,
3055 htlc_minimum_msat: 0,
3056 htlc_maximum_msat: MAX_VALUE_MSAT,
3058 fee_proportional_millionths: 0,
3059 excess_data: Vec::new()
3062 // Disable other paths
3063 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3064 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3065 short_channel_id: 1,
3067 flags: 2, // to disable
3068 cltv_expiry_delta: 0,
3069 htlc_minimum_msat: 0,
3070 htlc_maximum_msat: MAX_VALUE_MSAT,
3072 fee_proportional_millionths: 0,
3073 excess_data: Vec::new()
3076 let route_params = RouteParameters::from_payment_params_and_value(
3077 payment_params.clone(), 60_000);
3078 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3079 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3080 // Overpay fees to hit htlc_minimum_msat.
3081 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3082 // TODO: this could be better balanced to overpay 10k and not 15k.
3083 assert_eq!(overpaid_fees, 15_000);
3085 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3086 // while taking even more fee to match htlc_minimum_msat.
3087 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3088 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3089 short_channel_id: 12,
3092 cltv_expiry_delta: 0,
3093 htlc_minimum_msat: 65_000,
3094 htlc_maximum_msat: 80_000,
3096 fee_proportional_millionths: 0,
3097 excess_data: Vec::new()
3099 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3100 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3101 short_channel_id: 2,
3104 cltv_expiry_delta: 0,
3105 htlc_minimum_msat: 0,
3106 htlc_maximum_msat: MAX_VALUE_MSAT,
3108 fee_proportional_millionths: 0,
3109 excess_data: Vec::new()
3111 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3112 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3113 short_channel_id: 4,
3116 cltv_expiry_delta: 0,
3117 htlc_minimum_msat: 0,
3118 htlc_maximum_msat: MAX_VALUE_MSAT,
3120 fee_proportional_millionths: 100_000,
3121 excess_data: Vec::new()
3124 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3125 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3126 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3127 assert_eq!(route.paths.len(), 1);
3128 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3129 let fees = route.paths[0].hops[0].fee_msat;
3130 assert_eq!(fees, 5_000);
3132 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3133 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3134 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3135 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3136 // the other channel.
3137 assert_eq!(route.paths.len(), 1);
3138 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3139 let fees = route.paths[0].hops[0].fee_msat;
3140 assert_eq!(fees, 5_000);
3144 fn disable_channels_test() {
3145 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3146 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3147 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3148 let scorer = ln_test_utils::TestScorer::new();
3149 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3150 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3152 // // Disable channels 4 and 12 by flags=2
3153 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3154 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3155 short_channel_id: 4,
3157 flags: 2, // to disable
3158 cltv_expiry_delta: 0,
3159 htlc_minimum_msat: 0,
3160 htlc_maximum_msat: MAX_VALUE_MSAT,
3162 fee_proportional_millionths: 0,
3163 excess_data: Vec::new()
3165 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3166 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3167 short_channel_id: 12,
3169 flags: 2, // to disable
3170 cltv_expiry_delta: 0,
3171 htlc_minimum_msat: 0,
3172 htlc_maximum_msat: MAX_VALUE_MSAT,
3174 fee_proportional_millionths: 0,
3175 excess_data: Vec::new()
3178 // If all the channels require some features we don't understand, route should fail
3179 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3180 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3181 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer, &(),
3182 &random_seed_bytes) {
3183 assert_eq!(err, "Failed to find a path to the given destination");
3184 } else { panic!(); }
3186 // If we specify a channel to node7, that overrides our local channel view and that gets used
3187 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3188 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3189 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3190 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
3191 &random_seed_bytes).unwrap();
3192 assert_eq!(route.paths[0].hops.len(), 2);
3194 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3195 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3196 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3197 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3198 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3199 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3201 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3202 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3203 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3204 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3205 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3206 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3210 fn disable_node_test() {
3211 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3212 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3213 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3214 let scorer = ln_test_utils::TestScorer::new();
3215 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3216 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3218 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3219 let mut unknown_features = NodeFeatures::empty();
3220 unknown_features.set_unknown_feature_required();
3221 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3222 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3223 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3225 // If all nodes require some features we don't understand, route should fail
3226 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3227 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3228 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer, &(),
3229 &random_seed_bytes) {
3230 assert_eq!(err, "Failed to find a path to the given destination");
3231 } else { panic!(); }
3233 // If we specify a channel to node7, that overrides our local channel view and that gets used
3234 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3235 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3236 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3237 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
3238 &random_seed_bytes).unwrap();
3239 assert_eq!(route.paths[0].hops.len(), 2);
3241 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3242 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3243 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3244 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3245 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3246 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3248 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3249 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3250 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3251 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3252 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3253 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3255 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3256 // naively) assume that the user checked the feature bits on the invoice, which override
3257 // the node_announcement.
3261 fn our_chans_test() {
3262 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3263 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3264 let scorer = ln_test_utils::TestScorer::new();
3265 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3266 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3268 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3269 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3270 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3271 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3272 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3273 assert_eq!(route.paths[0].hops.len(), 3);
3275 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3276 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3277 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3278 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3279 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3280 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3282 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3283 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3284 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3285 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3286 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3287 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3289 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3290 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3291 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3292 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3293 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3294 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3296 // If we specify a channel to node7, that overrides our local channel view and that gets used
3297 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3298 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3299 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3300 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3301 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3302 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
3303 &random_seed_bytes).unwrap();
3304 assert_eq!(route.paths[0].hops.len(), 2);
3306 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3307 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3308 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3309 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3310 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3311 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3313 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3314 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3315 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3316 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3317 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3318 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3321 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3322 let zero_fees = RoutingFees {
3324 proportional_millionths: 0,
3326 vec![RouteHint(vec![RouteHintHop {
3327 src_node_id: nodes[3],
3328 short_channel_id: 8,
3330 cltv_expiry_delta: (8 << 4) | 1,
3331 htlc_minimum_msat: None,
3332 htlc_maximum_msat: None,
3334 ]), RouteHint(vec![RouteHintHop {
3335 src_node_id: nodes[4],
3336 short_channel_id: 9,
3339 proportional_millionths: 0,
3341 cltv_expiry_delta: (9 << 4) | 1,
3342 htlc_minimum_msat: None,
3343 htlc_maximum_msat: None,
3344 }]), RouteHint(vec![RouteHintHop {
3345 src_node_id: nodes[5],
3346 short_channel_id: 10,
3348 cltv_expiry_delta: (10 << 4) | 1,
3349 htlc_minimum_msat: None,
3350 htlc_maximum_msat: None,
3354 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3355 let zero_fees = RoutingFees {
3357 proportional_millionths: 0,
3359 vec![RouteHint(vec![RouteHintHop {
3360 src_node_id: nodes[2],
3361 short_channel_id: 5,
3364 proportional_millionths: 0,
3366 cltv_expiry_delta: (5 << 4) | 1,
3367 htlc_minimum_msat: None,
3368 htlc_maximum_msat: None,
3370 src_node_id: nodes[3],
3371 short_channel_id: 8,
3373 cltv_expiry_delta: (8 << 4) | 1,
3374 htlc_minimum_msat: None,
3375 htlc_maximum_msat: None,
3377 ]), RouteHint(vec![RouteHintHop {
3378 src_node_id: nodes[4],
3379 short_channel_id: 9,
3382 proportional_millionths: 0,
3384 cltv_expiry_delta: (9 << 4) | 1,
3385 htlc_minimum_msat: None,
3386 htlc_maximum_msat: None,
3387 }]), RouteHint(vec![RouteHintHop {
3388 src_node_id: nodes[5],
3389 short_channel_id: 10,
3391 cltv_expiry_delta: (10 << 4) | 1,
3392 htlc_minimum_msat: None,
3393 htlc_maximum_msat: None,
3398 fn partial_route_hint_test() {
3399 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3400 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3401 let scorer = ln_test_utils::TestScorer::new();
3402 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3403 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3405 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3406 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3407 // RouteHint may be partially used by the algo to build the best path.
3409 // First check that last hop can't have its source as the payee.
3410 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3411 src_node_id: nodes[6],
3412 short_channel_id: 8,
3415 proportional_millionths: 0,
3417 cltv_expiry_delta: (8 << 4) | 1,
3418 htlc_minimum_msat: None,
3419 htlc_maximum_msat: None,
3422 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3423 invalid_last_hops.push(invalid_last_hop);
3425 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3426 .with_route_hints(invalid_last_hops).unwrap();
3427 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3428 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3429 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer, &(),
3430 &random_seed_bytes) {
3431 assert_eq!(err, "Route hint cannot have the payee as the source.");
3432 } else { panic!(); }
3435 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3436 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3437 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3438 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3439 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3440 assert_eq!(route.paths[0].hops.len(), 5);
3442 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3443 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3444 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3445 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3446 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3447 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3449 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3450 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3451 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3452 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3453 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3454 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3456 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3457 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3458 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3459 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3460 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3461 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3463 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3464 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3465 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3466 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3467 // If we have a peer in the node map, we'll use their features here since we don't have
3468 // a way of figuring out their features from the invoice:
3469 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3470 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3472 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3473 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3474 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3475 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3476 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3477 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3480 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3481 let zero_fees = RoutingFees {
3483 proportional_millionths: 0,
3485 vec![RouteHint(vec![RouteHintHop {
3486 src_node_id: nodes[3],
3487 short_channel_id: 8,
3489 cltv_expiry_delta: (8 << 4) | 1,
3490 htlc_minimum_msat: None,
3491 htlc_maximum_msat: None,
3492 }]), RouteHint(vec![
3494 ]), RouteHint(vec![RouteHintHop {
3495 src_node_id: nodes[5],
3496 short_channel_id: 10,
3498 cltv_expiry_delta: (10 << 4) | 1,
3499 htlc_minimum_msat: None,
3500 htlc_maximum_msat: None,
3505 fn ignores_empty_last_hops_test() {
3506 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3507 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3508 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3509 let scorer = ln_test_utils::TestScorer::new();
3510 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3511 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3513 // Test handling of an empty RouteHint passed in Invoice.
3514 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3515 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3516 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3517 assert_eq!(route.paths[0].hops.len(), 5);
3519 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3520 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3521 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3522 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3523 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3524 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3526 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3527 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3528 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3529 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3530 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3531 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3533 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3534 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3535 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3536 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3537 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3538 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3540 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3541 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3542 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3543 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3544 // If we have a peer in the node map, we'll use their features here since we don't have
3545 // a way of figuring out their features from the invoice:
3546 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3547 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3549 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3550 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3551 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3552 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3553 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3554 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3557 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3559 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3560 let zero_fees = RoutingFees {
3562 proportional_millionths: 0,
3564 vec![RouteHint(vec![RouteHintHop {
3565 src_node_id: hint_hops[0],
3566 short_channel_id: 0xff00,
3569 proportional_millionths: 0,
3571 cltv_expiry_delta: (5 << 4) | 1,
3572 htlc_minimum_msat: None,
3573 htlc_maximum_msat: None,
3575 src_node_id: hint_hops[1],
3576 short_channel_id: 0xff01,
3578 cltv_expiry_delta: (8 << 4) | 1,
3579 htlc_minimum_msat: None,
3580 htlc_maximum_msat: None,
3585 fn multi_hint_last_hops_test() {
3586 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3587 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3588 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3589 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3590 let scorer = ln_test_utils::TestScorer::new();
3591 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3592 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3593 // Test through channels 2, 3, 0xff00, 0xff01.
3594 // Test shows that multiple hop hints are considered.
3596 // Disabling channels 6 & 7 by flags=2
3597 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3598 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3599 short_channel_id: 6,
3601 flags: 2, // to disable
3602 cltv_expiry_delta: 0,
3603 htlc_minimum_msat: 0,
3604 htlc_maximum_msat: MAX_VALUE_MSAT,
3606 fee_proportional_millionths: 0,
3607 excess_data: Vec::new()
3609 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3610 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3611 short_channel_id: 7,
3613 flags: 2, // to disable
3614 cltv_expiry_delta: 0,
3615 htlc_minimum_msat: 0,
3616 htlc_maximum_msat: MAX_VALUE_MSAT,
3618 fee_proportional_millionths: 0,
3619 excess_data: Vec::new()
3622 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3623 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3624 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3625 assert_eq!(route.paths[0].hops.len(), 4);
3627 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3628 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3629 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3630 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3631 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3632 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3634 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3635 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3636 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3637 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3638 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3639 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3641 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3642 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3643 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3644 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3645 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3646 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3648 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3649 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3650 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3651 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3652 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3653 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3657 fn private_multi_hint_last_hops_test() {
3658 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3659 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3661 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3662 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3664 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3665 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3666 let scorer = ln_test_utils::TestScorer::new();
3667 // Test through channels 2, 3, 0xff00, 0xff01.
3668 // Test shows that multiple hop hints are considered.
3670 // Disabling channels 6 & 7 by flags=2
3671 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3672 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3673 short_channel_id: 6,
3675 flags: 2, // to disable
3676 cltv_expiry_delta: 0,
3677 htlc_minimum_msat: 0,
3678 htlc_maximum_msat: MAX_VALUE_MSAT,
3680 fee_proportional_millionths: 0,
3681 excess_data: Vec::new()
3683 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3684 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3685 short_channel_id: 7,
3687 flags: 2, // to disable
3688 cltv_expiry_delta: 0,
3689 htlc_minimum_msat: 0,
3690 htlc_maximum_msat: MAX_VALUE_MSAT,
3692 fee_proportional_millionths: 0,
3693 excess_data: Vec::new()
3696 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3697 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3698 Arc::clone(&logger), &scorer, &(), &[42u8; 32]).unwrap();
3699 assert_eq!(route.paths[0].hops.len(), 4);
3701 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3702 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3703 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3704 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3705 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3706 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3708 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3709 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3710 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3711 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3712 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3713 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3715 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3716 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3717 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3718 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3719 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3720 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3722 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3723 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3724 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3725 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3726 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3727 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3730 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3731 let zero_fees = RoutingFees {
3733 proportional_millionths: 0,
3735 vec![RouteHint(vec![RouteHintHop {
3736 src_node_id: nodes[4],
3737 short_channel_id: 11,
3739 cltv_expiry_delta: (11 << 4) | 1,
3740 htlc_minimum_msat: None,
3741 htlc_maximum_msat: None,
3743 src_node_id: nodes[3],
3744 short_channel_id: 8,
3746 cltv_expiry_delta: (8 << 4) | 1,
3747 htlc_minimum_msat: None,
3748 htlc_maximum_msat: None,
3749 }]), RouteHint(vec![RouteHintHop {
3750 src_node_id: nodes[4],
3751 short_channel_id: 9,
3754 proportional_millionths: 0,
3756 cltv_expiry_delta: (9 << 4) | 1,
3757 htlc_minimum_msat: None,
3758 htlc_maximum_msat: None,
3759 }]), RouteHint(vec![RouteHintHop {
3760 src_node_id: nodes[5],
3761 short_channel_id: 10,
3763 cltv_expiry_delta: (10 << 4) | 1,
3764 htlc_minimum_msat: None,
3765 htlc_maximum_msat: None,
3770 fn last_hops_with_public_channel_test() {
3771 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3772 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3773 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
3774 let scorer = ln_test_utils::TestScorer::new();
3775 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3776 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3777 // This test shows that public routes can be present in the invoice
3778 // which would be handled in the same manner.
3780 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3781 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3782 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3783 assert_eq!(route.paths[0].hops.len(), 5);
3785 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3786 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3787 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3788 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3789 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3790 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3792 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3793 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3794 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3795 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3796 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3797 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3799 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3800 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3801 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3802 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3803 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3804 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3806 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3807 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3808 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3809 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3810 // If we have a peer in the node map, we'll use their features here since we don't have
3811 // a way of figuring out their features from the invoice:
3812 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3813 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3815 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3816 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3817 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3818 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3819 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3820 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3824 fn our_chans_last_hop_connect_test() {
3825 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3826 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3827 let scorer = ln_test_utils::TestScorer::new();
3828 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3829 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3831 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3832 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3833 let mut last_hops = last_hops(&nodes);
3834 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3835 .with_route_hints(last_hops.clone()).unwrap();
3836 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3837 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3838 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
3839 &random_seed_bytes).unwrap();
3840 assert_eq!(route.paths[0].hops.len(), 2);
3842 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3843 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3844 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3845 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3846 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3847 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3849 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3850 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3851 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3852 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3853 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3854 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3856 last_hops[0].0[0].fees.base_msat = 1000;
3858 // Revert to via 6 as the fee on 8 goes up
3859 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3860 .with_route_hints(last_hops).unwrap();
3861 let route_params = RouteParameters::from_payment_params_and_value(
3862 payment_params.clone(), 100);
3863 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3864 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3865 assert_eq!(route.paths[0].hops.len(), 4);
3867 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3868 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3869 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
3870 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3871 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3872 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3874 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3875 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3876 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3877 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
3878 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3879 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3881 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
3882 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3883 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3884 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3885 // If we have a peer in the node map, we'll use their features here since we don't have
3886 // a way of figuring out their features from the invoice:
3887 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3888 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3890 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3891 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3892 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3893 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3894 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3895 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3897 // ...but still use 8 for larger payments as 6 has a variable feerate
3898 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
3899 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3900 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3901 assert_eq!(route.paths[0].hops.len(), 5);
3903 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3904 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3905 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3906 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3907 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3908 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3910 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3911 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3912 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3913 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3914 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3915 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3917 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3918 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3919 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3920 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3921 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3922 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3924 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3925 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3926 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
3927 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3928 // If we have a peer in the node map, we'll use their features here since we don't have
3929 // a way of figuring out their features from the invoice:
3930 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3931 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3933 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3934 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3935 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
3936 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3937 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3938 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3941 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> {
3942 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3943 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3944 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3946 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3947 let last_hops = RouteHint(vec![RouteHintHop {
3948 src_node_id: middle_node_id,
3949 short_channel_id: 8,
3952 proportional_millionths: last_hop_fee_prop,
3954 cltv_expiry_delta: (8 << 4) | 1,
3955 htlc_minimum_msat: None,
3956 htlc_maximum_msat: last_hop_htlc_max,
3958 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
3959 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3960 let scorer = ln_test_utils::TestScorer::new();
3961 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3962 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3963 let logger = ln_test_utils::TestLogger::new();
3964 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3965 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
3966 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
3967 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &(),
3968 &random_seed_bytes);
3973 fn unannounced_path_test() {
3974 // We should be able to send a payment to a destination without any help of a routing graph
3975 // if we have a channel with a common counterparty that appears in the first and last hop
3977 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3979 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3980 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3981 assert_eq!(route.paths[0].hops.len(), 2);
3983 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
3984 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3985 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
3986 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3987 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
3988 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3990 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
3991 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3992 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
3993 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3994 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3995 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3999 fn overflow_unannounced_path_test_liquidity_underflow() {
4000 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4001 // the last-hop had a fee which overflowed a u64, we'd panic.
4002 // This was due to us adding the first-hop from us unconditionally, causing us to think
4003 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4004 // In this test, we previously hit a subtraction underflow due to having less available
4005 // liquidity at the last hop than 0.
4006 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());
4010 fn overflow_unannounced_path_test_feerate_overflow() {
4011 // This tests for the same case as above, except instead of hitting a subtraction
4012 // underflow, we hit a case where the fee charged at a hop overflowed.
4013 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());
4017 fn available_amount_while_routing_test() {
4018 // Tests whether we choose the correct available channel amount while routing.
4020 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4021 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4022 let scorer = ln_test_utils::TestScorer::new();
4023 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4024 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4025 let config = UserConfig::default();
4026 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4028 // We will use a simple single-path route from
4029 // our node to node2 via node0: channels {1, 3}.
4031 // First disable all other paths.
4032 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4033 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4034 short_channel_id: 2,
4037 cltv_expiry_delta: 0,
4038 htlc_minimum_msat: 0,
4039 htlc_maximum_msat: 100_000,
4041 fee_proportional_millionths: 0,
4042 excess_data: Vec::new()
4044 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4045 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4046 short_channel_id: 12,
4049 cltv_expiry_delta: 0,
4050 htlc_minimum_msat: 0,
4051 htlc_maximum_msat: 100_000,
4053 fee_proportional_millionths: 0,
4054 excess_data: Vec::new()
4057 // Make the first channel (#1) very permissive,
4058 // and we will be testing all limits on the second channel.
4059 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4060 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4061 short_channel_id: 1,
4064 cltv_expiry_delta: 0,
4065 htlc_minimum_msat: 0,
4066 htlc_maximum_msat: 1_000_000_000,
4068 fee_proportional_millionths: 0,
4069 excess_data: Vec::new()
4072 // First, let's see if routing works if we have absolutely no idea about the available amount.
4073 // In this case, it should be set to 250_000 sats.
4074 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4075 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4076 short_channel_id: 3,
4079 cltv_expiry_delta: 0,
4080 htlc_minimum_msat: 0,
4081 htlc_maximum_msat: 250_000_000,
4083 fee_proportional_millionths: 0,
4084 excess_data: Vec::new()
4088 // Attempt to route more than available results in a failure.
4089 let route_params = RouteParameters::from_payment_params_and_value(
4090 payment_params.clone(), 250_000_001);
4091 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4092 &our_id, &route_params, &network_graph.read_only(), None,
4093 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4094 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4095 } else { panic!(); }
4099 // Now, attempt to route an exact amount we have should be fine.
4100 let route_params = RouteParameters::from_payment_params_and_value(
4101 payment_params.clone(), 250_000_000);
4102 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4103 Arc::clone(&logger), &scorer, &(),&random_seed_bytes).unwrap();
4104 assert_eq!(route.paths.len(), 1);
4105 let path = route.paths.last().unwrap();
4106 assert_eq!(path.hops.len(), 2);
4107 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4108 assert_eq!(path.final_value_msat(), 250_000_000);
4111 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4112 // Disable channel #1 and use another first hop.
4113 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4114 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4115 short_channel_id: 1,
4118 cltv_expiry_delta: 0,
4119 htlc_minimum_msat: 0,
4120 htlc_maximum_msat: 1_000_000_000,
4122 fee_proportional_millionths: 0,
4123 excess_data: Vec::new()
4126 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4127 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4130 // Attempt to route more than available results in a failure.
4131 let route_params = RouteParameters::from_payment_params_and_value(
4132 payment_params.clone(), 200_000_001);
4133 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4134 &our_id, &route_params, &network_graph.read_only(),
4135 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4136 &(), &random_seed_bytes) {
4137 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4138 } else { panic!(); }
4142 // Now, attempt to route an exact amount we have should be fine.
4143 let route_params = RouteParameters::from_payment_params_and_value(
4144 payment_params.clone(), 200_000_000);
4145 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4146 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
4147 &random_seed_bytes).unwrap();
4148 assert_eq!(route.paths.len(), 1);
4149 let path = route.paths.last().unwrap();
4150 assert_eq!(path.hops.len(), 2);
4151 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4152 assert_eq!(path.final_value_msat(), 200_000_000);
4155 // Enable channel #1 back.
4156 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4157 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4158 short_channel_id: 1,
4161 cltv_expiry_delta: 0,
4162 htlc_minimum_msat: 0,
4163 htlc_maximum_msat: 1_000_000_000,
4165 fee_proportional_millionths: 0,
4166 excess_data: Vec::new()
4170 // Now let's see if routing works if we know only htlc_maximum_msat.
4171 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4172 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4173 short_channel_id: 3,
4176 cltv_expiry_delta: 0,
4177 htlc_minimum_msat: 0,
4178 htlc_maximum_msat: 15_000,
4180 fee_proportional_millionths: 0,
4181 excess_data: Vec::new()
4185 // Attempt to route more than available results in a failure.
4186 let route_params = RouteParameters::from_payment_params_and_value(
4187 payment_params.clone(), 15_001);
4188 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4189 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4190 &scorer, &(), &random_seed_bytes) {
4191 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4192 } else { panic!(); }
4196 // Now, attempt to route an exact amount we have should be fine.
4197 let route_params = RouteParameters::from_payment_params_and_value(
4198 payment_params.clone(), 15_000);
4199 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4200 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4201 assert_eq!(route.paths.len(), 1);
4202 let path = route.paths.last().unwrap();
4203 assert_eq!(path.hops.len(), 2);
4204 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4205 assert_eq!(path.final_value_msat(), 15_000);
4208 // Now let's see if routing works if we know only capacity from the UTXO.
4210 // We can't change UTXO capacity on the fly, so we'll disable
4211 // the existing channel and add another one with the capacity we need.
4212 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4213 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4214 short_channel_id: 3,
4217 cltv_expiry_delta: 0,
4218 htlc_minimum_msat: 0,
4219 htlc_maximum_msat: MAX_VALUE_MSAT,
4221 fee_proportional_millionths: 0,
4222 excess_data: Vec::new()
4225 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4226 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4227 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4228 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4229 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4231 *chain_monitor.utxo_ret.lock().unwrap() =
4232 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4233 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4235 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4236 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4237 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4238 short_channel_id: 333,
4241 cltv_expiry_delta: (3 << 4) | 1,
4242 htlc_minimum_msat: 0,
4243 htlc_maximum_msat: 15_000,
4245 fee_proportional_millionths: 0,
4246 excess_data: Vec::new()
4248 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4249 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4250 short_channel_id: 333,
4253 cltv_expiry_delta: (3 << 4) | 2,
4254 htlc_minimum_msat: 0,
4255 htlc_maximum_msat: 15_000,
4257 fee_proportional_millionths: 0,
4258 excess_data: Vec::new()
4262 // Attempt to route more than available results in a failure.
4263 let route_params = RouteParameters::from_payment_params_and_value(
4264 payment_params.clone(), 15_001);
4265 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4266 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4267 &scorer, &(), &random_seed_bytes) {
4268 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4269 } else { panic!(); }
4273 // Now, attempt to route an exact amount we have should be fine.
4274 let route_params = RouteParameters::from_payment_params_and_value(
4275 payment_params.clone(), 15_000);
4276 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4277 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4278 assert_eq!(route.paths.len(), 1);
4279 let path = route.paths.last().unwrap();
4280 assert_eq!(path.hops.len(), 2);
4281 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4282 assert_eq!(path.final_value_msat(), 15_000);
4285 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4286 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4287 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4288 short_channel_id: 333,
4291 cltv_expiry_delta: 0,
4292 htlc_minimum_msat: 0,
4293 htlc_maximum_msat: 10_000,
4295 fee_proportional_millionths: 0,
4296 excess_data: Vec::new()
4300 // Attempt to route more than available results in a failure.
4301 let route_params = RouteParameters::from_payment_params_and_value(
4302 payment_params.clone(), 10_001);
4303 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4304 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4305 &scorer, &(), &random_seed_bytes) {
4306 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4307 } else { panic!(); }
4311 // Now, attempt to route an exact amount we have should be fine.
4312 let route_params = RouteParameters::from_payment_params_and_value(
4313 payment_params.clone(), 10_000);
4314 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4315 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4316 assert_eq!(route.paths.len(), 1);
4317 let path = route.paths.last().unwrap();
4318 assert_eq!(path.hops.len(), 2);
4319 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4320 assert_eq!(path.final_value_msat(), 10_000);
4325 fn available_liquidity_last_hop_test() {
4326 // Check that available liquidity properly limits the path even when only
4327 // one of the latter hops is limited.
4328 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4329 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4330 let scorer = ln_test_utils::TestScorer::new();
4331 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4332 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4333 let config = UserConfig::default();
4334 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4336 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4337 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4338 // Total capacity: 50 sats.
4340 // Disable other potential paths.
4341 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4342 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4343 short_channel_id: 2,
4346 cltv_expiry_delta: 0,
4347 htlc_minimum_msat: 0,
4348 htlc_maximum_msat: 100_000,
4350 fee_proportional_millionths: 0,
4351 excess_data: Vec::new()
4353 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4354 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4355 short_channel_id: 7,
4358 cltv_expiry_delta: 0,
4359 htlc_minimum_msat: 0,
4360 htlc_maximum_msat: 100_000,
4362 fee_proportional_millionths: 0,
4363 excess_data: Vec::new()
4368 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4370 short_channel_id: 12,
4373 cltv_expiry_delta: 0,
4374 htlc_minimum_msat: 0,
4375 htlc_maximum_msat: 100_000,
4377 fee_proportional_millionths: 0,
4378 excess_data: Vec::new()
4380 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4382 short_channel_id: 13,
4385 cltv_expiry_delta: 0,
4386 htlc_minimum_msat: 0,
4387 htlc_maximum_msat: 100_000,
4389 fee_proportional_millionths: 0,
4390 excess_data: Vec::new()
4393 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4394 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4395 short_channel_id: 6,
4398 cltv_expiry_delta: 0,
4399 htlc_minimum_msat: 0,
4400 htlc_maximum_msat: 50_000,
4402 fee_proportional_millionths: 0,
4403 excess_data: Vec::new()
4405 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4406 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4407 short_channel_id: 11,
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 // Attempt to route more than available results in a failure.
4419 let route_params = RouteParameters::from_payment_params_and_value(
4420 payment_params.clone(), 60_000);
4421 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4422 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4423 &scorer, &(), &random_seed_bytes) {
4424 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4425 } else { panic!(); }
4429 // Now, attempt to route 49 sats (just a bit below the capacity).
4430 let route_params = RouteParameters::from_payment_params_and_value(
4431 payment_params.clone(), 49_000);
4432 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4433 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4434 assert_eq!(route.paths.len(), 1);
4435 let mut total_amount_paid_msat = 0;
4436 for path in &route.paths {
4437 assert_eq!(path.hops.len(), 4);
4438 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4439 total_amount_paid_msat += path.final_value_msat();
4441 assert_eq!(total_amount_paid_msat, 49_000);
4445 // Attempt to route an exact amount is also fine
4446 let route_params = RouteParameters::from_payment_params_and_value(
4447 payment_params, 50_000);
4448 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4449 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4450 assert_eq!(route.paths.len(), 1);
4451 let mut total_amount_paid_msat = 0;
4452 for path in &route.paths {
4453 assert_eq!(path.hops.len(), 4);
4454 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4455 total_amount_paid_msat += path.final_value_msat();
4457 assert_eq!(total_amount_paid_msat, 50_000);
4462 fn ignore_fee_first_hop_test() {
4463 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4464 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4465 let scorer = ln_test_utils::TestScorer::new();
4466 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4467 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4468 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4470 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4471 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4472 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4473 short_channel_id: 1,
4476 cltv_expiry_delta: 0,
4477 htlc_minimum_msat: 0,
4478 htlc_maximum_msat: 100_000,
4479 fee_base_msat: 1_000_000,
4480 fee_proportional_millionths: 0,
4481 excess_data: Vec::new()
4483 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4484 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4485 short_channel_id: 3,
4488 cltv_expiry_delta: 0,
4489 htlc_minimum_msat: 0,
4490 htlc_maximum_msat: 50_000,
4492 fee_proportional_millionths: 0,
4493 excess_data: Vec::new()
4497 let route_params = RouteParameters::from_payment_params_and_value(
4498 payment_params, 50_000);
4499 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4500 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4501 assert_eq!(route.paths.len(), 1);
4502 let mut total_amount_paid_msat = 0;
4503 for path in &route.paths {
4504 assert_eq!(path.hops.len(), 2);
4505 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4506 total_amount_paid_msat += path.final_value_msat();
4508 assert_eq!(total_amount_paid_msat, 50_000);
4513 fn simple_mpp_route_test() {
4514 let (secp_ctx, _, _, _, _) = build_graph();
4515 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4516 let config = UserConfig::default();
4517 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4518 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4519 do_simple_mpp_route_test(clear_payment_params);
4521 // MPP to a 1-hop blinded path for nodes[2]
4522 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
4523 let blinded_path = BlindedPath {
4524 introduction_node_id: nodes[2],
4525 blinding_point: ln_test_utils::pubkey(42),
4526 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4528 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4530 fee_proportional_millionths: 0,
4531 htlc_minimum_msat: 0,
4532 htlc_maximum_msat: 0,
4533 cltv_expiry_delta: 0,
4534 features: BlindedHopFeatures::empty(),
4536 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4537 .with_bolt12_features(bolt12_features.clone()).unwrap();
4538 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4540 // MPP to 3 2-hop blinded paths
4541 let mut blinded_path_node_0 = blinded_path.clone();
4542 blinded_path_node_0.introduction_node_id = nodes[0];
4543 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4544 let mut node_0_payinfo = blinded_payinfo.clone();
4545 node_0_payinfo.htlc_maximum_msat = 50_000;
4547 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4548 blinded_path_node_7.introduction_node_id = nodes[7];
4549 let mut node_7_payinfo = blinded_payinfo.clone();
4550 node_7_payinfo.htlc_maximum_msat = 60_000;
4552 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4553 blinded_path_node_1.introduction_node_id = nodes[1];
4554 let mut node_1_payinfo = blinded_payinfo.clone();
4555 node_1_payinfo.htlc_maximum_msat = 180_000;
4557 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4559 (node_0_payinfo, blinded_path_node_0),
4560 (node_7_payinfo, blinded_path_node_7),
4561 (node_1_payinfo, blinded_path_node_1)
4563 .with_bolt12_features(bolt12_features).unwrap();
4564 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4568 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4569 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4570 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4571 let scorer = ln_test_utils::TestScorer::new();
4572 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4573 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4575 // We need a route consisting of 3 paths:
4576 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4577 // To achieve this, the amount being transferred should be around
4578 // the total capacity of these 3 paths.
4580 // First, we set limits on these (previously unlimited) channels.
4581 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4583 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4584 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4585 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4586 short_channel_id: 1,
4589 cltv_expiry_delta: 0,
4590 htlc_minimum_msat: 0,
4591 htlc_maximum_msat: 100_000,
4593 fee_proportional_millionths: 0,
4594 excess_data: Vec::new()
4596 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4597 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4598 short_channel_id: 3,
4601 cltv_expiry_delta: 0,
4602 htlc_minimum_msat: 0,
4603 htlc_maximum_msat: 50_000,
4605 fee_proportional_millionths: 0,
4606 excess_data: Vec::new()
4609 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4610 // (total limit 60).
4611 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4612 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4613 short_channel_id: 12,
4616 cltv_expiry_delta: 0,
4617 htlc_minimum_msat: 0,
4618 htlc_maximum_msat: 60_000,
4620 fee_proportional_millionths: 0,
4621 excess_data: Vec::new()
4623 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4624 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4625 short_channel_id: 13,
4628 cltv_expiry_delta: 0,
4629 htlc_minimum_msat: 0,
4630 htlc_maximum_msat: 60_000,
4632 fee_proportional_millionths: 0,
4633 excess_data: Vec::new()
4636 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4637 // (total capacity 180 sats).
4638 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4639 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4640 short_channel_id: 2,
4643 cltv_expiry_delta: 0,
4644 htlc_minimum_msat: 0,
4645 htlc_maximum_msat: 200_000,
4647 fee_proportional_millionths: 0,
4648 excess_data: Vec::new()
4650 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4651 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4652 short_channel_id: 4,
4655 cltv_expiry_delta: 0,
4656 htlc_minimum_msat: 0,
4657 htlc_maximum_msat: 180_000,
4659 fee_proportional_millionths: 0,
4660 excess_data: Vec::new()
4664 // Attempt to route more than available results in a failure.
4665 let route_params = RouteParameters::from_payment_params_and_value(
4666 payment_params.clone(), 300_000);
4667 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4668 &our_id, &route_params, &network_graph.read_only(), None,
4669 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4670 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4671 } else { panic!(); }
4675 // Attempt to route while setting max_path_count to 0 results in a failure.
4676 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4677 let route_params = RouteParameters::from_payment_params_and_value(
4678 zero_payment_params, 100);
4679 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4680 &our_id, &route_params, &network_graph.read_only(), None,
4681 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4682 assert_eq!(err, "Can't find a route with no paths allowed.");
4683 } else { panic!(); }
4687 // Attempt to route while setting max_path_count to 3 results in a failure.
4688 // This is the case because the minimal_value_contribution_msat would require each path
4689 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4690 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4691 let route_params = RouteParameters::from_payment_params_and_value(
4692 fail_payment_params, 250_000);
4693 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4694 &our_id, &route_params, &network_graph.read_only(), None,
4695 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4696 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4697 } else { panic!(); }
4701 // Now, attempt to route 250 sats (just a bit below the capacity).
4702 // Our algorithm should provide us with these 3 paths.
4703 let route_params = RouteParameters::from_payment_params_and_value(
4704 payment_params.clone(), 250_000);
4705 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4706 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4707 assert_eq!(route.paths.len(), 3);
4708 let mut total_amount_paid_msat = 0;
4709 for path in &route.paths {
4710 if let Some(bt) = &path.blinded_tail {
4711 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4713 assert_eq!(path.hops.len(), 2);
4714 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4716 total_amount_paid_msat += path.final_value_msat();
4718 assert_eq!(total_amount_paid_msat, 250_000);
4722 // Attempt to route an exact amount is also fine
4723 let route_params = RouteParameters::from_payment_params_and_value(
4724 payment_params.clone(), 290_000);
4725 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4726 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4727 assert_eq!(route.paths.len(), 3);
4728 let mut total_amount_paid_msat = 0;
4729 for path in &route.paths {
4730 if payment_params.payee.blinded_route_hints().len() != 0 {
4731 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
4732 if let Some(bt) = &path.blinded_tail {
4733 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4734 if bt.hops.len() > 1 {
4735 assert_eq!(path.hops.last().unwrap().pubkey,
4736 payment_params.payee.blinded_route_hints().iter()
4737 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
4738 .map(|(_, p)| p.introduction_node_id).unwrap());
4740 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4743 assert_eq!(path.hops.len(), 2);
4744 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4746 total_amount_paid_msat += path.final_value_msat();
4748 assert_eq!(total_amount_paid_msat, 290_000);
4753 fn long_mpp_route_test() {
4754 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4755 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4756 let scorer = ln_test_utils::TestScorer::new();
4757 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4758 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4759 let config = UserConfig::default();
4760 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4761 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4763 // We need a route consisting of 3 paths:
4764 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4765 // Note that these paths overlap (channels 5, 12, 13).
4766 // We will route 300 sats.
4767 // Each path will have 100 sats capacity, those channels which
4768 // are used twice will have 200 sats capacity.
4770 // Disable other potential paths.
4771 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4772 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4773 short_channel_id: 2,
4776 cltv_expiry_delta: 0,
4777 htlc_minimum_msat: 0,
4778 htlc_maximum_msat: 100_000,
4780 fee_proportional_millionths: 0,
4781 excess_data: Vec::new()
4783 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4784 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4785 short_channel_id: 7,
4788 cltv_expiry_delta: 0,
4789 htlc_minimum_msat: 0,
4790 htlc_maximum_msat: 100_000,
4792 fee_proportional_millionths: 0,
4793 excess_data: Vec::new()
4796 // Path via {node0, node2} is channels {1, 3, 5}.
4797 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4798 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4799 short_channel_id: 1,
4802 cltv_expiry_delta: 0,
4803 htlc_minimum_msat: 0,
4804 htlc_maximum_msat: 100_000,
4806 fee_proportional_millionths: 0,
4807 excess_data: Vec::new()
4809 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4810 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4811 short_channel_id: 3,
4814 cltv_expiry_delta: 0,
4815 htlc_minimum_msat: 0,
4816 htlc_maximum_msat: 100_000,
4818 fee_proportional_millionths: 0,
4819 excess_data: Vec::new()
4822 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4823 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4824 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4825 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4826 short_channel_id: 5,
4829 cltv_expiry_delta: 0,
4830 htlc_minimum_msat: 0,
4831 htlc_maximum_msat: 200_000,
4833 fee_proportional_millionths: 0,
4834 excess_data: Vec::new()
4837 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4838 // Add 100 sats to the capacities of {12, 13}, because these channels
4839 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4840 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4841 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4842 short_channel_id: 12,
4845 cltv_expiry_delta: 0,
4846 htlc_minimum_msat: 0,
4847 htlc_maximum_msat: 200_000,
4849 fee_proportional_millionths: 0,
4850 excess_data: Vec::new()
4852 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4853 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4854 short_channel_id: 13,
4857 cltv_expiry_delta: 0,
4858 htlc_minimum_msat: 0,
4859 htlc_maximum_msat: 200_000,
4861 fee_proportional_millionths: 0,
4862 excess_data: Vec::new()
4865 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4866 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4867 short_channel_id: 6,
4870 cltv_expiry_delta: 0,
4871 htlc_minimum_msat: 0,
4872 htlc_maximum_msat: 100_000,
4874 fee_proportional_millionths: 0,
4875 excess_data: Vec::new()
4877 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4878 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4879 short_channel_id: 11,
4882 cltv_expiry_delta: 0,
4883 htlc_minimum_msat: 0,
4884 htlc_maximum_msat: 100_000,
4886 fee_proportional_millionths: 0,
4887 excess_data: Vec::new()
4890 // Path via {node7, node2} is channels {12, 13, 5}.
4891 // We already limited them to 200 sats (they are used twice for 100 sats).
4892 // Nothing to do here.
4895 // Attempt to route more than available results in a failure.
4896 let route_params = RouteParameters::from_payment_params_and_value(
4897 payment_params.clone(), 350_000);
4898 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4899 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4900 &scorer, &(), &random_seed_bytes) {
4901 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4902 } else { panic!(); }
4906 // Now, attempt to route 300 sats (exact amount we can route).
4907 // Our algorithm should provide us with these 3 paths, 100 sats each.
4908 let route_params = RouteParameters::from_payment_params_and_value(
4909 payment_params, 300_000);
4910 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4911 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4912 assert_eq!(route.paths.len(), 3);
4914 let mut total_amount_paid_msat = 0;
4915 for path in &route.paths {
4916 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4917 total_amount_paid_msat += path.final_value_msat();
4919 assert_eq!(total_amount_paid_msat, 300_000);
4925 fn mpp_cheaper_route_test() {
4926 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4927 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4928 let scorer = ln_test_utils::TestScorer::new();
4929 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4930 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4931 let config = UserConfig::default();
4932 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4934 // This test checks that if we have two cheaper paths and one more expensive path,
4935 // so that liquidity-wise any 2 of 3 combination is sufficient,
4936 // two cheaper paths will be taken.
4937 // These paths have equal available liquidity.
4939 // We need a combination of 3 paths:
4940 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4941 // Note that these paths overlap (channels 5, 12, 13).
4942 // Each path will have 100 sats capacity, those channels which
4943 // are used twice will have 200 sats capacity.
4945 // Disable other potential paths.
4946 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4947 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4948 short_channel_id: 2,
4951 cltv_expiry_delta: 0,
4952 htlc_minimum_msat: 0,
4953 htlc_maximum_msat: 100_000,
4955 fee_proportional_millionths: 0,
4956 excess_data: Vec::new()
4958 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4959 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4960 short_channel_id: 7,
4963 cltv_expiry_delta: 0,
4964 htlc_minimum_msat: 0,
4965 htlc_maximum_msat: 100_000,
4967 fee_proportional_millionths: 0,
4968 excess_data: Vec::new()
4971 // Path via {node0, node2} is channels {1, 3, 5}.
4972 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4973 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4974 short_channel_id: 1,
4977 cltv_expiry_delta: 0,
4978 htlc_minimum_msat: 0,
4979 htlc_maximum_msat: 100_000,
4981 fee_proportional_millionths: 0,
4982 excess_data: Vec::new()
4984 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4985 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4986 short_channel_id: 3,
4989 cltv_expiry_delta: 0,
4990 htlc_minimum_msat: 0,
4991 htlc_maximum_msat: 100_000,
4993 fee_proportional_millionths: 0,
4994 excess_data: Vec::new()
4997 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4998 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4999 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5000 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5001 short_channel_id: 5,
5004 cltv_expiry_delta: 0,
5005 htlc_minimum_msat: 0,
5006 htlc_maximum_msat: 200_000,
5008 fee_proportional_millionths: 0,
5009 excess_data: Vec::new()
5012 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5013 // Add 100 sats to the capacities of {12, 13}, because these channels
5014 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5015 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5016 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5017 short_channel_id: 12,
5020 cltv_expiry_delta: 0,
5021 htlc_minimum_msat: 0,
5022 htlc_maximum_msat: 200_000,
5024 fee_proportional_millionths: 0,
5025 excess_data: Vec::new()
5027 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5028 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5029 short_channel_id: 13,
5032 cltv_expiry_delta: 0,
5033 htlc_minimum_msat: 0,
5034 htlc_maximum_msat: 200_000,
5036 fee_proportional_millionths: 0,
5037 excess_data: Vec::new()
5040 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5041 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5042 short_channel_id: 6,
5045 cltv_expiry_delta: 0,
5046 htlc_minimum_msat: 0,
5047 htlc_maximum_msat: 100_000,
5048 fee_base_msat: 1_000,
5049 fee_proportional_millionths: 0,
5050 excess_data: Vec::new()
5052 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5053 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5054 short_channel_id: 11,
5057 cltv_expiry_delta: 0,
5058 htlc_minimum_msat: 0,
5059 htlc_maximum_msat: 100_000,
5061 fee_proportional_millionths: 0,
5062 excess_data: Vec::new()
5065 // Path via {node7, node2} is channels {12, 13, 5}.
5066 // We already limited them to 200 sats (they are used twice for 100 sats).
5067 // Nothing to do here.
5070 // Now, attempt to route 180 sats.
5071 // Our algorithm should provide us with these 2 paths.
5072 let route_params = RouteParameters::from_payment_params_and_value(
5073 payment_params, 180_000);
5074 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5075 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5076 assert_eq!(route.paths.len(), 2);
5078 let mut total_value_transferred_msat = 0;
5079 let mut total_paid_msat = 0;
5080 for path in &route.paths {
5081 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5082 total_value_transferred_msat += path.final_value_msat();
5083 for hop in &path.hops {
5084 total_paid_msat += hop.fee_msat;
5087 // If we paid fee, this would be higher.
5088 assert_eq!(total_value_transferred_msat, 180_000);
5089 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5090 assert_eq!(total_fees_paid, 0);
5095 fn fees_on_mpp_route_test() {
5096 // This test makes sure that MPP algorithm properly takes into account
5097 // fees charged on the channels, by making the fees impactful:
5098 // if the fee is not properly accounted for, the behavior is different.
5099 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5100 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5101 let scorer = ln_test_utils::TestScorer::new();
5102 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5103 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5104 let config = UserConfig::default();
5105 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5107 // We need a route consisting of 2 paths:
5108 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5109 // We will route 200 sats, Each path will have 100 sats capacity.
5111 // This test is not particularly stable: e.g.,
5112 // there's a way to route via {node0, node2, node4}.
5113 // It works while pathfinding is deterministic, but can be broken otherwise.
5114 // It's fine to ignore this concern for now.
5116 // Disable other potential paths.
5117 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5118 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5119 short_channel_id: 2,
5122 cltv_expiry_delta: 0,
5123 htlc_minimum_msat: 0,
5124 htlc_maximum_msat: 100_000,
5126 fee_proportional_millionths: 0,
5127 excess_data: Vec::new()
5130 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5131 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5132 short_channel_id: 7,
5135 cltv_expiry_delta: 0,
5136 htlc_minimum_msat: 0,
5137 htlc_maximum_msat: 100_000,
5139 fee_proportional_millionths: 0,
5140 excess_data: Vec::new()
5143 // Path via {node0, node2} is channels {1, 3, 5}.
5144 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5145 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5146 short_channel_id: 1,
5149 cltv_expiry_delta: 0,
5150 htlc_minimum_msat: 0,
5151 htlc_maximum_msat: 100_000,
5153 fee_proportional_millionths: 0,
5154 excess_data: Vec::new()
5156 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5157 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5158 short_channel_id: 3,
5161 cltv_expiry_delta: 0,
5162 htlc_minimum_msat: 0,
5163 htlc_maximum_msat: 100_000,
5165 fee_proportional_millionths: 0,
5166 excess_data: Vec::new()
5169 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5170 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5171 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5172 short_channel_id: 5,
5175 cltv_expiry_delta: 0,
5176 htlc_minimum_msat: 0,
5177 htlc_maximum_msat: 100_000,
5179 fee_proportional_millionths: 0,
5180 excess_data: Vec::new()
5183 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5184 // All channels should be 100 sats capacity. But for the fee experiment,
5185 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5186 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5187 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5188 // so no matter how large are other channels,
5189 // the whole path will be limited by 100 sats with just these 2 conditions:
5190 // - channel 12 capacity is 250 sats
5191 // - fee for channel 6 is 150 sats
5192 // Let's test this by enforcing these 2 conditions and removing other limits.
5193 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5194 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5195 short_channel_id: 12,
5198 cltv_expiry_delta: 0,
5199 htlc_minimum_msat: 0,
5200 htlc_maximum_msat: 250_000,
5202 fee_proportional_millionths: 0,
5203 excess_data: Vec::new()
5205 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5206 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5207 short_channel_id: 13,
5210 cltv_expiry_delta: 0,
5211 htlc_minimum_msat: 0,
5212 htlc_maximum_msat: MAX_VALUE_MSAT,
5214 fee_proportional_millionths: 0,
5215 excess_data: Vec::new()
5218 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5219 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5220 short_channel_id: 6,
5223 cltv_expiry_delta: 0,
5224 htlc_minimum_msat: 0,
5225 htlc_maximum_msat: MAX_VALUE_MSAT,
5226 fee_base_msat: 150_000,
5227 fee_proportional_millionths: 0,
5228 excess_data: Vec::new()
5230 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5231 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5232 short_channel_id: 11,
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()
5244 // Attempt to route more than available results in a failure.
5245 let route_params = RouteParameters::from_payment_params_and_value(
5246 payment_params.clone(), 210_000);
5247 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5248 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5249 &scorer, &(), &random_seed_bytes) {
5250 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5251 } else { panic!(); }
5255 // Now, attempt to route 200 sats (exact amount we can route).
5256 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 200_000);
5257 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5258 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5259 assert_eq!(route.paths.len(), 2);
5261 let mut total_amount_paid_msat = 0;
5262 for path in &route.paths {
5263 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5264 total_amount_paid_msat += path.final_value_msat();
5266 assert_eq!(total_amount_paid_msat, 200_000);
5267 assert_eq!(route.get_total_fees(), 150_000);
5272 fn mpp_with_last_hops() {
5273 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5274 // via a single last-hop route hint, we'd fail to route if we first collected routes
5275 // totaling close but not quite enough to fund the full payment.
5277 // This was because we considered last-hop hints to have exactly the sought payment amount
5278 // instead of the amount we were trying to collect, needlessly limiting our path searching
5279 // at the very first hop.
5281 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5282 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5283 // to only have the remaining to-collect amount in available liquidity.
5285 // This bug appeared in production in some specific channel configurations.
5286 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5287 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5288 let scorer = ln_test_utils::TestScorer::new();
5289 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5290 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5291 let config = UserConfig::default();
5292 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5293 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5294 src_node_id: nodes[2],
5295 short_channel_id: 42,
5296 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5297 cltv_expiry_delta: 42,
5298 htlc_minimum_msat: None,
5299 htlc_maximum_msat: None,
5300 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5302 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5303 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5304 // would first use the no-fee route and then fail to find a path along the second route as
5305 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5306 // under 5% of our payment amount.
5307 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5308 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5309 short_channel_id: 1,
5312 cltv_expiry_delta: (5 << 4) | 5,
5313 htlc_minimum_msat: 0,
5314 htlc_maximum_msat: 99_000,
5315 fee_base_msat: u32::max_value(),
5316 fee_proportional_millionths: u32::max_value(),
5317 excess_data: Vec::new()
5319 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5320 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5321 short_channel_id: 2,
5324 cltv_expiry_delta: (5 << 4) | 3,
5325 htlc_minimum_msat: 0,
5326 htlc_maximum_msat: 99_000,
5327 fee_base_msat: u32::max_value(),
5328 fee_proportional_millionths: u32::max_value(),
5329 excess_data: Vec::new()
5331 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5332 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5333 short_channel_id: 4,
5336 cltv_expiry_delta: (4 << 4) | 1,
5337 htlc_minimum_msat: 0,
5338 htlc_maximum_msat: MAX_VALUE_MSAT,
5340 fee_proportional_millionths: 0,
5341 excess_data: Vec::new()
5343 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5344 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5345 short_channel_id: 13,
5347 flags: 0|2, // Channel disabled
5348 cltv_expiry_delta: (13 << 4) | 1,
5349 htlc_minimum_msat: 0,
5350 htlc_maximum_msat: MAX_VALUE_MSAT,
5352 fee_proportional_millionths: 2000000,
5353 excess_data: Vec::new()
5356 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5358 let route_params = RouteParameters::from_payment_params_and_value(
5359 payment_params, 100_000);
5360 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5361 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5362 assert_eq!(route.paths.len(), 2);
5363 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5364 // Paths are manually ordered ordered by SCID, so:
5365 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5366 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5367 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5368 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5369 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5370 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5371 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5372 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5373 assert_eq!(route.get_total_fees(), 1);
5374 assert_eq!(route.get_total_amount(), 100_000);
5378 fn drop_lowest_channel_mpp_route_test() {
5379 // This test checks that low-capacity channel is dropped when after
5380 // path finding we realize that we found more capacity than we need.
5381 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5382 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5383 let scorer = ln_test_utils::TestScorer::new();
5384 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5385 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5386 let config = UserConfig::default();
5387 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5388 .with_max_channel_saturation_power_of_half(0);
5390 // We need a route consisting of 3 paths:
5391 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5393 // The first and the second paths should be sufficient, but the third should be
5394 // cheaper, so that we select it but drop later.
5396 // First, we set limits on these (previously unlimited) channels.
5397 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5399 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5400 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5401 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5402 short_channel_id: 1,
5405 cltv_expiry_delta: 0,
5406 htlc_minimum_msat: 0,
5407 htlc_maximum_msat: 100_000,
5409 fee_proportional_millionths: 0,
5410 excess_data: Vec::new()
5412 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5413 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5414 short_channel_id: 3,
5417 cltv_expiry_delta: 0,
5418 htlc_minimum_msat: 0,
5419 htlc_maximum_msat: 50_000,
5421 fee_proportional_millionths: 0,
5422 excess_data: Vec::new()
5425 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5426 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5427 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5428 short_channel_id: 12,
5431 cltv_expiry_delta: 0,
5432 htlc_minimum_msat: 0,
5433 htlc_maximum_msat: 60_000,
5435 fee_proportional_millionths: 0,
5436 excess_data: Vec::new()
5438 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5439 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5440 short_channel_id: 13,
5443 cltv_expiry_delta: 0,
5444 htlc_minimum_msat: 0,
5445 htlc_maximum_msat: 60_000,
5447 fee_proportional_millionths: 0,
5448 excess_data: Vec::new()
5451 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5452 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5453 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5454 short_channel_id: 2,
5457 cltv_expiry_delta: 0,
5458 htlc_minimum_msat: 0,
5459 htlc_maximum_msat: 20_000,
5461 fee_proportional_millionths: 0,
5462 excess_data: Vec::new()
5464 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5465 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5466 short_channel_id: 4,
5469 cltv_expiry_delta: 0,
5470 htlc_minimum_msat: 0,
5471 htlc_maximum_msat: 20_000,
5473 fee_proportional_millionths: 0,
5474 excess_data: Vec::new()
5478 // Attempt to route more than available results in a failure.
5479 let route_params = RouteParameters::from_payment_params_and_value(
5480 payment_params.clone(), 150_000);
5481 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5482 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5483 &scorer, &(), &random_seed_bytes) {
5484 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5485 } else { panic!(); }
5489 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5490 // Our algorithm should provide us with these 3 paths.
5491 let route_params = RouteParameters::from_payment_params_and_value(
5492 payment_params.clone(), 125_000);
5493 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5494 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5495 assert_eq!(route.paths.len(), 3);
5496 let mut total_amount_paid_msat = 0;
5497 for path in &route.paths {
5498 assert_eq!(path.hops.len(), 2);
5499 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5500 total_amount_paid_msat += path.final_value_msat();
5502 assert_eq!(total_amount_paid_msat, 125_000);
5506 // Attempt to route without the last small cheap channel
5507 let route_params = RouteParameters::from_payment_params_and_value(
5508 payment_params, 90_000);
5509 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5510 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5511 assert_eq!(route.paths.len(), 2);
5512 let mut total_amount_paid_msat = 0;
5513 for path in &route.paths {
5514 assert_eq!(path.hops.len(), 2);
5515 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5516 total_amount_paid_msat += path.final_value_msat();
5518 assert_eq!(total_amount_paid_msat, 90_000);
5523 fn min_criteria_consistency() {
5524 // Test that we don't use an inconsistent metric between updating and walking nodes during
5525 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5526 // was updated with a different criterion from the heap sorting, resulting in loops in
5527 // calculated paths. We test for that specific case here.
5529 // We construct a network that looks like this:
5531 // node2 -1(3)2- node3
5535 // node1 -1(5)2- node4 -1(1)2- node6
5541 // We create a loop on the side of our real path - our destination is node 6, with a
5542 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5543 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5544 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5545 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5546 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5547 // "previous hop" being set to node 3, creating a loop in the path.
5548 let secp_ctx = Secp256k1::new();
5549 let logger = Arc::new(ln_test_utils::TestLogger::new());
5550 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5551 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5552 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5553 let scorer = ln_test_utils::TestScorer::new();
5554 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5555 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5556 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5558 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5559 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5560 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5561 short_channel_id: 6,
5564 cltv_expiry_delta: (6 << 4) | 0,
5565 htlc_minimum_msat: 0,
5566 htlc_maximum_msat: MAX_VALUE_MSAT,
5568 fee_proportional_millionths: 0,
5569 excess_data: Vec::new()
5571 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5573 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5574 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5575 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5576 short_channel_id: 5,
5579 cltv_expiry_delta: (5 << 4) | 0,
5580 htlc_minimum_msat: 0,
5581 htlc_maximum_msat: MAX_VALUE_MSAT,
5583 fee_proportional_millionths: 0,
5584 excess_data: Vec::new()
5586 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5588 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5589 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5590 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5591 short_channel_id: 4,
5594 cltv_expiry_delta: (4 << 4) | 0,
5595 htlc_minimum_msat: 0,
5596 htlc_maximum_msat: MAX_VALUE_MSAT,
5598 fee_proportional_millionths: 0,
5599 excess_data: Vec::new()
5601 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5603 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5604 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5605 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5606 short_channel_id: 3,
5609 cltv_expiry_delta: (3 << 4) | 0,
5610 htlc_minimum_msat: 0,
5611 htlc_maximum_msat: MAX_VALUE_MSAT,
5613 fee_proportional_millionths: 0,
5614 excess_data: Vec::new()
5616 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5618 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5619 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5620 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5621 short_channel_id: 2,
5624 cltv_expiry_delta: (2 << 4) | 0,
5625 htlc_minimum_msat: 0,
5626 htlc_maximum_msat: MAX_VALUE_MSAT,
5628 fee_proportional_millionths: 0,
5629 excess_data: Vec::new()
5632 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5633 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5634 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5635 short_channel_id: 1,
5638 cltv_expiry_delta: (1 << 4) | 0,
5639 htlc_minimum_msat: 100,
5640 htlc_maximum_msat: MAX_VALUE_MSAT,
5642 fee_proportional_millionths: 0,
5643 excess_data: Vec::new()
5645 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5648 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5649 let route_params = RouteParameters::from_payment_params_and_value(
5650 payment_params, 10_000);
5651 let route = get_route(&our_id, &route_params, &network.read_only(), None,
5652 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5653 assert_eq!(route.paths.len(), 1);
5654 assert_eq!(route.paths[0].hops.len(), 3);
5656 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5657 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5658 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5659 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5660 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5661 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5663 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5664 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5665 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5666 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5667 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5668 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5670 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5671 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5672 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5673 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5674 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5675 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5681 fn exact_fee_liquidity_limit() {
5682 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5683 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5684 // we calculated fees on a higher value, resulting in us ignoring such paths.
5685 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5686 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5687 let scorer = ln_test_utils::TestScorer::new();
5688 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5689 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5690 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5692 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5694 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5695 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5696 short_channel_id: 2,
5699 cltv_expiry_delta: 0,
5700 htlc_minimum_msat: 0,
5701 htlc_maximum_msat: 85_000,
5703 fee_proportional_millionths: 0,
5704 excess_data: Vec::new()
5707 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5708 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5709 short_channel_id: 12,
5712 cltv_expiry_delta: (4 << 4) | 1,
5713 htlc_minimum_msat: 0,
5714 htlc_maximum_msat: 270_000,
5716 fee_proportional_millionths: 1000000,
5717 excess_data: Vec::new()
5721 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5722 // 200% fee charged channel 13 in the 1-to-2 direction.
5723 let route_params = RouteParameters::from_payment_params_and_value(
5724 payment_params, 90_000);
5725 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5726 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5727 assert_eq!(route.paths.len(), 1);
5728 assert_eq!(route.paths[0].hops.len(), 2);
5730 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5731 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5732 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5733 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5734 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5735 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5737 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5738 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5739 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5740 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5741 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5742 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5747 fn htlc_max_reduction_below_min() {
5748 // Test that if, while walking the graph, we reduce the value being sent to meet an
5749 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5750 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5751 // resulting in us thinking there is no possible path, even if other paths exist.
5752 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5753 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5754 let scorer = ln_test_utils::TestScorer::new();
5755 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5756 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5757 let config = UserConfig::default();
5758 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5760 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5761 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5762 // then try to send 90_000.
5763 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5764 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5765 short_channel_id: 2,
5768 cltv_expiry_delta: 0,
5769 htlc_minimum_msat: 0,
5770 htlc_maximum_msat: 80_000,
5772 fee_proportional_millionths: 0,
5773 excess_data: Vec::new()
5775 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5776 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5777 short_channel_id: 4,
5780 cltv_expiry_delta: (4 << 4) | 1,
5781 htlc_minimum_msat: 90_000,
5782 htlc_maximum_msat: MAX_VALUE_MSAT,
5784 fee_proportional_millionths: 0,
5785 excess_data: Vec::new()
5789 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5790 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5791 // expensive) channels 12-13 path.
5792 let route_params = RouteParameters::from_payment_params_and_value(
5793 payment_params, 90_000);
5794 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5795 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5796 assert_eq!(route.paths.len(), 1);
5797 assert_eq!(route.paths[0].hops.len(), 2);
5799 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5800 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5801 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5802 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5803 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5804 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5806 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5807 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5808 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5809 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5810 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5811 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5816 fn multiple_direct_first_hops() {
5817 // Previously we'd only ever considered one first hop path per counterparty.
5818 // However, as we don't restrict users to one channel per peer, we really need to support
5819 // looking at all first hop paths.
5820 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5821 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5822 // route over multiple channels with the same first hop.
5823 let secp_ctx = Secp256k1::new();
5824 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5825 let logger = Arc::new(ln_test_utils::TestLogger::new());
5826 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5827 let scorer = ln_test_utils::TestScorer::new();
5828 let config = UserConfig::default();
5829 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5830 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5831 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5834 let route_params = RouteParameters::from_payment_params_and_value(
5835 payment_params.clone(), 100_000);
5836 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5837 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5838 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5839 ]), Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5840 assert_eq!(route.paths.len(), 1);
5841 assert_eq!(route.paths[0].hops.len(), 1);
5843 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5844 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5845 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5848 let route_params = RouteParameters::from_payment_params_and_value(
5849 payment_params.clone(), 100_000);
5850 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5851 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5852 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5853 ]), Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5854 assert_eq!(route.paths.len(), 2);
5855 assert_eq!(route.paths[0].hops.len(), 1);
5856 assert_eq!(route.paths[1].hops.len(), 1);
5858 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5859 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5861 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5862 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5864 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5865 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5869 // If we have a bunch of outbound channels to the same node, where most are not
5870 // sufficient to pay the full payment, but one is, we should default to just using the
5871 // one single channel that has sufficient balance, avoiding MPP.
5873 // If we have several options above the 3xpayment value threshold, we should pick the
5874 // smallest of them, avoiding further fragmenting our available outbound balance to
5876 let route_params = RouteParameters::from_payment_params_and_value(
5877 payment_params, 100_000);
5878 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5879 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5880 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5881 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5882 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5883 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5884 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5885 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5886 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5887 ]), Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5888 assert_eq!(route.paths.len(), 1);
5889 assert_eq!(route.paths[0].hops.len(), 1);
5891 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5892 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5893 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5898 fn prefers_shorter_route_with_higher_fees() {
5899 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5900 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5901 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5903 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5904 let scorer = ln_test_utils::TestScorer::new();
5905 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5906 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5907 let route_params = RouteParameters::from_payment_params_and_value(
5908 payment_params.clone(), 100);
5909 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
5910 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5911 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5913 assert_eq!(route.get_total_fees(), 100);
5914 assert_eq!(route.get_total_amount(), 100);
5915 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5917 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5918 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5919 let scorer = FixedPenaltyScorer::with_penalty(100);
5920 let route_params = RouteParameters::from_payment_params_and_value(
5921 payment_params, 100);
5922 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
5923 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5924 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5926 assert_eq!(route.get_total_fees(), 300);
5927 assert_eq!(route.get_total_amount(), 100);
5928 assert_eq!(path, vec![2, 4, 7, 10]);
5931 struct BadChannelScorer {
5932 short_channel_id: u64,
5936 impl Writeable for BadChannelScorer {
5937 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5939 impl ScoreLookUp for BadChannelScorer {
5940 type ScoreParams = ();
5941 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5942 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5946 struct BadNodeScorer {
5951 impl Writeable for BadNodeScorer {
5952 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5955 impl ScoreLookUp for BadNodeScorer {
5956 type ScoreParams = ();
5957 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5958 if *target == self.node_id { u64::max_value() } else { 0 }
5963 fn avoids_routing_through_bad_channels_and_nodes() {
5964 let (secp_ctx, network, _, _, logger) = build_graph();
5965 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5966 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5967 let network_graph = network.read_only();
5969 // A path to nodes[6] exists when no penalties are applied to any channel.
5970 let scorer = ln_test_utils::TestScorer::new();
5971 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5972 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5973 let route_params = RouteParameters::from_payment_params_and_value(
5974 payment_params, 100);
5975 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
5976 &scorer, &(), &random_seed_bytes).unwrap();
5977 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5979 assert_eq!(route.get_total_fees(), 100);
5980 assert_eq!(route.get_total_amount(), 100);
5981 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5983 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5984 let scorer = BadChannelScorer { short_channel_id: 6 };
5985 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
5986 &scorer, &(), &random_seed_bytes).unwrap();
5987 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5989 assert_eq!(route.get_total_fees(), 300);
5990 assert_eq!(route.get_total_amount(), 100);
5991 assert_eq!(path, vec![2, 4, 7, 10]);
5993 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5994 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5995 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
5996 &scorer, &(), &random_seed_bytes) {
5997 Err(LightningError { err, .. } ) => {
5998 assert_eq!(err, "Failed to find a path to the given destination");
6000 Ok(_) => panic!("Expected error"),
6005 fn total_fees_single_path() {
6007 paths: vec![Path { hops: vec![
6009 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6010 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6011 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6014 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6015 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6016 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6019 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6020 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6021 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6023 ], blinded_tail: None }],
6027 assert_eq!(route.get_total_fees(), 250);
6028 assert_eq!(route.get_total_amount(), 225);
6032 fn total_fees_multi_path() {
6034 paths: vec![Path { hops: vec![
6036 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6037 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6038 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6041 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6042 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6043 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6045 ], blinded_tail: None }, Path { hops: vec![
6047 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6048 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6049 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6052 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6053 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6054 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6056 ], blinded_tail: None }],
6060 assert_eq!(route.get_total_fees(), 200);
6061 assert_eq!(route.get_total_amount(), 300);
6065 fn total_empty_route_no_panic() {
6066 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6067 // would both panic if the route was completely empty. We test to ensure they return 0
6068 // here, even though its somewhat nonsensical as a route.
6069 let route = Route { paths: Vec::new(), route_params: None };
6071 assert_eq!(route.get_total_fees(), 0);
6072 assert_eq!(route.get_total_amount(), 0);
6076 fn limits_total_cltv_delta() {
6077 let (secp_ctx, network, _, _, logger) = build_graph();
6078 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6079 let network_graph = network.read_only();
6081 let scorer = ln_test_utils::TestScorer::new();
6083 // Make sure that generally there is at least one route available
6084 let feasible_max_total_cltv_delta = 1008;
6085 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6086 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6087 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6088 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6089 let route_params = RouteParameters::from_payment_params_and_value(
6090 feasible_payment_params, 100);
6091 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6092 &scorer, &(), &random_seed_bytes).unwrap();
6093 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6094 assert_ne!(path.len(), 0);
6096 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6097 let fail_max_total_cltv_delta = 23;
6098 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6099 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6100 let route_params = RouteParameters::from_payment_params_and_value(
6101 fail_payment_params, 100);
6102 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6103 &(), &random_seed_bytes)
6105 Err(LightningError { err, .. } ) => {
6106 assert_eq!(err, "Failed to find a path to the given destination");
6108 Ok(_) => panic!("Expected error"),
6113 fn avoids_recently_failed_paths() {
6114 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6115 // randomly inserting channels into it until we can't find a route anymore.
6116 let (secp_ctx, network, _, _, logger) = build_graph();
6117 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6118 let network_graph = network.read_only();
6120 let scorer = ln_test_utils::TestScorer::new();
6121 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6122 .with_max_path_count(1);
6123 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6124 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6126 // We should be able to find a route initially, and then after we fail a few random
6127 // channels eventually we won't be able to any longer.
6128 let route_params = RouteParameters::from_payment_params_and_value(
6129 payment_params.clone(), 100);
6130 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6131 &scorer, &(), &random_seed_bytes).is_ok());
6133 let route_params = RouteParameters::from_payment_params_and_value(
6134 payment_params.clone(), 100);
6135 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6136 Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
6138 for chan in route.paths[0].hops.iter() {
6139 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6141 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6142 % route.paths[0].hops.len();
6143 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6149 fn limits_path_length() {
6150 let (secp_ctx, network, _, _, logger) = build_line_graph();
6151 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6152 let network_graph = network.read_only();
6154 let scorer = ln_test_utils::TestScorer::new();
6155 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6156 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6158 // First check we can actually create a long route on this graph.
6159 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6160 let route_params = RouteParameters::from_payment_params_and_value(
6161 feasible_payment_params, 100);
6162 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6163 &scorer, &(), &random_seed_bytes).unwrap();
6164 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6165 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6167 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6168 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6169 let route_params = RouteParameters::from_payment_params_and_value(
6170 fail_payment_params, 100);
6171 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6172 &(), &random_seed_bytes)
6174 Err(LightningError { err, .. } ) => {
6175 assert_eq!(err, "Failed to find a path to the given destination");
6177 Ok(_) => panic!("Expected error"),
6182 fn adds_and_limits_cltv_offset() {
6183 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6184 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6186 let scorer = ln_test_utils::TestScorer::new();
6188 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6189 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6190 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6191 let route_params = RouteParameters::from_payment_params_and_value(
6192 payment_params.clone(), 100);
6193 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6194 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6195 assert_eq!(route.paths.len(), 1);
6197 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6199 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6200 let mut route_default = route.clone();
6201 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6202 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6203 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6204 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6205 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6207 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6208 let mut route_limited = route.clone();
6209 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6210 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6211 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6212 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6213 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6217 fn adds_plausible_cltv_offset() {
6218 let (secp_ctx, network, _, _, logger) = build_graph();
6219 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6220 let network_graph = network.read_only();
6221 let network_nodes = network_graph.nodes();
6222 let network_channels = network_graph.channels();
6223 let scorer = ln_test_utils::TestScorer::new();
6224 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6225 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6226 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 mut route = get_route(&our_id, &route_params, &network_graph, None,
6231 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6232 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6234 let mut path_plausibility = vec![];
6236 for p in route.paths {
6237 // 1. Select random observation point
6238 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6239 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6241 prng.process_in_place(&mut random_bytes);
6242 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6243 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6245 // 2. Calculate what CLTV expiry delta we would observe there
6246 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6248 // 3. Starting from the observation point, find candidate paths
6249 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6250 candidates.push_back((observation_point, vec![]));
6252 let mut found_plausible_candidate = false;
6254 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6255 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6256 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6257 found_plausible_candidate = true;
6258 break 'candidate_loop;
6262 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6263 for channel_id in &cur_node.channels {
6264 if let Some(channel_info) = network_channels.get(&channel_id) {
6265 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6266 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6267 if cur_path_cltv_deltas.iter().sum::<u32>()
6268 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6269 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6270 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6271 candidates.push_back((*next_id, new_path_cltv_deltas));
6279 path_plausibility.push(found_plausible_candidate);
6281 assert!(path_plausibility.iter().all(|x| *x));
6285 fn builds_correct_path_from_hops() {
6286 let (secp_ctx, network, _, _, logger) = build_graph();
6287 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6288 let network_graph = network.read_only();
6290 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6291 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6293 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6294 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6295 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6296 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6297 Arc::clone(&logger), &random_seed_bytes).unwrap();
6298 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6299 assert_eq!(hops.len(), route.paths[0].hops.len());
6300 for (idx, hop_pubkey) in hops.iter().enumerate() {
6301 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6306 fn avoids_saturating_channels() {
6307 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6308 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6309 let decay_params = ProbabilisticScoringDecayParameters::default();
6310 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6312 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6313 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6314 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6315 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6316 short_channel_id: 4,
6319 cltv_expiry_delta: (4 << 4) | 1,
6320 htlc_minimum_msat: 0,
6321 htlc_maximum_msat: 250_000_000,
6323 fee_proportional_millionths: 0,
6324 excess_data: Vec::new()
6326 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6327 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6328 short_channel_id: 13,
6331 cltv_expiry_delta: (13 << 4) | 1,
6332 htlc_minimum_msat: 0,
6333 htlc_maximum_msat: 250_000_000,
6335 fee_proportional_millionths: 0,
6336 excess_data: Vec::new()
6339 let config = UserConfig::default();
6340 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6341 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6342 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6343 // 100,000 sats is less than the available liquidity on each channel, set above.
6344 let route_params = RouteParameters::from_payment_params_and_value(
6345 payment_params, 100_000_000);
6346 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6347 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6348 assert_eq!(route.paths.len(), 2);
6349 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6350 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6353 #[cfg(not(feature = "no-std"))]
6354 pub(super) fn random_init_seed() -> u64 {
6355 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6356 use core::hash::{BuildHasher, Hasher};
6357 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6358 println!("Using seed of {}", seed);
6363 #[cfg(not(feature = "no-std"))]
6364 fn generate_routes() {
6365 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6367 let logger = ln_test_utils::TestLogger::new();
6368 let graph = match super::bench_utils::read_network_graph(&logger) {
6376 let params = ProbabilisticScoringFeeParameters::default();
6377 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6378 let features = super::Bolt11InvoiceFeatures::empty();
6380 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6384 #[cfg(not(feature = "no-std"))]
6385 fn generate_routes_mpp() {
6386 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6388 let logger = ln_test_utils::TestLogger::new();
6389 let graph = match super::bench_utils::read_network_graph(&logger) {
6397 let params = ProbabilisticScoringFeeParameters::default();
6398 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6399 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6401 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6405 #[cfg(not(feature = "no-std"))]
6406 fn generate_large_mpp_routes() {
6407 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6409 let logger = ln_test_utils::TestLogger::new();
6410 let graph = match super::bench_utils::read_network_graph(&logger) {
6418 let params = ProbabilisticScoringFeeParameters::default();
6419 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6420 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6422 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6426 fn honors_manual_penalties() {
6427 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6428 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6430 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6431 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6433 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6434 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6436 // First check set manual penalties are returned by the scorer.
6437 let usage = ChannelUsage {
6439 inflight_htlc_msat: 0,
6440 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6442 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6443 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6444 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
6446 // Then check we can get a normal route
6447 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6448 let route_params = RouteParameters::from_payment_params_and_value(
6449 payment_params, 100);
6450 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6451 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6452 assert!(route.is_ok());
6454 // Then check that we can't get a route if we ban an intermediate node.
6455 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6456 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6457 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6458 assert!(route.is_err());
6460 // Finally make sure we can route again, when we remove the ban.
6461 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6462 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6463 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6464 assert!(route.is_ok());
6468 fn abide_by_route_hint_max_htlc() {
6469 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6470 // params in the final route.
6471 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6472 let netgraph = network_graph.read_only();
6473 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6474 let scorer = ln_test_utils::TestScorer::new();
6475 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6476 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6477 let config = UserConfig::default();
6479 let max_htlc_msat = 50_000;
6480 let route_hint_1 = RouteHint(vec![RouteHintHop {
6481 src_node_id: nodes[2],
6482 short_channel_id: 42,
6485 proportional_millionths: 0,
6487 cltv_expiry_delta: 10,
6488 htlc_minimum_msat: None,
6489 htlc_maximum_msat: Some(max_htlc_msat),
6491 let dest_node_id = ln_test_utils::pubkey(42);
6492 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6493 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6494 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6496 // Make sure we'll error if our route hints don't have enough liquidity according to their
6497 // htlc_maximum_msat.
6498 let route_params = RouteParameters::from_payment_params_and_value(
6499 payment_params, max_htlc_msat + 1);
6500 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6501 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &(),
6504 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6505 } else { panic!(); }
6507 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6508 let mut route_hint_2 = route_hint_1.clone();
6509 route_hint_2.0[0].short_channel_id = 43;
6510 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6511 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6512 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6513 let route_params = RouteParameters::from_payment_params_and_value(
6514 payment_params, max_htlc_msat + 1);
6515 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
6516 &scorer, &(), &random_seed_bytes).unwrap();
6517 assert_eq!(route.paths.len(), 2);
6518 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6519 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6523 fn direct_channel_to_hints_with_max_htlc() {
6524 // Check that if we have a first hop channel peer that's connected to multiple provided route
6525 // hints, that we properly split the payment between the route hints if needed.
6526 let logger = Arc::new(ln_test_utils::TestLogger::new());
6527 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6528 let scorer = ln_test_utils::TestScorer::new();
6529 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6530 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6531 let config = UserConfig::default();
6533 let our_node_id = ln_test_utils::pubkey(42);
6534 let intermed_node_id = ln_test_utils::pubkey(43);
6535 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6537 let amt_msat = 900_000;
6538 let max_htlc_msat = 500_000;
6539 let route_hint_1 = RouteHint(vec![RouteHintHop {
6540 src_node_id: intermed_node_id,
6541 short_channel_id: 44,
6544 proportional_millionths: 0,
6546 cltv_expiry_delta: 10,
6547 htlc_minimum_msat: None,
6548 htlc_maximum_msat: Some(max_htlc_msat),
6550 src_node_id: intermed_node_id,
6551 short_channel_id: 45,
6554 proportional_millionths: 0,
6556 cltv_expiry_delta: 10,
6557 htlc_minimum_msat: None,
6558 // Check that later route hint max htlcs don't override earlier ones
6559 htlc_maximum_msat: Some(max_htlc_msat - 50),
6561 let mut route_hint_2 = route_hint_1.clone();
6562 route_hint_2.0[0].short_channel_id = 46;
6563 route_hint_2.0[1].short_channel_id = 47;
6564 let dest_node_id = ln_test_utils::pubkey(44);
6565 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6566 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6567 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6569 let route_params = RouteParameters::from_payment_params_and_value(
6570 payment_params, amt_msat);
6571 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6572 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
6573 &random_seed_bytes).unwrap();
6574 assert_eq!(route.paths.len(), 2);
6575 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6576 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6577 assert_eq!(route.get_total_amount(), amt_msat);
6579 // Re-run but with two first hop channels connected to the same route hint peers that must be
6581 let first_hops = vec![
6582 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6583 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6585 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6586 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
6587 &random_seed_bytes).unwrap();
6588 assert_eq!(route.paths.len(), 2);
6589 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6590 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6591 assert_eq!(route.get_total_amount(), amt_msat);
6593 // Make sure this works for blinded route hints.
6594 let blinded_path = BlindedPath {
6595 introduction_node_id: intermed_node_id,
6596 blinding_point: ln_test_utils::pubkey(42),
6598 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6599 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6602 let blinded_payinfo = BlindedPayInfo {
6604 fee_proportional_millionths: 0,
6605 htlc_minimum_msat: 1,
6606 htlc_maximum_msat: max_htlc_msat,
6607 cltv_expiry_delta: 10,
6608 features: BlindedHopFeatures::empty(),
6610 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6611 let payment_params = PaymentParameters::blinded(vec![
6612 (blinded_payinfo.clone(), blinded_path.clone()),
6613 (blinded_payinfo.clone(), blinded_path.clone())])
6614 .with_bolt12_features(bolt12_features).unwrap();
6615 let route_params = RouteParameters::from_payment_params_and_value(
6616 payment_params, amt_msat);
6617 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6618 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
6619 &random_seed_bytes).unwrap();
6620 assert_eq!(route.paths.len(), 2);
6621 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6622 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6623 assert_eq!(route.get_total_amount(), amt_msat);
6627 fn blinded_route_ser() {
6628 let blinded_path_1 = BlindedPath {
6629 introduction_node_id: ln_test_utils::pubkey(42),
6630 blinding_point: ln_test_utils::pubkey(43),
6632 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6633 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6636 let blinded_path_2 = BlindedPath {
6637 introduction_node_id: ln_test_utils::pubkey(46),
6638 blinding_point: ln_test_utils::pubkey(47),
6640 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6641 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6644 // (De)serialize a Route with 1 blinded path out of two total paths.
6645 let mut route = Route { paths: vec![Path {
6646 hops: vec![RouteHop {
6647 pubkey: ln_test_utils::pubkey(50),
6648 node_features: NodeFeatures::empty(),
6649 short_channel_id: 42,
6650 channel_features: ChannelFeatures::empty(),
6652 cltv_expiry_delta: 0,
6653 maybe_announced_channel: true,
6655 blinded_tail: Some(BlindedTail {
6656 hops: blinded_path_1.blinded_hops,
6657 blinding_point: blinded_path_1.blinding_point,
6658 excess_final_cltv_expiry_delta: 40,
6659 final_value_msat: 100,
6661 hops: vec![RouteHop {
6662 pubkey: ln_test_utils::pubkey(51),
6663 node_features: NodeFeatures::empty(),
6664 short_channel_id: 43,
6665 channel_features: ChannelFeatures::empty(),
6667 cltv_expiry_delta: 0,
6668 maybe_announced_channel: true,
6669 }], blinded_tail: None }],
6672 let encoded_route = route.encode();
6673 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6674 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6675 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6677 // (De)serialize a Route with two paths, each containing a blinded tail.
6678 route.paths[1].blinded_tail = Some(BlindedTail {
6679 hops: blinded_path_2.blinded_hops,
6680 blinding_point: blinded_path_2.blinding_point,
6681 excess_final_cltv_expiry_delta: 41,
6682 final_value_msat: 101,
6684 let encoded_route = route.encode();
6685 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6686 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6687 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6691 fn blinded_path_inflight_processing() {
6692 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6693 // account for the blinded tail's final amount_msat.
6694 let mut inflight_htlcs = InFlightHtlcs::new();
6695 let blinded_path = BlindedPath {
6696 introduction_node_id: ln_test_utils::pubkey(43),
6697 blinding_point: ln_test_utils::pubkey(48),
6698 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
6701 hops: vec![RouteHop {
6702 pubkey: ln_test_utils::pubkey(42),
6703 node_features: NodeFeatures::empty(),
6704 short_channel_id: 42,
6705 channel_features: ChannelFeatures::empty(),
6707 cltv_expiry_delta: 0,
6708 maybe_announced_channel: false,
6711 pubkey: blinded_path.introduction_node_id,
6712 node_features: NodeFeatures::empty(),
6713 short_channel_id: 43,
6714 channel_features: ChannelFeatures::empty(),
6716 cltv_expiry_delta: 0,
6717 maybe_announced_channel: false,
6719 blinded_tail: Some(BlindedTail {
6720 hops: blinded_path.blinded_hops,
6721 blinding_point: blinded_path.blinding_point,
6722 excess_final_cltv_expiry_delta: 0,
6723 final_value_msat: 200,
6726 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
6727 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
6728 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
6732 fn blinded_path_cltv_shadow_offset() {
6733 // Make sure we add a shadow offset when sending to blinded paths.
6734 let blinded_path = BlindedPath {
6735 introduction_node_id: ln_test_utils::pubkey(43),
6736 blinding_point: ln_test_utils::pubkey(44),
6738 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
6739 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
6742 let mut route = Route { paths: vec![Path {
6743 hops: vec![RouteHop {
6744 pubkey: ln_test_utils::pubkey(42),
6745 node_features: NodeFeatures::empty(),
6746 short_channel_id: 42,
6747 channel_features: ChannelFeatures::empty(),
6749 cltv_expiry_delta: 0,
6750 maybe_announced_channel: false,
6753 pubkey: blinded_path.introduction_node_id,
6754 node_features: NodeFeatures::empty(),
6755 short_channel_id: 43,
6756 channel_features: ChannelFeatures::empty(),
6758 cltv_expiry_delta: 0,
6759 maybe_announced_channel: false,
6762 blinded_tail: Some(BlindedTail {
6763 hops: blinded_path.blinded_hops,
6764 blinding_point: blinded_path.blinding_point,
6765 excess_final_cltv_expiry_delta: 0,
6766 final_value_msat: 200,
6768 }], route_params: None};
6770 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
6771 let (_, network_graph, _, _, _) = build_line_graph();
6772 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
6773 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
6774 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
6778 fn simple_blinded_route_hints() {
6779 do_simple_blinded_route_hints(1);
6780 do_simple_blinded_route_hints(2);
6781 do_simple_blinded_route_hints(3);
6784 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
6785 // Check that we can generate a route to a blinded path with the expected hops.
6786 let (secp_ctx, network, _, _, logger) = build_graph();
6787 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6788 let network_graph = network.read_only();
6790 let scorer = ln_test_utils::TestScorer::new();
6791 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6792 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6794 let mut blinded_path = BlindedPath {
6795 introduction_node_id: nodes[2],
6796 blinding_point: ln_test_utils::pubkey(42),
6797 blinded_hops: Vec::with_capacity(num_blinded_hops),
6799 for i in 0..num_blinded_hops {
6800 blinded_path.blinded_hops.push(
6801 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
6804 let blinded_payinfo = BlindedPayInfo {
6806 fee_proportional_millionths: 500,
6807 htlc_minimum_msat: 1000,
6808 htlc_maximum_msat: 100_000_000,
6809 cltv_expiry_delta: 15,
6810 features: BlindedHopFeatures::empty(),
6813 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
6814 let route_params = RouteParameters::from_payment_params_and_value(
6815 payment_params, 1001);
6816 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6817 &scorer, &(), &random_seed_bytes).unwrap();
6818 assert_eq!(route.paths.len(), 1);
6819 assert_eq!(route.paths[0].hops.len(), 2);
6821 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
6822 assert_eq!(tail.hops, blinded_path.blinded_hops);
6823 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
6824 assert_eq!(tail.final_value_msat, 1001);
6826 let final_hop = route.paths[0].hops.last().unwrap();
6827 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
6828 if tail.hops.len() > 1 {
6829 assert_eq!(final_hop.fee_msat,
6830 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
6831 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
6833 assert_eq!(final_hop.fee_msat, 0);
6834 assert_eq!(final_hop.cltv_expiry_delta, 0);
6839 fn blinded_path_routing_errors() {
6840 // Check that we can generate a route to a blinded path with the expected hops.
6841 let (secp_ctx, network, _, _, logger) = build_graph();
6842 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6843 let network_graph = network.read_only();
6845 let scorer = ln_test_utils::TestScorer::new();
6846 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6847 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6849 let mut invalid_blinded_path = BlindedPath {
6850 introduction_node_id: nodes[2],
6851 blinding_point: ln_test_utils::pubkey(42),
6853 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
6856 let blinded_payinfo = BlindedPayInfo {
6858 fee_proportional_millionths: 500,
6859 htlc_minimum_msat: 1000,
6860 htlc_maximum_msat: 100_000_000,
6861 cltv_expiry_delta: 15,
6862 features: BlindedHopFeatures::empty(),
6865 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
6866 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
6867 let payment_params = PaymentParameters::blinded(vec![
6868 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
6869 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
6870 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6871 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6872 &scorer, &(), &random_seed_bytes)
6874 Err(LightningError { err, .. }) => {
6875 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
6877 _ => panic!("Expected error")
6880 invalid_blinded_path.introduction_node_id = our_id;
6881 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
6882 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6883 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6884 &(), &random_seed_bytes)
6886 Err(LightningError { err, .. }) => {
6887 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
6889 _ => panic!("Expected error")
6892 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
6893 invalid_blinded_path.blinded_hops.clear();
6894 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
6895 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6896 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6897 &(), &random_seed_bytes)
6899 Err(LightningError { err, .. }) => {
6900 assert_eq!(err, "0-hop blinded path provided");
6902 _ => panic!("Expected error")
6907 fn matching_intro_node_paths_provided() {
6908 // Check that if multiple blinded paths with the same intro node are provided in payment
6909 // parameters, we'll return the correct paths in the resulting MPP route.
6910 let (secp_ctx, network, _, _, logger) = build_graph();
6911 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6912 let network_graph = network.read_only();
6914 let scorer = ln_test_utils::TestScorer::new();
6915 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6916 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6917 let config = UserConfig::default();
6919 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6920 let blinded_path_1 = BlindedPath {
6921 introduction_node_id: nodes[2],
6922 blinding_point: ln_test_utils::pubkey(42),
6924 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6925 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6928 let blinded_payinfo_1 = BlindedPayInfo {
6930 fee_proportional_millionths: 0,
6931 htlc_minimum_msat: 0,
6932 htlc_maximum_msat: 30_000,
6933 cltv_expiry_delta: 0,
6934 features: BlindedHopFeatures::empty(),
6937 let mut blinded_path_2 = blinded_path_1.clone();
6938 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
6939 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
6940 blinded_payinfo_2.htlc_maximum_msat = 70_000;
6942 let blinded_hints = vec![
6943 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
6944 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
6946 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
6947 .with_bolt12_features(bolt12_features.clone()).unwrap();
6949 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
6950 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6951 &scorer, &(), &random_seed_bytes).unwrap();
6952 assert_eq!(route.paths.len(), 2);
6953 let mut total_amount_paid_msat = 0;
6954 for path in route.paths.into_iter() {
6955 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6956 if let Some(bt) = &path.blinded_tail {
6957 assert_eq!(bt.blinding_point,
6958 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
6959 .map(|(_, bp)| bp.blinding_point).unwrap());
6960 } else { panic!(); }
6961 total_amount_paid_msat += path.final_value_msat();
6963 assert_eq!(total_amount_paid_msat, 100_000);
6967 fn direct_to_intro_node() {
6968 // This previously caused a debug panic in the router when asserting
6969 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
6970 // direct channels we failed to account for the fee charged for use of the blinded path.
6973 // node0 -1(1)2 - node1
6974 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
6975 // doesn't account for the blinded path fee.
6977 let secp_ctx = Secp256k1::new();
6978 let logger = Arc::new(ln_test_utils::TestLogger::new());
6979 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6980 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
6981 let scorer = ln_test_utils::TestScorer::new();
6982 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6983 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6985 let amt_msat = 10_000_000;
6986 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
6987 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
6988 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6989 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6990 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6991 short_channel_id: 1,
6994 cltv_expiry_delta: 42,
6995 htlc_minimum_msat: 1_000,
6996 htlc_maximum_msat: 10_000_000,
6998 fee_proportional_millionths: 0,
6999 excess_data: Vec::new()
7001 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7002 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
7003 short_channel_id: 1,
7006 cltv_expiry_delta: 42,
7007 htlc_minimum_msat: 1_000,
7008 htlc_maximum_msat: 10_000_000,
7010 fee_proportional_millionths: 0,
7011 excess_data: Vec::new()
7013 let first_hops = vec![
7014 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7016 let blinded_path = BlindedPath {
7017 introduction_node_id: nodes[1],
7018 blinding_point: ln_test_utils::pubkey(42),
7020 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7021 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7024 let blinded_payinfo = BlindedPayInfo {
7025 fee_base_msat: 1000,
7026 fee_proportional_millionths: 0,
7027 htlc_minimum_msat: 1000,
7028 htlc_maximum_msat: MAX_VALUE_MSAT,
7029 cltv_expiry_delta: 0,
7030 features: BlindedHopFeatures::empty(),
7032 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7034 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7036 let netgraph = network_graph.read_only();
7037 let route_params = RouteParameters::from_payment_params_and_value(
7038 payment_params.clone(), amt_msat);
7039 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7040 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
7041 &random_seed_bytes) {
7042 assert_eq!(err, "Failed to find a path to the given destination");
7043 } else { panic!("Expected error") }
7045 // Sending an exact amount accounting for the blinded path fee works.
7046 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7047 let route_params = RouteParameters::from_payment_params_and_value(
7048 payment_params, amt_minus_blinded_path_fee);
7049 let route = get_route(&nodes[0], &route_params, &netgraph,
7050 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
7051 &random_seed_bytes).unwrap();
7052 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7053 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7057 fn direct_to_matching_intro_nodes() {
7058 // This previously caused us to enter `unreachable` code in the following situation:
7059 // 1. We add a route candidate for intro_node contributing a high amount
7060 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7061 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7062 // amount, and update our route candidate for intro_node for the lower amount
7063 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7064 // lower contribution amount, but fail (this was previously caused by failure to account for
7065 // blinded path fees when adding first_hop<>intro_node candidates)
7066 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7067 // candidate still thinks its path is contributing the original higher amount. This caused us
7068 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7070 let secp_ctx = Secp256k1::new();
7071 let logger = Arc::new(ln_test_utils::TestLogger::new());
7072 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7073 let scorer = ln_test_utils::TestScorer::new();
7074 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7075 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7076 let config = UserConfig::default();
7078 // Values are taken from the fuzz input that uncovered this panic.
7079 let amt_msat = 21_7020_5185_1403_2640;
7080 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7081 let first_hops = vec![
7082 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7083 18446744073709551615)];
7085 let blinded_path = BlindedPath {
7086 introduction_node_id: nodes[1],
7087 blinding_point: ln_test_utils::pubkey(42),
7089 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7090 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7093 let blinded_payinfo = BlindedPayInfo {
7094 fee_base_msat: 5046_2720,
7095 fee_proportional_millionths: 0,
7096 htlc_minimum_msat: 4503_5996_2737_0496,
7097 htlc_maximum_msat: 45_0359_9627_3704_9600,
7098 cltv_expiry_delta: 0,
7099 features: BlindedHopFeatures::empty(),
7101 let mut blinded_hints = vec![
7102 (blinded_payinfo.clone(), blinded_path.clone()),
7103 (blinded_payinfo.clone(), blinded_path.clone()),
7105 blinded_hints[1].0.fee_base_msat = 419_4304;
7106 blinded_hints[1].0.fee_proportional_millionths = 257;
7107 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7108 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7109 blinded_hints[1].0.cltv_expiry_delta = 0;
7111 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7112 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7113 .with_bolt12_features(bolt12_features.clone()).unwrap();
7115 let netgraph = network_graph.read_only();
7116 let route_params = RouteParameters::from_payment_params_and_value(
7117 payment_params, amt_msat);
7118 let route = get_route(&nodes[0], &route_params, &netgraph,
7119 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer, &(),
7120 &random_seed_bytes).unwrap();
7121 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7122 assert_eq!(route.get_total_amount(), amt_msat);
7126 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
7127 pub(crate) mod bench_utils {
7131 use bitcoin::hashes::Hash;
7132 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
7134 use crate::chain::transaction::OutPoint;
7135 use crate::routing::scoring::ScoreUpdate;
7136 use crate::sign::{EntropySource, KeysManager};
7137 use crate::ln::ChannelId;
7138 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
7139 use crate::ln::features::Bolt11InvoiceFeatures;
7140 use crate::routing::gossip::NetworkGraph;
7141 use crate::util::config::UserConfig;
7142 use crate::util::ser::ReadableArgs;
7143 use crate::util::test_utils::TestLogger;
7145 /// Tries to open a network graph file, or panics with a URL to fetch it.
7146 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
7147 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
7148 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
7149 .or_else(|_| { // Fall back to guessing based on the binary location
7150 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
7151 let mut path = std::env::current_exe().unwrap();
7152 path.pop(); // lightning-...
7154 path.pop(); // debug
7155 path.pop(); // target
7156 path.push("lightning");
7157 path.push("net_graph-2023-01-18.bin");
7160 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
7161 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
7162 let mut path = std::env::current_exe().unwrap();
7163 path.pop(); // bench...
7165 path.pop(); // debug
7166 path.pop(); // target
7167 path.pop(); // bench
7168 path.push("lightning");
7169 path.push("net_graph-2023-01-18.bin");
7172 .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");
7173 #[cfg(require_route_graph_test)]
7174 return Ok(res.unwrap());
7175 #[cfg(not(require_route_graph_test))]
7179 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
7180 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
7183 pub(crate) fn payer_pubkey() -> PublicKey {
7184 let secp_ctx = Secp256k1::new();
7185 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
7189 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
7191 channel_id: ChannelId::new_zero(),
7192 counterparty: ChannelCounterparty {
7193 features: channelmanager::provided_init_features(&UserConfig::default()),
7195 unspendable_punishment_reserve: 0,
7196 forwarding_info: None,
7197 outbound_htlc_minimum_msat: None,
7198 outbound_htlc_maximum_msat: None,
7200 funding_txo: Some(OutPoint {
7201 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
7204 short_channel_id: Some(1),
7205 inbound_scid_alias: None,
7206 outbound_scid_alias: None,
7207 channel_value_satoshis: 10_000_000_000,
7209 outbound_capacity_msat: 10_000_000_000,
7210 next_outbound_htlc_minimum_msat: 0,
7211 next_outbound_htlc_limit_msat: 10_000_000_000,
7212 inbound_capacity_msat: 0,
7213 unspendable_punishment_reserve: None,
7214 confirmations_required: None,
7215 confirmations: None,
7216 force_close_spend_delay: None,
7218 is_channel_ready: true,
7221 inbound_htlc_minimum_msat: None,
7222 inbound_htlc_maximum_msat: None,
7224 feerate_sat_per_1000_weight: None,
7225 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
7229 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
7230 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
7231 starting_amount: u64, route_count: usize,
7232 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
7233 let payer = payer_pubkey();
7234 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7235 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7237 let nodes = graph.read_only().nodes().clone();
7238 let mut route_endpoints = Vec::new();
7239 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
7240 // with some routes we picked being un-routable.
7241 for _ in 0..route_count * 3 / 2 {
7243 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7244 let src = PublicKey::from_slice(nodes.unordered_keys()
7245 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
7246 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7247 let dst = PublicKey::from_slice(nodes.unordered_keys()
7248 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
7249 let params = PaymentParameters::from_node_id(dst, 42)
7250 .with_bolt11_features(features.clone()).unwrap();
7251 let first_hop = first_hop(src);
7252 let amt_msat = starting_amount + seed % 1_000_000;
7253 let route_params = RouteParameters::from_payment_params_and_value(
7254 params.clone(), amt_msat);
7256 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
7257 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
7259 // ...and seed the scorer with success and failure data...
7260 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7261 let mut score_amt = seed % 1_000_000_000;
7263 // Generate fail/success paths for a wider range of potential amounts with
7264 // MPP enabled to give us a chance to apply penalties for more potential
7266 let mpp_features = channelmanager::provided_invoice_features(&UserConfig::default());
7267 let params = PaymentParameters::from_node_id(dst, 42)
7268 .with_bolt11_features(mpp_features).unwrap();
7269 let route_params = RouteParameters::from_payment_params_and_value(
7270 params.clone(), score_amt);
7271 let route_res = get_route(&payer, &route_params, &graph.read_only(),
7272 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
7273 &random_seed_bytes);
7274 if let Ok(route) = route_res {
7275 for path in route.paths {
7276 if seed & 0x80 == 0 {
7277 scorer.payment_path_successful(&path);
7279 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
7280 scorer.payment_path_failed(&path, short_channel_id);
7282 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7286 // If we couldn't find a path with a higer amount, reduce and try again.
7290 route_endpoints.push((first_hop, params, amt_msat));
7296 // Because we've changed channel scores, it's possible we'll take different routes to the
7297 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
7298 // requires a too-high CLTV delta.
7299 route_endpoints.retain(|(first_hop, params, amt_msat)| {
7300 let route_params = RouteParameters::from_payment_params_and_value(
7301 params.clone(), *amt_msat);
7302 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
7303 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
7305 route_endpoints.truncate(route_count);
7306 assert_eq!(route_endpoints.len(), route_count);
7314 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
7315 use crate::sign::{EntropySource, KeysManager};
7316 use crate::ln::channelmanager;
7317 use crate::ln::features::Bolt11InvoiceFeatures;
7318 use crate::routing::gossip::NetworkGraph;
7319 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
7320 use crate::util::config::UserConfig;
7321 use crate::util::logger::{Logger, Record};
7322 use crate::util::test_utils::TestLogger;
7324 use criterion::Criterion;
7326 struct DummyLogger {}
7327 impl Logger for DummyLogger {
7328 fn log(&self, _record: &Record) {}
7331 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7332 let logger = TestLogger::new();
7333 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7334 let scorer = FixedPenaltyScorer::with_penalty(0);
7335 generate_routes(bench, &network_graph, scorer, &(), Bolt11InvoiceFeatures::empty(), 0,
7336 "generate_routes_with_zero_penalty_scorer");
7339 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7340 let logger = TestLogger::new();
7341 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7342 let scorer = FixedPenaltyScorer::with_penalty(0);
7343 generate_routes(bench, &network_graph, scorer, &(),
7344 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7345 "generate_mpp_routes_with_zero_penalty_scorer");
7348 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7349 let logger = TestLogger::new();
7350 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7351 let params = ProbabilisticScoringFeeParameters::default();
7352 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7353 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
7354 "generate_routes_with_probabilistic_scorer");
7357 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7358 let logger = TestLogger::new();
7359 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7360 let params = ProbabilisticScoringFeeParameters::default();
7361 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7362 generate_routes(bench, &network_graph, scorer, ¶ms,
7363 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7364 "generate_mpp_routes_with_probabilistic_scorer");
7367 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7368 let logger = TestLogger::new();
7369 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7370 let params = ProbabilisticScoringFeeParameters::default();
7371 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7372 generate_routes(bench, &network_graph, scorer, ¶ms,
7373 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
7374 "generate_large_mpp_routes_with_probabilistic_scorer");
7377 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
7378 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
7379 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
7380 bench_name: &'static str,
7382 let payer = bench_utils::payer_pubkey();
7383 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7384 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7386 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
7387 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
7389 // ...then benchmark finding paths between the nodes we learned.
7391 bench.bench_function(bench_name, |b| b.iter(|| {
7392 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
7393 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
7394 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
7395 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());