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.saturating_add(used_liquidity),
146 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
148 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
153 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
154 /// in-use channel liquidity.
156 pub struct InFlightHtlcs(
157 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
158 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
159 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
161 HashMap<(u64, bool), u64>
165 /// Constructs an empty `InFlightHtlcs`.
166 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
168 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
169 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
170 if path.hops.is_empty() { return };
172 let mut cumulative_msat = 0;
173 if let Some(tail) = &path.blinded_tail {
174 cumulative_msat += tail.final_value_msat;
177 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
178 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
179 // the router excludes the payer node. In the following lines, the payer's information is
180 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
181 // in our sliding window of two.
182 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
183 .map(|hop| hop.pubkey)
184 .chain(core::iter::once(payer_node_id));
186 // Taking the reversed vector from above, we zip it with just the reversed hops list to
187 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
188 // the total amount sent.
189 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
190 cumulative_msat += next_hop.fee_msat;
192 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
193 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
194 .or_insert(cumulative_msat);
198 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
200 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
202 .entry((channel_scid, source < target))
203 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
204 .or_insert(used_msat);
207 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
209 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
210 self.0.get(&(channel_scid, source < target)).map(|v| *v)
214 impl Writeable for InFlightHtlcs {
215 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
218 impl Readable for InFlightHtlcs {
219 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
220 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
221 Ok(Self(infight_map))
225 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
226 /// that leads to it.
227 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
228 pub struct RouteHop {
229 /// The node_id of the node at this hop.
230 pub pubkey: PublicKey,
231 /// The node_announcement features of the node at this hop. For the last hop, these may be
232 /// amended to match the features present in the invoice this node generated.
233 pub node_features: NodeFeatures,
234 /// The channel that should be used from the previous hop to reach this node.
235 pub short_channel_id: u64,
236 /// The channel_announcement features of the channel that should be used from the previous hop
237 /// to reach this node.
238 pub channel_features: ChannelFeatures,
239 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
240 /// If this is the last hop in [`Path::hops`]:
241 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
242 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
244 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
246 /// The CLTV delta added for this hop.
247 /// If this is the last hop in [`Path::hops`]:
248 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
249 /// * otherwise, this is the CLTV delta expected at the destination
251 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
252 pub cltv_expiry_delta: u32,
253 /// Indicates whether this hop is possibly announced in the public network graph.
255 /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
256 /// either know for sure it's announced in the public graph, or if any public channels exist
257 /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
258 /// the channel to be unannounced.
260 /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
261 pub maybe_announced_channel: bool,
264 impl_writeable_tlv_based!(RouteHop, {
265 (0, pubkey, required),
266 (1, maybe_announced_channel, (default_value, true)),
267 (2, node_features, required),
268 (4, short_channel_id, required),
269 (6, channel_features, required),
270 (8, fee_msat, required),
271 (10, cltv_expiry_delta, required),
274 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
275 /// their [`Bolt12Invoice`].
277 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
278 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
279 pub struct BlindedTail {
280 /// The hops of the [`BlindedPath`] provided by the recipient.
282 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
283 pub hops: Vec<BlindedHop>,
284 /// The blinding point of the [`BlindedPath`] provided by the recipient.
286 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
287 pub blinding_point: PublicKey,
288 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
289 /// inferring the destination. May be 0.
290 pub excess_final_cltv_expiry_delta: u32,
291 /// The total amount paid on this [`Path`], excluding the fees.
292 pub final_value_msat: u64,
295 impl_writeable_tlv_based!(BlindedTail, {
296 (0, hops, required_vec),
297 (2, blinding_point, required),
298 (4, excess_final_cltv_expiry_delta, required),
299 (6, final_value_msat, required),
302 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
303 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
304 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
306 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
307 pub hops: Vec<RouteHop>,
308 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
309 pub blinded_tail: Option<BlindedTail>,
313 /// Gets the fees for a given path, excluding any excess paid to the recipient.
314 pub fn fee_msat(&self) -> u64 {
315 match &self.blinded_tail {
316 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
318 // Do not count last hop of each path since that's the full value of the payment
319 self.hops.split_last().map_or(0,
320 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
325 /// Gets the total amount paid on this [`Path`], excluding the fees.
326 pub fn final_value_msat(&self) -> u64 {
327 match &self.blinded_tail {
328 Some(blinded_tail) => blinded_tail.final_value_msat,
329 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
333 /// Gets the final hop's CLTV expiry delta.
334 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
335 match &self.blinded_tail {
337 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
342 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
343 /// it can take multiple paths. Each path is composed of one or more hops through the network.
344 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
346 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
347 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
349 pub paths: Vec<Path>,
350 /// The `route_params` parameter passed to [`find_route`].
352 /// This is used by `ChannelManager` to track information which may be required for retries.
354 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
355 pub route_params: Option<RouteParameters>,
359 /// Returns the total amount of fees paid on this [`Route`].
361 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
362 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
363 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
365 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
366 pub fn get_total_fees(&self) -> u64 {
367 let overpaid_value_msat = self.route_params.as_ref()
368 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
369 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
372 /// Returns the total amount paid on this [`Route`], excluding the fees.
374 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
375 /// we had to reach the [`htlc_minimum_msat`] limits.
377 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
378 pub fn get_total_amount(&self) -> u64 {
379 self.paths.iter().map(|path| path.final_value_msat()).sum()
383 impl fmt::Display for Route {
384 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
385 log_route!(self).fmt(f)
389 const SERIALIZATION_VERSION: u8 = 1;
390 const MIN_SERIALIZATION_VERSION: u8 = 1;
392 impl Writeable for Route {
393 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
394 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
395 (self.paths.len() as u64).write(writer)?;
396 let mut blinded_tails = Vec::new();
397 for path in self.paths.iter() {
398 (path.hops.len() as u8).write(writer)?;
399 for (idx, hop) in path.hops.iter().enumerate() {
401 if let Some(blinded_tail) = &path.blinded_tail {
402 if blinded_tails.is_empty() {
403 blinded_tails = Vec::with_capacity(path.hops.len());
405 blinded_tails.push(None);
408 blinded_tails.push(Some(blinded_tail));
409 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
412 write_tlv_fields!(writer, {
413 // For compatibility with LDK versions prior to 0.0.117, we take the individual
414 // RouteParameters' fields and reconstruct them on read.
415 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
416 (2, blinded_tails, optional_vec),
417 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
418 (5, self.route_params.as_ref().map(|p| p.max_total_routing_fee_msat), option),
424 impl Readable for Route {
425 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
426 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
427 let path_count: u64 = Readable::read(reader)?;
428 if path_count == 0 { return Err(DecodeError::InvalidValue); }
429 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
430 let mut min_final_cltv_expiry_delta = u32::max_value();
431 for _ in 0..path_count {
432 let hop_count: u8 = Readable::read(reader)?;
433 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
434 for _ in 0..hop_count {
435 hops.push(Readable::read(reader)?);
437 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
438 min_final_cltv_expiry_delta =
439 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
440 paths.push(Path { hops, blinded_tail: None });
442 _init_and_read_len_prefixed_tlv_fields!(reader, {
443 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
444 (2, blinded_tails, optional_vec),
445 (3, final_value_msat, option),
446 (5, max_total_routing_fee_msat, option)
448 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
449 if blinded_tails.len() != 0 {
450 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
451 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
452 path.blinded_tail = blinded_tail_opt;
456 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
457 let route_params = match (payment_params, final_value_msat) {
458 (Some(payment_params), Some(final_value_msat)) => {
459 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
464 Ok(Route { paths, route_params })
468 /// Parameters needed to find a [`Route`].
470 /// Passed to [`find_route`] and [`build_route_from_hops`].
471 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
472 pub struct RouteParameters {
473 /// The parameters of the failed payment path.
474 pub payment_params: PaymentParameters,
476 /// The amount in msats sent on the failed payment path.
477 pub final_value_msat: u64,
479 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
481 /// This limit also applies to the total fees that may arise while retrying failed payment
484 /// Note that values below a few sats may result in some paths being spuriously ignored.
485 pub max_total_routing_fee_msat: Option<u64>,
488 impl RouteParameters {
489 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
491 /// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
492 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
493 Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
497 impl Writeable for RouteParameters {
498 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
499 write_tlv_fields!(writer, {
500 (0, self.payment_params, required),
501 (1, self.max_total_routing_fee_msat, option),
502 (2, self.final_value_msat, required),
503 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
504 // `RouteParameters` directly. For compatibility, we write it here.
505 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
511 impl Readable for RouteParameters {
512 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
513 _init_and_read_len_prefixed_tlv_fields!(reader, {
514 (0, payment_params, (required: ReadableArgs, 0)),
515 (1, max_total_routing_fee_msat, option),
516 (2, final_value_msat, required),
517 (4, final_cltv_delta, option),
519 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
520 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
521 if final_cltv_expiry_delta == &0 {
522 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
527 final_value_msat: final_value_msat.0.unwrap(),
528 max_total_routing_fee_msat,
533 /// Maximum total CTLV difference we allow for a full payment path.
534 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
536 /// Maximum number of paths we allow an (MPP) payment to have.
537 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
538 // limits, but for now more than 10 paths likely carries too much one-path failure.
539 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
541 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
543 // The median hop CLTV expiry delta currently seen in the network.
544 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
546 // During routing, we only consider paths shorter than our maximum length estimate.
547 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
548 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
549 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
551 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
552 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
553 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
554 // (payment_secret and total_msat) = 93 bytes for the final hop.
555 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
556 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
557 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
559 /// Information used to route a payment.
560 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
561 pub struct PaymentParameters {
562 /// Information about the payee, such as their features and route hints for their channels.
565 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
566 pub expiry_time: Option<u64>,
568 /// The maximum total CLTV delta we accept for the route.
569 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
570 pub max_total_cltv_expiry_delta: u32,
572 /// The maximum number of paths that may be used by (MPP) payments.
573 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
574 pub max_path_count: u8,
576 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
577 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
578 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
579 /// increasing failure probability for those paths.
581 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
582 /// restriction have been found. While paths which meet this criteria will be searched for, it
583 /// is ultimately up to the scorer to select them over other paths.
585 /// A value of 0 will allow payments up to and including a channel's total announced usable
586 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
589 pub max_channel_saturation_power_of_half: u8,
591 /// A list of SCIDs which this payment was previously attempted over and which caused the
592 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
594 pub previously_failed_channels: Vec<u64>,
597 impl Writeable for PaymentParameters {
598 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
599 let mut clear_hints = &vec![];
600 let mut blinded_hints = &vec![];
602 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
603 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
605 write_tlv_fields!(writer, {
606 (0, self.payee.node_id(), option),
607 (1, self.max_total_cltv_expiry_delta, required),
608 (2, self.payee.features(), option),
609 (3, self.max_path_count, required),
610 (4, *clear_hints, required_vec),
611 (5, self.max_channel_saturation_power_of_half, required),
612 (6, self.expiry_time, option),
613 (7, self.previously_failed_channels, required_vec),
614 (8, *blinded_hints, optional_vec),
615 (9, self.payee.final_cltv_expiry_delta(), option),
621 impl ReadableArgs<u32> for PaymentParameters {
622 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
623 _init_and_read_len_prefixed_tlv_fields!(reader, {
624 (0, payee_pubkey, option),
625 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
626 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
627 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
628 (4, clear_route_hints, required_vec),
629 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
630 (6, expiry_time, option),
631 (7, previously_failed_channels, optional_vec),
632 (8, blinded_route_hints, optional_vec),
633 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
635 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
636 let payee = if blinded_route_hints.len() != 0 {
637 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
639 route_hints: blinded_route_hints,
640 features: features.and_then(|f: Features| f.bolt12()),
644 route_hints: clear_route_hints,
645 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
646 features: features.and_then(|f| f.bolt11()),
647 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
651 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
652 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
654 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
656 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
662 impl PaymentParameters {
663 /// Creates a payee with the node id of the given `pubkey`.
665 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
667 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
669 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
671 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
672 max_path_count: DEFAULT_MAX_PATH_COUNT,
673 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
674 previously_failed_channels: Vec::new(),
678 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
680 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
683 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
684 /// whether your router will be allowed to find a multi-part route for this payment. If you
685 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
686 /// [`RecipientOnionFields::secret_only`].
688 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
689 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
690 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
691 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
692 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
695 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
696 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
697 /// [`PaymentParameters::expiry_time`].
698 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
699 Self::blinded(invoice.payment_paths().to_vec())
700 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
701 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
704 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
705 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
707 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
709 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
710 max_path_count: DEFAULT_MAX_PATH_COUNT,
711 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
712 previously_failed_channels: Vec::new(),
716 /// Includes the payee's features. Errors if the parameters were not initialized with
717 /// [`PaymentParameters::from_bolt12_invoice`].
719 /// This is not exported to bindings users since bindings don't support move semantics
720 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
722 Payee::Clear { .. } => Err(()),
723 Payee::Blinded { route_hints, .. } =>
724 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
728 /// Includes the payee's features. Errors if the parameters were initialized with
729 /// [`PaymentParameters::from_bolt12_invoice`].
731 /// This is not exported to bindings users since bindings don't support move semantics
732 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
734 Payee::Blinded { .. } => Err(()),
735 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
737 payee: Payee::Clear {
738 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
744 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
745 /// [`PaymentParameters::from_bolt12_invoice`].
747 /// This is not exported to bindings users since bindings don't support move semantics
748 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
750 Payee::Blinded { .. } => Err(()),
751 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
753 payee: Payee::Clear {
754 route_hints, node_id, features, final_cltv_expiry_delta,
760 /// Includes a payment expiration in seconds relative to the UNIX epoch.
762 /// This is not exported to bindings users since bindings don't support move semantics
763 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
764 Self { expiry_time: Some(expiry_time), ..self }
767 /// Includes a limit for the total CLTV expiry delta which is considered during routing
769 /// This is not exported to bindings users since bindings don't support move semantics
770 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
771 Self { max_total_cltv_expiry_delta, ..self }
774 /// Includes a limit for the maximum number of payment paths that may be used.
776 /// This is not exported to bindings users since bindings don't support move semantics
777 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
778 Self { max_path_count, ..self }
781 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
782 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
784 /// This is not exported to bindings users since bindings don't support move semantics
785 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
786 Self { max_channel_saturation_power_of_half, ..self }
790 /// The recipient of a payment, differing based on whether they've hidden their identity with route
792 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
794 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
795 /// will be included in the final [`Route`].
797 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
799 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
800 /// Features supported by the payee.
802 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
804 features: Option<Bolt12InvoiceFeatures>,
806 /// The recipient included these route hints in their BOLT11 invoice.
808 /// The node id of the payee.
810 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
811 route_hints: Vec<RouteHint>,
812 /// Features supported by the payee.
814 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
815 /// does not contain any features.
817 /// [`for_keysend`]: PaymentParameters::for_keysend
818 features: Option<Bolt11InvoiceFeatures>,
819 /// The minimum CLTV delta at the end of the route. This value must not be zero.
820 final_cltv_expiry_delta: u32,
825 fn node_id(&self) -> Option<PublicKey> {
827 Self::Clear { node_id, .. } => Some(*node_id),
831 fn node_features(&self) -> Option<NodeFeatures> {
833 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
834 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
837 fn supports_basic_mpp(&self) -> bool {
839 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
840 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
843 fn features(&self) -> Option<FeaturesRef> {
845 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
846 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
849 fn final_cltv_expiry_delta(&self) -> Option<u32> {
851 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
855 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
857 Self::Blinded { route_hints, .. } => &route_hints[..],
858 Self::Clear { .. } => &[]
862 fn unblinded_route_hints(&self) -> &[RouteHint] {
864 Self::Blinded { .. } => &[],
865 Self::Clear { route_hints, .. } => &route_hints[..]
870 enum FeaturesRef<'a> {
871 Bolt11(&'a Bolt11InvoiceFeatures),
872 Bolt12(&'a Bolt12InvoiceFeatures),
875 Bolt11(Bolt11InvoiceFeatures),
876 Bolt12(Bolt12InvoiceFeatures),
880 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
882 Self::Bolt12(f) => Some(f),
886 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
888 Self::Bolt11(f) => Some(f),
894 impl<'a> Writeable for FeaturesRef<'a> {
895 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
897 Self::Bolt11(f) => Ok(f.write(w)?),
898 Self::Bolt12(f) => Ok(f.write(w)?),
903 impl ReadableArgs<bool> for Features {
904 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
905 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
906 Ok(Self::Bolt12(Readable::read(reader)?))
910 /// A list of hops along a payment path terminating with a channel to the recipient.
911 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
912 pub struct RouteHint(pub Vec<RouteHintHop>);
914 impl Writeable for RouteHint {
915 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
916 (self.0.len() as u64).write(writer)?;
917 for hop in self.0.iter() {
924 impl Readable for RouteHint {
925 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
926 let hop_count: u64 = Readable::read(reader)?;
927 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
928 for _ in 0..hop_count {
929 hops.push(Readable::read(reader)?);
935 /// A channel descriptor for a hop along a payment path.
936 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
937 pub struct RouteHintHop {
938 /// The node_id of the non-target end of the route
939 pub src_node_id: PublicKey,
940 /// The short_channel_id of this channel
941 pub short_channel_id: u64,
942 /// The fees which must be paid to use this channel
943 pub fees: RoutingFees,
944 /// The difference in CLTV values between this node and the next node.
945 pub cltv_expiry_delta: u16,
946 /// The minimum value, in msat, which must be relayed to the next hop.
947 pub htlc_minimum_msat: Option<u64>,
948 /// The maximum value in msat available for routing with a single HTLC.
949 pub htlc_maximum_msat: Option<u64>,
952 impl_writeable_tlv_based!(RouteHintHop, {
953 (0, src_node_id, required),
954 (1, htlc_minimum_msat, option),
955 (2, short_channel_id, required),
956 (3, htlc_maximum_msat, option),
958 (6, cltv_expiry_delta, required),
961 #[derive(Eq, PartialEq)]
962 struct RouteGraphNode {
964 lowest_fee_to_node: u64,
965 total_cltv_delta: u32,
966 // The maximum value a yet-to-be-constructed payment path might flow through this node.
967 // This value is upper-bounded by us by:
968 // - how much is needed for a path being constructed
969 // - how much value can channels following this node (up to the destination) can contribute,
970 // considering their capacity and fees
971 value_contribution_msat: u64,
972 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
973 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
974 path_htlc_minimum_msat: u64,
975 /// All penalties incurred from this hop on the way to the destination, as calculated using
977 path_penalty_msat: u64,
978 /// The number of hops walked up to this node.
979 path_length_to_node: u8,
982 impl cmp::Ord for RouteGraphNode {
983 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
984 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
985 .saturating_add(other.path_penalty_msat);
986 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
987 .saturating_add(self.path_penalty_msat);
988 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
992 impl cmp::PartialOrd for RouteGraphNode {
993 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
994 Some(self.cmp(other))
998 /// A wrapper around the various hop representations.
1000 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
1001 #[derive(Clone, Debug)]
1002 enum CandidateRouteHop<'a> {
1003 /// A hop from the payer, where the outbound liquidity is known.
1005 details: &'a ChannelDetails,
1007 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
1009 info: DirectedChannelInfo<'a>,
1010 short_channel_id: u64,
1012 /// A hop to the payee found in the BOLT 11 payment invoice, though not necessarily a direct
1015 hint: &'a RouteHintHop,
1017 /// The payee's identity is concealed behind blinded paths provided in a BOLT 12 invoice.
1019 hint: &'a (BlindedPayInfo, BlindedPath),
1022 /// Similar to [`Self::Blinded`], but the path here has 1 blinded hop. `BlindedPayInfo` provided
1023 /// for 1-hop blinded paths is ignored because it is meant to apply to the hops *between* the
1024 /// introduction node and the destination. Useful for tracking that we need to include a blinded
1025 /// path at the end of our [`Route`].
1027 hint: &'a (BlindedPayInfo, BlindedPath),
1032 impl<'a> CandidateRouteHop<'a> {
1033 fn short_channel_id(&self) -> Option<u64> {
1035 CandidateRouteHop::FirstHop { details } => Some(details.get_outbound_payment_scid().unwrap()),
1036 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
1037 CandidateRouteHop::PrivateHop { hint } => Some(hint.short_channel_id),
1038 CandidateRouteHop::Blinded { .. } => None,
1039 CandidateRouteHop::OneHopBlinded { .. } => None,
1043 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1044 fn features(&self) -> ChannelFeatures {
1046 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
1047 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
1048 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
1049 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
1050 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
1054 fn cltv_expiry_delta(&self) -> u32 {
1056 CandidateRouteHop::FirstHop { .. } => 0,
1057 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1058 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
1059 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1060 CandidateRouteHop::OneHopBlinded { .. } => 0,
1064 fn htlc_minimum_msat(&self) -> u64 {
1066 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_minimum_msat,
1067 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1068 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
1069 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1070 CandidateRouteHop::OneHopBlinded { .. } => 0,
1074 fn fees(&self) -> RoutingFees {
1076 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1077 base_msat: 0, proportional_millionths: 0,
1079 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1080 CandidateRouteHop::PrivateHop { hint } => hint.fees,
1081 CandidateRouteHop::Blinded { hint, .. } => {
1083 base_msat: hint.0.fee_base_msat,
1084 proportional_millionths: hint.0.fee_proportional_millionths
1087 CandidateRouteHop::OneHopBlinded { .. } =>
1088 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1092 fn effective_capacity(&self) -> EffectiveCapacity {
1094 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
1095 liquidity_msat: details.next_outbound_htlc_limit_msat,
1097 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1098 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }} =>
1099 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1100 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }} =>
1101 EffectiveCapacity::Infinite,
1102 CandidateRouteHop::Blinded { hint, .. } =>
1103 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1104 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1108 fn id(&self, channel_direction: bool /* src_node_id < target_node_id */) -> CandidateHopId {
1110 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1111 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1112 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), channel_direction)),
1115 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1117 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1125 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1126 enum CandidateHopId {
1127 /// Contains (scid, src_node_id < target_node_id)
1129 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1134 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1135 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1137 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1138 EffectiveCapacity::Infinite => u64::max_value(),
1139 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1140 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1141 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1142 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1143 // expected to have been generated from up-to-date capacity information.
1144 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1145 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1146 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1150 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1151 -> bool where I1::Item: PartialEq<I2::Item> {
1153 let a = iter_a.next();
1154 let b = iter_b.next();
1155 if a.is_none() && b.is_none() { return true; }
1156 if a.is_none() || b.is_none() { return false; }
1157 if a.unwrap().ne(&b.unwrap()) { return false; }
1161 /// It's useful to keep track of the hops associated with the fees required to use them,
1162 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1163 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1164 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1166 struct PathBuildingHop<'a> {
1167 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
1168 // is a larger refactor and will require careful performance analysis.
1170 candidate: CandidateRouteHop<'a>,
1173 /// All the fees paid *after* this channel on the way to the destination
1174 next_hops_fee_msat: u64,
1175 /// Fee paid for the use of the current channel (see candidate.fees()).
1176 /// The value will be actually deducted from the counterparty balance on the previous link.
1177 hop_use_fee_msat: u64,
1178 /// Used to compare channels when choosing the for routing.
1179 /// Includes paying for the use of a hop and the following hops, as well as
1180 /// an estimated cost of reaching this hop.
1181 /// Might get stale when fees are recomputed. Primarily for internal use.
1182 total_fee_msat: u64,
1183 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1184 /// walk and may be invalid thereafter.
1185 path_htlc_minimum_msat: u64,
1186 /// All penalties incurred from this channel on the way to the destination, as calculated using
1187 /// channel scoring.
1188 path_penalty_msat: u64,
1189 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1190 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1191 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1192 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1193 /// avoid processing them again.
1194 was_processed: bool,
1195 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1196 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1197 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1198 // value_contribution_msat, which requires tracking it here. See comments below where it is
1199 // used for more info.
1200 value_contribution_msat: u64,
1203 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1204 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1205 let mut debug_struct = f.debug_struct("PathBuildingHop");
1207 .field("node_id", &self.node_id)
1208 .field("short_channel_id", &self.candidate.short_channel_id())
1209 .field("total_fee_msat", &self.total_fee_msat)
1210 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1211 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1212 .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)))
1213 .field("path_penalty_msat", &self.path_penalty_msat)
1214 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1215 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1216 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1217 let debug_struct = debug_struct
1218 .field("value_contribution_msat", &self.value_contribution_msat);
1219 debug_struct.finish()
1223 // Instantiated with a list of hops with correct data in them collected during path finding,
1224 // an instance of this struct should be further modified only via given methods.
1226 struct PaymentPath<'a> {
1227 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1230 impl<'a> PaymentPath<'a> {
1231 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1232 fn get_value_msat(&self) -> u64 {
1233 self.hops.last().unwrap().0.fee_msat
1236 fn get_path_penalty_msat(&self) -> u64 {
1237 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1240 fn get_total_fee_paid_msat(&self) -> u64 {
1241 if self.hops.len() < 1 {
1245 // Can't use next_hops_fee_msat because it gets outdated.
1246 for (i, (hop, _)) in self.hops.iter().enumerate() {
1247 if i != self.hops.len() - 1 {
1248 result += hop.fee_msat;
1254 fn get_cost_msat(&self) -> u64 {
1255 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1258 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1259 // to change fees may result in an inconsistency.
1261 // Sometimes we call this function right after constructing a path which is inconsistent in
1262 // that it the value being transferred has decreased while we were doing path finding, leading
1263 // to the fees being paid not lining up with the actual limits.
1265 // Note that this function is not aware of the available_liquidity limit, and thus does not
1266 // support increasing the value being transferred beyond what was selected during the initial
1269 // Returns the amount that this path contributes to the total payment value, which may be greater
1270 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1271 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1272 let mut extra_contribution_msat = 0;
1273 let mut total_fee_paid_msat = 0 as u64;
1274 for i in (0..self.hops.len()).rev() {
1275 let last_hop = i == self.hops.len() - 1;
1277 // For non-last-hop, this value will represent the fees paid on the current hop. It
1278 // will consist of the fees for the use of the next hop, and extra fees to match
1279 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1280 let mut cur_hop_fees_msat = 0;
1282 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1285 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1286 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1287 cur_hop.path_penalty_msat += extra_contribution_msat;
1288 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1289 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1290 // set it too high just to maliciously take more fees by exploiting this
1291 // match htlc_minimum_msat logic.
1292 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1293 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1294 // Note that there is a risk that *previous hops* (those closer to us, as we go
1295 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1297 // This might make us end up with a broken route, although this should be super-rare
1298 // in practice, both because of how healthy channels look like, and how we pick
1299 // channels in add_entry.
1300 // Also, this can't be exploited more heavily than *announce a free path and fail
1302 cur_hop_transferred_amount_msat += extra_fees_msat;
1304 // We remember and return the extra fees on the final hop to allow accounting for
1305 // them in the path's value contribution.
1307 extra_contribution_msat = extra_fees_msat;
1309 total_fee_paid_msat += extra_fees_msat;
1310 cur_hop_fees_msat += extra_fees_msat;
1315 // Final hop is a special case: it usually has just value_msat (by design), but also
1316 // it still could overpay for the htlc_minimum_msat.
1317 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1319 // Propagate updated fees for the use of the channels to one hop back, where they
1320 // will be actually paid (fee_msat). The last hop is handled above separately.
1321 cur_hop.fee_msat = cur_hop_fees_msat;
1324 // Fee for the use of the current hop which will be deducted on the previous hop.
1325 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1326 // this channel is free for us.
1328 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1329 cur_hop.hop_use_fee_msat = new_fee;
1330 total_fee_paid_msat += new_fee;
1332 // It should not be possible because this function is called only to reduce the
1333 // value. In that case, compute_fee was already called with the same fees for
1334 // larger amount and there was no overflow.
1339 value_msat + extra_contribution_msat
1344 /// Calculate the fees required to route the given amount over a channel with the given fees.
1345 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1346 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1347 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1351 /// Calculate the fees required to route the given amount over a channel with the given fees,
1352 /// saturating to [`u64::max_value`].
1353 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1354 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1355 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1356 .saturating_add(channel_fees.base_msat as u64)
1359 /// The default `features` we assume for a node in a route, when no `features` are known about that
1362 /// Default features are:
1363 /// * variable_length_onion_optional
1364 fn default_node_features() -> NodeFeatures {
1365 let mut features = NodeFeatures::empty();
1366 features.set_variable_length_onion_optional();
1370 struct LoggedPayeePubkey(Option<PublicKey>);
1371 impl fmt::Display for LoggedPayeePubkey {
1372 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1375 "payee node id ".fmt(f)?;
1379 "blinded payee".fmt(f)
1385 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1386 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1387 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1389 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1390 "blinded route hint with introduction node id ".fmt(f)?;
1391 hint.1.introduction_node_id.fmt(f)?;
1392 " and blinding point ".fmt(f)?;
1393 hint.1.blinding_point.fmt(f)
1395 CandidateRouteHop::FirstHop { .. } => {
1396 "first hop with SCID ".fmt(f)?;
1397 self.0.short_channel_id().unwrap().fmt(f)
1399 CandidateRouteHop::PrivateHop { .. } => {
1400 "route hint with SCID ".fmt(f)?;
1401 self.0.short_channel_id().unwrap().fmt(f)
1405 self.0.short_channel_id().unwrap().fmt(f)
1412 fn sort_first_hop_channels(
1413 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1414 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1416 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1417 // most like to use.
1419 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1420 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1423 // Second, because simply always sorting in descending order would always use our largest
1424 // available outbound capacity, needlessly fragmenting our available channel capacities,
1425 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1426 // which have enough, but not too much, capacity for the payment.
1428 // Available outbound balances factor in liquidity already reserved for previously found paths.
1429 channels.sort_unstable_by(|chan_a, chan_b| {
1430 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1431 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1432 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1433 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1434 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1435 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1436 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1437 // Sort in descending order
1438 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1440 // Sort in ascending order
1441 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1446 /// Finds a route from us (payer) to the given target node (payee).
1448 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1449 /// in the given [`RouteParameters::payment_params`].
1450 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1452 /// Private routing paths between a public node and the target may be included in the `payee` field
1453 /// of [`RouteParameters::payment_params`].
1455 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1456 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1457 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1459 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1460 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1461 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1465 /// Panics if first_hops contains channels without `short_channel_id`s;
1466 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1468 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1469 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1470 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1471 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1472 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1473 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1474 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1475 ) -> Result<Route, LightningError>
1476 where L::Target: Logger, GL::Target: Logger {
1477 let graph_lock = network_graph.read_only();
1478 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1479 scorer, score_params, random_seed_bytes)?;
1480 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1484 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1485 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1486 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1487 _random_seed_bytes: &[u8; 32]
1488 ) -> Result<Route, LightningError>
1489 where L::Target: Logger {
1491 let payment_params = &route_params.payment_params;
1492 let final_value_msat = route_params.final_value_msat;
1493 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1494 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1495 // so use a dummy id for this in the blinded case.
1496 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1497 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1498 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1499 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1500 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1502 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1503 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1505 if our_node_id == maybe_dummy_payee_node_id {
1506 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1509 if final_value_msat > MAX_VALUE_MSAT {
1510 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1513 if final_value_msat == 0 {
1514 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1517 match &payment_params.payee {
1518 Payee::Clear { route_hints, node_id, .. } => {
1519 for route in route_hints.iter() {
1520 for hop in &route.0 {
1521 if hop.src_node_id == *node_id {
1522 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1527 Payee::Blinded { route_hints, .. } => {
1528 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1529 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});
1531 for (_, blinded_path) in route_hints.iter() {
1532 if blinded_path.blinded_hops.len() == 0 {
1533 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1534 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1535 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1536 } else if blinded_path.blinded_hops.len() == 1 &&
1537 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1538 && p.introduction_node_id != blinded_path.introduction_node_id)
1540 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1545 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1546 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1547 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});
1550 // The general routing idea is the following:
1551 // 1. Fill first/last hops communicated by the caller.
1552 // 2. Attempt to construct a path from payer to payee for transferring
1553 // any ~sufficient (described later) value.
1554 // If succeed, remember which channels were used and how much liquidity they have available,
1555 // so that future paths don't rely on the same liquidity.
1556 // 3. Proceed to the next step if:
1557 // - we hit the recommended target value;
1558 // - OR if we could not construct a new path. Any next attempt will fail too.
1559 // Otherwise, repeat step 2.
1560 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1561 // (not recommended value).
1562 // 5. If yes, proceed. If not, fail routing.
1563 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1564 // transferred up to the transfer target value.
1565 // 7. Reduce the value of the last path until we are sending only the target value.
1566 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1567 // them so that we're not sending two HTLCs along the same path.
1569 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1570 // distance from the payee
1572 // We are not a faithful Dijkstra's implementation because we can change values which impact
1573 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1574 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1575 // the value we are currently attempting to send over a path, we simply reduce the value being
1576 // sent along the path for any hops after that channel. This may imply that later fees (which
1577 // we've already tabulated) are lower because a smaller value is passing through the channels
1578 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1579 // channels which were selected earlier (and which may still be used for other paths without a
1580 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1583 // One potentially problematic case for this algorithm would be if there are many
1584 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1585 // graph walking), we may never find a path which is not liquidity-limited and has lower
1586 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1587 // Because we only consider paths with at least 5% of the total value being sent, the damage
1588 // from such a case should be limited, however this could be further reduced in the future by
1589 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1590 // limits for the purposes of fee calculation.
1592 // Alternatively, we could store more detailed path information in the heap (targets, below)
1593 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1594 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1595 // and practically (as we would need to store dynamically-allocated path information in heap
1596 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1597 // results of such an algorithm would likely be biased towards lower-value paths.
1599 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1600 // outside of our current search value, running a path search more times to gather candidate
1601 // paths at different values. While this may be acceptable, further path searches may increase
1602 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1603 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1604 // the same time, remaining generic across different payment values.
1606 let network_channels = network_graph.channels();
1607 let network_nodes = network_graph.nodes();
1609 if payment_params.max_path_count == 0 {
1610 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1613 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1614 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1616 let allow_mpp = if payment_params.max_path_count == 1 {
1618 } else if payment_params.payee.supports_basic_mpp() {
1620 } else if let Some(payee) = payee_node_id_opt {
1621 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1622 |info| info.features.supports_basic_mpp()))
1625 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1626 LoggedPayeePubkey(payment_params.payee.node_id()), if allow_mpp { "with" } else { "without" },
1627 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1630 // Prepare the data we'll use for payee-to-payer search by
1631 // inserting first hops suggested by the caller as targets.
1632 // Our search will then attempt to reach them while traversing from the payee node.
1633 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1634 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1635 if let Some(hops) = first_hops {
1637 if chan.get_outbound_payment_scid().is_none() {
1638 panic!("first_hops should be filled in with usable channels, not pending ones");
1640 if chan.counterparty.node_id == *our_node_pubkey {
1641 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1644 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1645 .or_insert(Vec::new())
1648 if first_hop_targets.is_empty() {
1649 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1653 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1654 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1655 // adding duplicate entries when we find a better path to a given node.
1656 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1658 // Map from node_id to information about the best current path to that node, including feerate
1660 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1662 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1663 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1664 // htlc_minimum with extra fees while still finding a cheaper path.
1665 let mut hit_minimum_limit;
1667 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1668 // We start with a path_value of the exact amount we want, and if that generates a route we may
1669 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1670 // amount we want in total across paths, selecting the best subset at the end.
1671 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1672 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1673 let mut path_value_msat = final_value_msat;
1675 // Routing Fragmentation Mitigation heuristic:
1677 // Routing fragmentation across many payment paths increases the overall routing
1678 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1679 // Taking too many smaller paths also increases the chance of payment failure.
1680 // Thus to avoid this effect, we require from our collected links to provide
1681 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1682 // This requirement is currently set to be 1/max_path_count of the payment
1683 // value to ensure we only ever return routes that do not violate this limit.
1684 let minimal_value_contribution_msat: u64 = if allow_mpp {
1685 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1690 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1691 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1692 // drop the requirement by setting this to 0.
1693 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1695 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1696 // determine if the channel can be used by additional MPP paths or to inform path finding
1697 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1698 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1700 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1701 HashMap::with_capacity(network_nodes.len());
1703 // Keeping track of how much value we already collected across other paths. Helps to decide
1704 // when we want to stop looking for new paths.
1705 let mut already_collected_value_msat = 0;
1707 for (_, channels) in first_hop_targets.iter_mut() {
1708 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1712 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1713 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1715 // Remember how many candidates we ignored to allow for some logging afterwards.
1716 let mut num_ignored_value_contribution = 0;
1717 let mut num_ignored_path_length_limit = 0;
1718 let mut num_ignored_cltv_delta_limit = 0;
1719 let mut num_ignored_previously_failed = 0;
1720 let mut num_ignored_total_fee_limit = 0;
1721 let mut num_ignored_avoid_overpayment = 0;
1722 let mut num_ignored_htlc_minimum_msat_limit = 0;
1724 macro_rules! add_entry {
1725 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1726 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1727 // since that value has to be transferred over this channel.
1728 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
1729 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1730 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1731 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1732 // We "return" whether we updated the path at the end, and how much we can route via
1733 // this channel, via this:
1734 let mut hop_contribution_amt_msat = None;
1735 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1736 // practice these cases should be caught earlier:
1737 // - for regular channels at channel announcement (TODO)
1738 // - for first and last hops early in get_route
1739 if $src_node_id != $dest_node_id {
1740 let scid_opt = $candidate.short_channel_id();
1741 let effective_capacity = $candidate.effective_capacity();
1742 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1744 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1745 // It may be misleading because we might later choose to reduce the value transferred
1746 // over these channels, and the channel which was insufficient might become sufficient.
1747 // Worst case: we drop a good channel here because it can't cover the high following
1748 // fees caused by one expensive channel, but then this channel could have been used
1749 // if the amount being transferred over this path is lower.
1750 // We do this for now, but this is a subject for removal.
1751 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1752 let used_liquidity_msat = used_liquidities
1753 .get(&$candidate.id($src_node_id < $dest_node_id))
1754 .map_or(0, |used_liquidity_msat| {
1755 available_value_contribution_msat = available_value_contribution_msat
1756 .saturating_sub(*used_liquidity_msat);
1757 *used_liquidity_msat
1760 // Verify the liquidity offered by this channel complies to the minimal contribution.
1761 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1762 // Do not consider candidate hops that would exceed the maximum path length.
1763 let path_length_to_node = $next_hops_path_length + 1;
1764 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1766 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1767 // In order to already account for some of the privacy enhancing random CLTV
1768 // expiry delta offset we add on top later, we subtract a rough estimate
1769 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1770 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1771 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1772 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1773 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1774 .saturating_add($candidate.cltv_expiry_delta());
1775 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1777 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1778 // Includes paying fees for the use of the following channels.
1779 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1780 Some(result) => result,
1781 // Can't overflow due to how the values were computed right above.
1782 None => unreachable!(),
1784 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1785 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1786 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1788 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1789 let may_overpay_to_meet_path_minimum_msat =
1790 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1791 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1792 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1793 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1795 let payment_failed_on_this_channel = scid_opt.map_or(false,
1796 |scid| payment_params.previously_failed_channels.contains(&scid));
1798 let should_log_candidate = match $candidate {
1799 CandidateRouteHop::FirstHop { .. } => true,
1800 CandidateRouteHop::PrivateHop { .. } => true,
1801 CandidateRouteHop::Blinded { .. } => true,
1802 CandidateRouteHop::OneHopBlinded { .. } => true,
1806 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1807 // bother considering this channel. If retrying with recommended_value_msat may
1808 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1809 // around again with a higher amount.
1810 if !contributes_sufficient_value {
1811 if should_log_candidate {
1812 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
1814 num_ignored_value_contribution += 1;
1815 } else if exceeds_max_path_length {
1816 if should_log_candidate {
1817 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
1819 num_ignored_path_length_limit += 1;
1820 } else if exceeds_cltv_delta_limit {
1821 if should_log_candidate {
1822 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
1824 num_ignored_cltv_delta_limit += 1;
1825 } else if payment_failed_on_this_channel {
1826 if should_log_candidate {
1827 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
1829 num_ignored_previously_failed += 1;
1830 } else if may_overpay_to_meet_path_minimum_msat {
1831 if should_log_candidate {
1833 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit.",
1834 LoggedCandidateHop(&$candidate));
1836 num_ignored_avoid_overpayment += 1;
1837 hit_minimum_limit = true;
1838 } else if over_path_minimum_msat {
1839 // Note that low contribution here (limited by available_liquidity_msat)
1840 // might violate htlc_minimum_msat on the hops which are next along the
1841 // payment path (upstream to the payee). To avoid that, we recompute
1842 // path fees knowing the final path contribution after constructing it.
1843 let curr_min = cmp::max(
1844 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
1846 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
1847 .saturating_add(curr_min);
1848 let hm_entry = dist.entry($src_node_id);
1849 let old_entry = hm_entry.or_insert_with(|| {
1850 // If there was previously no known way to access the source node
1851 // (recall it goes payee-to-payer) of short_channel_id, first add a
1852 // semi-dummy record just to compute the fees to reach the source node.
1853 // This will affect our decision on selecting short_channel_id
1854 // as a way to reach the $dest_node_id.
1856 node_id: $dest_node_id.clone(),
1857 candidate: $candidate.clone(),
1859 next_hops_fee_msat: u64::max_value(),
1860 hop_use_fee_msat: u64::max_value(),
1861 total_fee_msat: u64::max_value(),
1862 path_htlc_minimum_msat,
1863 path_penalty_msat: u64::max_value(),
1864 was_processed: false,
1865 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1866 value_contribution_msat,
1870 #[allow(unused_mut)] // We only use the mut in cfg(test)
1871 let mut should_process = !old_entry.was_processed;
1872 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1874 // In test/fuzzing builds, we do extra checks to make sure the skipping
1875 // of already-seen nodes only happens in cases we expect (see below).
1876 if !should_process { should_process = true; }
1880 let mut hop_use_fee_msat = 0;
1881 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1883 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1884 // will have the same effective-fee
1885 if $src_node_id != our_node_id {
1886 // Note that `u64::max_value` means we'll always fail the
1887 // `old_entry.total_fee_msat > total_fee_msat` check below
1888 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1889 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1892 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
1893 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1894 if total_fee_msat > max_total_routing_fee_msat {
1895 if should_log_candidate {
1896 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
1898 num_ignored_total_fee_limit += 1;
1900 let channel_usage = ChannelUsage {
1901 amount_msat: amount_to_transfer_over_msat,
1902 inflight_htlc_msat: used_liquidity_msat,
1905 let channel_penalty_msat = scid_opt.map_or(0,
1906 |scid| scorer.channel_penalty_msat(scid, &$src_node_id, &$dest_node_id,
1907 channel_usage, score_params));
1908 let path_penalty_msat = $next_hops_path_penalty_msat
1909 .saturating_add(channel_penalty_msat);
1910 let new_graph_node = RouteGraphNode {
1911 node_id: $src_node_id,
1912 lowest_fee_to_node: total_fee_msat,
1913 total_cltv_delta: hop_total_cltv_delta,
1914 value_contribution_msat,
1915 path_htlc_minimum_msat,
1917 path_length_to_node,
1920 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1921 // if this way is cheaper than the already known
1922 // (considering the cost to "reach" this channel from the route destination,
1923 // the cost of using this channel,
1924 // and the cost of routing to the source node of this channel).
1925 // Also, consider that htlc_minimum_msat_difference, because we might end up
1926 // paying it. Consider the following exploit:
1927 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1928 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1929 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1930 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1932 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1933 // but it may require additional tracking - we don't want to double-count
1934 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1935 // can't use something that may decrease on future hops.
1936 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1937 .saturating_add(old_entry.path_penalty_msat);
1938 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1939 .saturating_add(path_penalty_msat);
1941 if !old_entry.was_processed && new_cost < old_cost {
1942 targets.push(new_graph_node);
1943 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1944 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1945 old_entry.total_fee_msat = total_fee_msat;
1946 old_entry.node_id = $dest_node_id.clone();
1947 old_entry.candidate = $candidate.clone();
1948 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1949 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1950 old_entry.path_penalty_msat = path_penalty_msat;
1951 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1953 old_entry.value_contribution_msat = value_contribution_msat;
1955 hop_contribution_amt_msat = Some(value_contribution_msat);
1956 } else if old_entry.was_processed && new_cost < old_cost {
1957 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1959 // If we're skipping processing a node which was previously
1960 // processed even though we found another path to it with a
1961 // cheaper fee, check that it was because the second path we
1962 // found (which we are processing now) has a lower value
1963 // contribution due to an HTLC minimum limit.
1965 // e.g. take a graph with two paths from node 1 to node 2, one
1966 // through channel A, and one through channel B. Channel A and
1967 // B are both in the to-process heap, with their scores set by
1968 // a higher htlc_minimum than fee.
1969 // Channel A is processed first, and the channels onwards from
1970 // node 1 are added to the to-process heap. Thereafter, we pop
1971 // Channel B off of the heap, note that it has a much more
1972 // restrictive htlc_maximum_msat, and recalculate the fees for
1973 // all of node 1's channels using the new, reduced, amount.
1975 // This would be bogus - we'd be selecting a higher-fee path
1976 // with a lower htlc_maximum_msat instead of the one we'd
1977 // already decided to use.
1978 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1980 value_contribution_msat + path_penalty_msat <
1981 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1988 if should_log_candidate {
1990 "Ignoring {} due to its htlc_minimum_msat limit.",
1991 LoggedCandidateHop(&$candidate));
1993 num_ignored_htlc_minimum_msat_limit += 1;
1997 hop_contribution_amt_msat
2001 let default_node_features = default_node_features();
2003 // Find ways (channels with destination) to reach a given node and store them
2004 // in the corresponding data structures (routing graph etc).
2005 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2006 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2007 // This data can later be helpful to optimize routing (pay lower fees).
2008 macro_rules! add_entries_to_cheapest_to_target_node {
2009 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
2010 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
2011 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2012 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
2013 let was_processed = elem.was_processed;
2014 elem.was_processed = true;
2017 // Entries are added to dist in add_entry!() when there is a channel from a node.
2018 // Because there are no channels from payee, it will not have a dist entry at this point.
2019 // If we're processing any other node, it is always be the result of a channel from it.
2020 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2025 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
2026 for details in first_channels {
2027 let candidate = CandidateRouteHop::FirstHop { details };
2028 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
2029 $next_hops_value_contribution,
2030 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
2031 $next_hops_cltv_delta, $next_hops_path_length);
2035 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2038 &default_node_features
2041 if !features.requires_unknown_bits() {
2042 for chan_id in $node.channels.iter() {
2043 let chan = network_channels.get(chan_id).unwrap();
2044 if !chan.features.requires_unknown_bits() {
2045 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2046 if first_hops.is_none() || *source != our_node_id {
2047 if directed_channel.direction().enabled {
2048 let candidate = CandidateRouteHop::PublicHop {
2049 info: directed_channel,
2050 short_channel_id: *chan_id,
2052 add_entry!(candidate, *source, $node_id,
2053 $fee_to_target_msat,
2054 $next_hops_value_contribution,
2055 $next_hops_path_htlc_minimum_msat,
2056 $next_hops_path_penalty_msat,
2057 $next_hops_cltv_delta, $next_hops_path_length);
2068 let mut payment_paths = Vec::<PaymentPath>::new();
2070 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2071 'paths_collection: loop {
2072 // For every new path, start from scratch, except for used_liquidities, which
2073 // helps to avoid reusing previously selected paths in future iterations.
2076 hit_minimum_limit = false;
2078 // If first hop is a private channel and the only way to reach the payee, this is the only
2079 // place where it could be added.
2080 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2081 for details in first_channels {
2082 let candidate = CandidateRouteHop::FirstHop { details };
2083 let added = add_entry!(candidate, our_node_id, payee, 0, path_value_msat,
2084 0, 0u64, 0, 0).is_some();
2085 log_trace!(logger, "{} direct route to payee via {}",
2086 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2090 // Add the payee as a target, so that the payee-to-payer
2091 // search algorithm knows what to start with.
2092 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2093 // The payee is not in our network graph, so nothing to add here.
2094 // There is still a chance of reaching them via last_hops though,
2095 // so don't yet fail the payment here.
2096 // If not, targets.pop() will not even let us enter the loop in step 2.
2099 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
2104 // If a caller provided us with last hops, add them to routing targets. Since this happens
2105 // earlier than general path finding, they will be somewhat prioritized, although currently
2106 // it matters only if the fees are exactly the same.
2107 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2108 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2109 let have_intro_node_in_graph =
2110 // Only add the hops in this route to our candidate set if either
2111 // we have a direct channel to the first hop or the first hop is
2112 // in the regular network graph.
2113 first_hop_targets.get(&intro_node_id).is_some() ||
2114 network_nodes.get(&intro_node_id).is_some();
2115 if !have_intro_node_in_graph || our_node_id == intro_node_id { continue }
2116 let candidate = if hint.1.blinded_hops.len() == 1 {
2117 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
2118 } else { CandidateRouteHop::Blinded { hint, hint_idx } };
2119 let mut path_contribution_msat = path_value_msat;
2120 if let Some(hop_used_msat) = add_entry!(candidate, intro_node_id, maybe_dummy_payee_node_id,
2121 0, path_contribution_msat, 0, 0_u64, 0, 0)
2123 path_contribution_msat = hop_used_msat;
2125 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2126 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2128 for details in first_channels {
2129 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2130 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2134 let path_min = candidate.htlc_minimum_msat().saturating_add(
2135 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2136 add_entry!(first_hop_candidate, our_node_id, intro_node_id, blinded_path_fee,
2137 path_contribution_msat, path_min, 0_u64, candidate.cltv_expiry_delta(),
2138 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2142 for route in payment_params.payee.unblinded_route_hints().iter()
2143 .filter(|route| !route.0.is_empty())
2145 let first_hop_in_route = &(route.0)[0];
2146 let have_hop_src_in_graph =
2147 // Only add the hops in this route to our candidate set if either
2148 // we have a direct channel to the first hop or the first hop is
2149 // in the regular network graph.
2150 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
2151 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
2152 if have_hop_src_in_graph {
2153 // We start building the path from reverse, i.e., from payee
2154 // to the first RouteHintHop in the path.
2155 let hop_iter = route.0.iter().rev();
2156 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2157 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2158 let mut hop_used = true;
2159 let mut aggregate_next_hops_fee_msat: u64 = 0;
2160 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2161 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2162 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2163 let mut aggregate_next_hops_path_length: u8 = 0;
2164 let mut aggregate_path_contribution_msat = path_value_msat;
2166 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2167 let source = NodeId::from_pubkey(&hop.src_node_id);
2168 let target = NodeId::from_pubkey(&prev_hop_id);
2169 let candidate = network_channels
2170 .get(&hop.short_channel_id)
2171 .and_then(|channel| channel.as_directed_to(&target))
2172 .map(|(info, _)| CandidateRouteHop::PublicHop {
2174 short_channel_id: hop.short_channel_id,
2176 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
2178 if let Some(hop_used_msat) = add_entry!(candidate, source, target,
2179 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2180 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2181 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2183 aggregate_path_contribution_msat = hop_used_msat;
2185 // If this hop was not used then there is no use checking the preceding
2186 // hops in the RouteHint. We can break by just searching for a direct
2187 // channel between last checked hop and first_hop_targets.
2191 let used_liquidity_msat = used_liquidities
2192 .get(&candidate.id(source < target)).copied()
2194 let channel_usage = ChannelUsage {
2195 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2196 inflight_htlc_msat: used_liquidity_msat,
2197 effective_capacity: candidate.effective_capacity(),
2199 let channel_penalty_msat = scorer.channel_penalty_msat(
2200 hop.short_channel_id, &source, &target, channel_usage, score_params
2202 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2203 .saturating_add(channel_penalty_msat);
2205 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2206 .saturating_add(hop.cltv_expiry_delta as u32);
2208 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2211 // Searching for a direct channel between last checked hop and first_hop_targets
2212 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&prev_hop_id)) {
2213 sort_first_hop_channels(first_channels, &used_liquidities,
2214 recommended_value_msat, our_node_pubkey);
2215 for details in first_channels {
2216 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2217 add_entry!(first_hop_candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
2218 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2219 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2220 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2228 // In the next values of the iterator, the aggregate fees already reflects
2229 // the sum of value sent from payer (final_value_msat) and routing fees
2230 // for the last node in the RouteHint. We need to just add the fees to
2231 // route through the current node so that the preceding node (next iteration)
2233 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2234 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2235 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2237 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2238 // this route hint's source node to forward said min over this channel.
2239 aggregate_next_hops_path_htlc_minimum_msat = {
2240 let curr_htlc_min = cmp::max(
2241 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2243 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2244 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2247 if idx == route.0.len() - 1 {
2248 // The last hop in this iterator is the first hop in
2249 // overall RouteHint.
2250 // If this hop connects to a node with which we have a direct channel,
2251 // ignore the network graph and, if the last hop was added, add our
2252 // direct channel to the candidate set.
2254 // Note that we *must* check if the last hop was added as `add_entry`
2255 // always assumes that the third argument is a node to which we have a
2257 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2258 sort_first_hop_channels(first_channels, &used_liquidities,
2259 recommended_value_msat, our_node_pubkey);
2260 for details in first_channels {
2261 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2262 add_entry!(first_hop_candidate, our_node_id,
2263 NodeId::from_pubkey(&hop.src_node_id),
2264 aggregate_next_hops_fee_msat,
2265 aggregate_path_contribution_msat,
2266 aggregate_next_hops_path_htlc_minimum_msat,
2267 aggregate_next_hops_path_penalty_msat,
2268 aggregate_next_hops_cltv_delta,
2269 aggregate_next_hops_path_length);
2277 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2279 // At this point, targets are filled with the data from first and
2280 // last hops communicated by the caller, and the payment receiver.
2281 let mut found_new_path = false;
2284 // If this loop terminates due the exhaustion of targets, two situations are possible:
2285 // - not enough outgoing liquidity:
2286 // 0 < already_collected_value_msat < final_value_msat
2287 // - enough outgoing liquidity:
2288 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2289 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2290 // paths_collection will be stopped because found_new_path==false.
2291 // This is not necessarily a routing failure.
2292 '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() {
2294 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2295 // traversing the graph and arrange the path out of what we found.
2296 if node_id == our_node_id {
2297 let mut new_entry = dist.remove(&our_node_id).unwrap();
2298 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2301 let mut features_set = false;
2302 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
2303 for details in first_channels {
2304 if let Some(scid) = ordered_hops.last().unwrap().0.candidate.short_channel_id() {
2305 if details.get_outbound_payment_scid().unwrap() == scid {
2306 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2307 features_set = true;
2314 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
2315 if let Some(node_info) = node.announcement_info.as_ref() {
2316 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2318 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2321 // We can fill in features for everything except hops which were
2322 // provided via the invoice we're paying. We could guess based on the
2323 // recipient's features but for now we simply avoid guessing at all.
2327 // Means we succesfully traversed from the payer to the payee, now
2328 // save this path for the payment route. Also, update the liquidity
2329 // remaining on the used hops, so that we take them into account
2330 // while looking for more paths.
2331 if ordered_hops.last().unwrap().0.node_id == maybe_dummy_payee_node_id {
2335 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
2336 Some(payment_hop) => payment_hop,
2337 // We can't arrive at None because, if we ever add an entry to targets,
2338 // we also fill in the entry in dist (see add_entry!).
2339 None => unreachable!(),
2341 // We "propagate" the fees one hop backward (topologically) here,
2342 // so that fees paid for a HTLC forwarding on the current channel are
2343 // associated with the previous channel (where they will be subtracted).
2344 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2345 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2347 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2348 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2350 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2351 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2353 let mut payment_path = PaymentPath {hops: ordered_hops};
2355 // We could have possibly constructed a slightly inconsistent path: since we reduce
2356 // value being transferred along the way, we could have violated htlc_minimum_msat
2357 // on some channels we already passed (assuming dest->source direction). Here, we
2358 // recompute the fees again, so that if that's the case, we match the currently
2359 // underpaid htlc_minimum_msat with fees.
2360 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2361 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2362 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2364 // Since a path allows to transfer as much value as
2365 // the smallest channel it has ("bottleneck"), we should recompute
2366 // the fees so sender HTLC don't overpay fees when traversing
2367 // larger channels than the bottleneck. This may happen because
2368 // when we were selecting those channels we were not aware how much value
2369 // this path will transfer, and the relative fee for them
2370 // might have been computed considering a larger value.
2371 // Remember that we used these channels so that we don't rely
2372 // on the same liquidity in future paths.
2373 let mut prevented_redundant_path_selection = false;
2374 let prev_hop_iter = core::iter::once(&our_node_id)
2375 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
2376 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
2377 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2378 let used_liquidity_msat = used_liquidities
2379 .entry(hop.candidate.id(*prev_hop < hop.node_id))
2380 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2381 .or_insert(spent_on_hop_msat);
2382 let hop_capacity = hop.candidate.effective_capacity();
2383 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2384 if *used_liquidity_msat == hop_max_msat {
2385 // If this path used all of this channel's available liquidity, we know
2386 // this path will not be selected again in the next loop iteration.
2387 prevented_redundant_path_selection = true;
2389 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2391 if !prevented_redundant_path_selection {
2392 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2393 // we'll probably end up picking the same path again on the next iteration.
2394 // Decrease the available liquidity of a hop in the middle of the path.
2395 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2396 let exhausted = u64::max_value();
2398 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2399 LoggedCandidateHop(victim_candidate));
2400 *used_liquidities.entry(victim_candidate.id(false)).or_default() = exhausted;
2401 *used_liquidities.entry(victim_candidate.id(true)).or_default() = exhausted;
2404 // Track the total amount all our collected paths allow to send so that we know
2405 // when to stop looking for more paths
2406 already_collected_value_msat += value_contribution_msat;
2408 payment_paths.push(payment_path);
2409 found_new_path = true;
2410 break 'path_construction;
2413 // If we found a path back to the payee, we shouldn't try to process it again. This is
2414 // the equivalent of the `elem.was_processed` check in
2415 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2416 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2418 // Otherwise, since the current target node is not us,
2419 // keep "unrolling" the payment graph from payee to payer by
2420 // finding a way to reach the current target from the payer side.
2421 match network_nodes.get(&node_id) {
2424 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2425 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2426 total_cltv_delta, path_length_to_node);
2432 if !found_new_path && channel_saturation_pow_half != 0 {
2433 channel_saturation_pow_half = 0;
2434 continue 'paths_collection;
2436 // If we don't support MPP, no use trying to gather more value ever.
2437 break 'paths_collection;
2441 // Stop either when the recommended value is reached or if no new path was found in this
2443 // In the latter case, making another path finding attempt won't help,
2444 // because we deterministically terminated the search due to low liquidity.
2445 if !found_new_path && channel_saturation_pow_half != 0 {
2446 channel_saturation_pow_half = 0;
2447 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2448 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2449 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2450 break 'paths_collection;
2451 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2452 // Further, if this was our first walk of the graph, and we weren't limited by an
2453 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2454 // limited by an htlc_minimum_msat value, find another path with a higher value,
2455 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2456 // still keeping a lower total fee than this path.
2457 if !hit_minimum_limit {
2458 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2459 break 'paths_collection;
2461 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher value to meet htlc_minimum_msat limit.");
2462 path_value_msat = recommended_value_msat;
2466 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2467 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
2468 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
2469 num_ignored_total_fee_limit;
2470 if num_ignored_total > 0 {
2472 "Ignored {} candidate hops due to insufficient value contribution, {} due to path length limit, {} due to CLTV delta limit, {} due to previous payment failure, {} due to htlc_minimum_msat limit, {} to avoid overpaying, {} due to maximum total fee limit. Total: {} ignored candidates.",
2473 num_ignored_value_contribution, num_ignored_path_length_limit,
2474 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
2475 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
2476 num_ignored_total_fee_limit, num_ignored_total);
2480 if payment_paths.len() == 0 {
2481 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2484 if already_collected_value_msat < final_value_msat {
2485 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2489 let mut selected_route = payment_paths;
2491 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2492 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2494 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2495 // the value they contribute towards the payment amount.
2496 // We sort in descending order as we will remove from the front in `retain`, next.
2497 selected_route.sort_unstable_by(|a, b|
2498 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2499 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2502 // We should make sure that at least 1 path left.
2503 let mut paths_left = selected_route.len();
2504 selected_route.retain(|path| {
2505 if paths_left == 1 {
2508 let path_value_msat = path.get_value_msat();
2509 if path_value_msat <= overpaid_value_msat {
2510 overpaid_value_msat -= path_value_msat;
2516 debug_assert!(selected_route.len() > 0);
2518 if overpaid_value_msat != 0 {
2520 // Now, subtract the remaining overpaid value from the most-expensive path.
2521 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2522 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2523 selected_route.sort_unstable_by(|a, b| {
2524 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2525 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2526 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2528 let expensive_payment_path = selected_route.first_mut().unwrap();
2530 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2531 // can't go negative.
2532 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2533 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2537 // Sort by the path itself and combine redundant paths.
2538 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2539 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2541 selected_route.sort_unstable_by_key(|path| {
2542 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2543 debug_assert!(path.hops.len() <= key.len());
2544 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id(true)).zip(key.iter_mut()) {
2549 for idx in 0..(selected_route.len() - 1) {
2550 if idx + 1 >= selected_route.len() { break; }
2551 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id)),
2552 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id))) {
2553 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2554 selected_route[idx].update_value_and_recompute_fees(new_value);
2555 selected_route.remove(idx + 1);
2559 let mut paths = Vec::new();
2560 for payment_path in selected_route {
2561 let mut hops = Vec::with_capacity(payment_path.hops.len());
2562 let mut prev_hop_node_id = our_node_id;
2563 for (hop, node_features) in payment_path.hops.iter()
2564 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2566 let maybe_announced_channel = if let CandidateRouteHop::PublicHop { .. } = hop.candidate {
2567 // If we sourced the hop from the graph we're sure the target node is announced.
2569 } else if let CandidateRouteHop::FirstHop { details } = hop.candidate {
2570 // If this is a first hop we also know if it's announced.
2573 // If we sourced it any other way, we double-check the network graph to see if
2574 // there are announced channels between the endpoints. If so, the hop might be
2575 // referring to any of the announced channels, as its `short_channel_id` might be
2576 // an alias, in which case we don't take any chances here.
2577 network_graph.node(&hop.node_id).map_or(false, |hop_node|
2578 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
2579 .map_or(false, |c| c.as_directed_from(&prev_hop_node_id).is_some()))
2583 hops.push(RouteHop {
2584 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)})?,
2585 node_features: node_features.clone(),
2586 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2587 channel_features: hop.candidate.features(),
2588 fee_msat: hop.fee_msat,
2589 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2590 maybe_announced_channel,
2593 prev_hop_node_id = hop.node_id;
2595 let mut final_cltv_delta = final_cltv_expiry_delta;
2596 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2597 if let Some(blinded_path) = h.candidate.blinded_path() {
2598 final_cltv_delta = h.candidate.cltv_expiry_delta();
2600 hops: blinded_path.blinded_hops.clone(),
2601 blinding_point: blinded_path.blinding_point,
2602 excess_final_cltv_expiry_delta: 0,
2603 final_value_msat: h.fee_msat,
2607 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2608 // applicable for the previous hop.
2609 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2610 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2613 paths.push(Path { hops, blinded_tail });
2615 // Make sure we would never create a route with more paths than we allow.
2616 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2618 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
2619 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
2620 if paths.iter().map(|p| p.fee_msat()).sum::<u64>() > max_total_routing_fee_msat {
2621 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
2622 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
2626 if let Some(node_features) = payment_params.payee.node_features() {
2627 for path in paths.iter_mut() {
2628 path.hops.last_mut().unwrap().node_features = node_features.clone();
2632 let route = Route { paths, route_params: Some(route_params.clone()) };
2633 log_info!(logger, "Got route: {}", log_route!(route));
2637 // When an adversarial intermediary node observes a payment, it may be able to infer its
2638 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2639 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2640 // payment path by adding a randomized 'shadow route' offset to the final hop.
2641 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2642 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2644 let network_channels = network_graph.channels();
2645 let network_nodes = network_graph.nodes();
2647 for path in route.paths.iter_mut() {
2648 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2650 // Remember the last three nodes of the random walk and avoid looping back on them.
2651 // Init with the last three nodes from the actual path, if possible.
2652 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2653 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2654 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2656 // Choose the last publicly known node as the starting point for the random walk.
2657 let mut cur_hop: Option<NodeId> = None;
2658 let mut path_nonce = [0u8; 12];
2659 if let Some(starting_hop) = path.hops.iter().rev()
2660 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2661 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2662 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2665 // Init PRNG with the path-dependant nonce, which is static for private paths.
2666 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2667 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2669 // Pick a random path length in [1 .. 3]
2670 prng.process_in_place(&mut random_path_bytes);
2671 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2673 for random_hop in 0..random_walk_length {
2674 // If we don't find a suitable offset in the public network graph, we default to
2675 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2676 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2678 if let Some(cur_node_id) = cur_hop {
2679 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2680 // Randomly choose the next unvisited hop.
2681 prng.process_in_place(&mut random_path_bytes);
2682 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2683 .checked_rem(cur_node.channels.len())
2684 .and_then(|index| cur_node.channels.get(index))
2685 .and_then(|id| network_channels.get(id)) {
2686 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2687 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2688 nodes_to_avoid[random_hop] = *next_id;
2689 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2690 cur_hop = Some(*next_id);
2697 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2698 .checked_add(random_hop_offset)
2699 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2702 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2703 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2704 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2706 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2707 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2708 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2709 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2710 max_path_offset = cmp::max(
2711 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2712 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2713 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2715 // Add 'shadow' CLTV offset to the final hop
2716 if let Some(tail) = path.blinded_tail.as_mut() {
2717 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2718 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2720 if let Some(last_hop) = path.hops.last_mut() {
2721 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2722 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2727 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2728 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2730 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2731 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2732 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2733 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2734 ) -> Result<Route, LightningError>
2735 where L::Target: Logger, GL::Target: Logger {
2736 let graph_lock = network_graph.read_only();
2737 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
2738 &graph_lock, logger, random_seed_bytes)?;
2739 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2743 fn build_route_from_hops_internal<L: Deref>(
2744 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2745 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
2746 ) -> Result<Route, LightningError> where L::Target: Logger {
2749 our_node_id: NodeId,
2750 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2753 impl ScoreLookUp for HopScorer {
2754 type ScoreParams = ();
2755 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2756 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2758 let mut cur_id = self.our_node_id;
2759 for i in 0..self.hop_ids.len() {
2760 if let Some(next_id) = self.hop_ids[i] {
2761 if cur_id == *source && next_id == *target {
2773 impl<'a> Writeable for HopScorer {
2775 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2780 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2781 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2784 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2785 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2786 for i in 0..hops.len() {
2787 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2790 let scorer = HopScorer { our_node_id, hop_ids };
2792 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
2797 use crate::blinded_path::{BlindedHop, BlindedPath};
2798 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2799 use crate::routing::utxo::UtxoResult;
2800 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2801 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2802 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters};
2803 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2804 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2805 use crate::chain::transaction::OutPoint;
2806 use crate::sign::EntropySource;
2807 use crate::ln::ChannelId;
2808 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2809 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2810 use crate::ln::channelmanager;
2811 use crate::offers::invoice::BlindedPayInfo;
2812 use crate::util::config::UserConfig;
2813 use crate::util::test_utils as ln_test_utils;
2814 use crate::util::chacha20::ChaCha20;
2815 use crate::util::ser::{Readable, Writeable};
2817 use crate::util::ser::Writer;
2819 use bitcoin::hashes::Hash;
2820 use bitcoin::network::constants::Network;
2821 use bitcoin::blockdata::constants::genesis_block;
2822 use bitcoin::blockdata::script::Builder;
2823 use bitcoin::blockdata::opcodes;
2824 use bitcoin::blockdata::transaction::TxOut;
2828 use bitcoin::secp256k1::{PublicKey,SecretKey};
2829 use bitcoin::secp256k1::Secp256k1;
2831 use crate::io::Cursor;
2832 use crate::prelude::*;
2833 use crate::sync::Arc;
2835 use core::convert::TryInto;
2837 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2838 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2839 channelmanager::ChannelDetails {
2840 channel_id: ChannelId::new_zero(),
2841 counterparty: channelmanager::ChannelCounterparty {
2844 unspendable_punishment_reserve: 0,
2845 forwarding_info: None,
2846 outbound_htlc_minimum_msat: None,
2847 outbound_htlc_maximum_msat: None,
2849 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2852 outbound_scid_alias: None,
2853 inbound_scid_alias: None,
2854 channel_value_satoshis: 0,
2856 outbound_capacity_msat,
2857 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2858 next_outbound_htlc_minimum_msat: 0,
2859 inbound_capacity_msat: 42,
2860 unspendable_punishment_reserve: None,
2861 confirmations_required: None,
2862 confirmations: None,
2863 force_close_spend_delay: None,
2864 is_outbound: true, is_channel_ready: true,
2865 is_usable: true, is_public: true,
2866 inbound_htlc_minimum_msat: None,
2867 inbound_htlc_maximum_msat: None,
2869 feerate_sat_per_1000_weight: None,
2870 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
2875 fn simple_route_test() {
2876 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2877 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2878 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2879 let scorer = ln_test_utils::TestScorer::new();
2880 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2881 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2883 // Simple route to 2 via 1
2885 let route_params = RouteParameters::from_payment_params_and_value(
2886 payment_params.clone(), 0);
2887 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2888 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
2889 &Default::default(), &random_seed_bytes) {
2890 assert_eq!(err, "Cannot send a payment of 0 msat");
2891 } else { panic!(); }
2893 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
2894 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2895 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
2896 assert_eq!(route.paths[0].hops.len(), 2);
2898 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2899 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2900 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2901 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2902 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2903 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2905 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2906 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2907 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2908 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2909 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2910 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2914 fn invalid_first_hop_test() {
2915 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2916 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2917 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2918 let scorer = ln_test_utils::TestScorer::new();
2919 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2920 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2922 // Simple route to 2 via 1
2924 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2926 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
2927 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2928 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
2929 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
2930 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2931 } else { panic!(); }
2933 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2934 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
2935 assert_eq!(route.paths[0].hops.len(), 2);
2939 fn htlc_minimum_test() {
2940 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2941 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2942 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2943 let scorer = ln_test_utils::TestScorer::new();
2944 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2945 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2947 // Simple route to 2 via 1
2949 // Disable other paths
2950 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2951 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2952 short_channel_id: 12,
2954 flags: 2, // to disable
2955 cltv_expiry_delta: 0,
2956 htlc_minimum_msat: 0,
2957 htlc_maximum_msat: MAX_VALUE_MSAT,
2959 fee_proportional_millionths: 0,
2960 excess_data: Vec::new()
2962 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2963 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2964 short_channel_id: 3,
2966 flags: 2, // to disable
2967 cltv_expiry_delta: 0,
2968 htlc_minimum_msat: 0,
2969 htlc_maximum_msat: MAX_VALUE_MSAT,
2971 fee_proportional_millionths: 0,
2972 excess_data: Vec::new()
2974 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2975 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2976 short_channel_id: 13,
2978 flags: 2, // to disable
2979 cltv_expiry_delta: 0,
2980 htlc_minimum_msat: 0,
2981 htlc_maximum_msat: MAX_VALUE_MSAT,
2983 fee_proportional_millionths: 0,
2984 excess_data: Vec::new()
2986 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2987 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2988 short_channel_id: 6,
2990 flags: 2, // to disable
2991 cltv_expiry_delta: 0,
2992 htlc_minimum_msat: 0,
2993 htlc_maximum_msat: MAX_VALUE_MSAT,
2995 fee_proportional_millionths: 0,
2996 excess_data: Vec::new()
2998 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2999 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3000 short_channel_id: 7,
3002 flags: 2, // to disable
3003 cltv_expiry_delta: 0,
3004 htlc_minimum_msat: 0,
3005 htlc_maximum_msat: MAX_VALUE_MSAT,
3007 fee_proportional_millionths: 0,
3008 excess_data: Vec::new()
3011 // Check against amount_to_transfer_over_msat.
3012 // Set minimal HTLC of 200_000_000 msat.
3013 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3014 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3015 short_channel_id: 2,
3018 cltv_expiry_delta: 0,
3019 htlc_minimum_msat: 200_000_000,
3020 htlc_maximum_msat: MAX_VALUE_MSAT,
3022 fee_proportional_millionths: 0,
3023 excess_data: Vec::new()
3026 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3028 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3029 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3030 short_channel_id: 4,
3033 cltv_expiry_delta: 0,
3034 htlc_minimum_msat: 0,
3035 htlc_maximum_msat: 199_999_999,
3037 fee_proportional_millionths: 0,
3038 excess_data: Vec::new()
3041 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3042 let route_params = RouteParameters::from_payment_params_and_value(
3043 payment_params, 199_999_999);
3044 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3045 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3046 &Default::default(), &random_seed_bytes) {
3047 assert_eq!(err, "Failed to find a path to the given destination");
3048 } else { panic!(); }
3050 // Lift the restriction on the first hop.
3051 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3052 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3053 short_channel_id: 2,
3056 cltv_expiry_delta: 0,
3057 htlc_minimum_msat: 0,
3058 htlc_maximum_msat: MAX_VALUE_MSAT,
3060 fee_proportional_millionths: 0,
3061 excess_data: Vec::new()
3064 // A payment above the minimum should pass
3065 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3066 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3067 assert_eq!(route.paths[0].hops.len(), 2);
3071 fn htlc_minimum_overpay_test() {
3072 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3073 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3074 let config = UserConfig::default();
3075 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3076 let scorer = ln_test_utils::TestScorer::new();
3077 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3078 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3080 // A route to node#2 via two paths.
3081 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3082 // Thus, they can't send 60 without overpaying.
3083 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3084 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3085 short_channel_id: 2,
3088 cltv_expiry_delta: 0,
3089 htlc_minimum_msat: 35_000,
3090 htlc_maximum_msat: 40_000,
3092 fee_proportional_millionths: 0,
3093 excess_data: Vec::new()
3095 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3096 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3097 short_channel_id: 12,
3100 cltv_expiry_delta: 0,
3101 htlc_minimum_msat: 35_000,
3102 htlc_maximum_msat: 40_000,
3104 fee_proportional_millionths: 0,
3105 excess_data: Vec::new()
3109 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3110 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3111 short_channel_id: 13,
3114 cltv_expiry_delta: 0,
3115 htlc_minimum_msat: 0,
3116 htlc_maximum_msat: MAX_VALUE_MSAT,
3118 fee_proportional_millionths: 0,
3119 excess_data: Vec::new()
3121 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3122 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3123 short_channel_id: 4,
3126 cltv_expiry_delta: 0,
3127 htlc_minimum_msat: 0,
3128 htlc_maximum_msat: MAX_VALUE_MSAT,
3130 fee_proportional_millionths: 0,
3131 excess_data: Vec::new()
3134 // Disable other paths
3135 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3136 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3137 short_channel_id: 1,
3139 flags: 2, // to disable
3140 cltv_expiry_delta: 0,
3141 htlc_minimum_msat: 0,
3142 htlc_maximum_msat: MAX_VALUE_MSAT,
3144 fee_proportional_millionths: 0,
3145 excess_data: Vec::new()
3148 let mut route_params = RouteParameters::from_payment_params_and_value(
3149 payment_params.clone(), 60_000);
3150 route_params.max_total_routing_fee_msat = Some(15_000);
3151 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3152 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3153 // Overpay fees to hit htlc_minimum_msat.
3154 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3155 // TODO: this could be better balanced to overpay 10k and not 15k.
3156 assert_eq!(overpaid_fees, 15_000);
3158 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3159 // while taking even more fee to match htlc_minimum_msat.
3160 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3161 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3162 short_channel_id: 12,
3165 cltv_expiry_delta: 0,
3166 htlc_minimum_msat: 65_000,
3167 htlc_maximum_msat: 80_000,
3169 fee_proportional_millionths: 0,
3170 excess_data: Vec::new()
3172 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3173 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3174 short_channel_id: 2,
3177 cltv_expiry_delta: 0,
3178 htlc_minimum_msat: 0,
3179 htlc_maximum_msat: MAX_VALUE_MSAT,
3181 fee_proportional_millionths: 0,
3182 excess_data: Vec::new()
3184 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3185 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3186 short_channel_id: 4,
3189 cltv_expiry_delta: 0,
3190 htlc_minimum_msat: 0,
3191 htlc_maximum_msat: MAX_VALUE_MSAT,
3193 fee_proportional_millionths: 100_000,
3194 excess_data: Vec::new()
3197 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3198 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3199 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3200 assert_eq!(route.paths.len(), 1);
3201 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3202 let fees = route.paths[0].hops[0].fee_msat;
3203 assert_eq!(fees, 5_000);
3205 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3206 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3207 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3208 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3209 // the other channel.
3210 assert_eq!(route.paths.len(), 1);
3211 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3212 let fees = route.paths[0].hops[0].fee_msat;
3213 assert_eq!(fees, 5_000);
3217 fn disable_channels_test() {
3218 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3219 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3220 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3221 let scorer = ln_test_utils::TestScorer::new();
3222 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3223 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3225 // // Disable channels 4 and 12 by flags=2
3226 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3227 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3228 short_channel_id: 4,
3230 flags: 2, // to disable
3231 cltv_expiry_delta: 0,
3232 htlc_minimum_msat: 0,
3233 htlc_maximum_msat: MAX_VALUE_MSAT,
3235 fee_proportional_millionths: 0,
3236 excess_data: Vec::new()
3238 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3239 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3240 short_channel_id: 12,
3242 flags: 2, // to disable
3243 cltv_expiry_delta: 0,
3244 htlc_minimum_msat: 0,
3245 htlc_maximum_msat: MAX_VALUE_MSAT,
3247 fee_proportional_millionths: 0,
3248 excess_data: Vec::new()
3251 // If all the channels require some features we don't understand, route should fail
3252 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3253 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3254 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3255 &Default::default(), &random_seed_bytes) {
3256 assert_eq!(err, "Failed to find a path to the given destination");
3257 } else { panic!(); }
3259 // If we specify a channel to node7, that overrides our local channel view and that gets used
3260 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3261 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3262 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3263 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3264 &Default::default(), &random_seed_bytes).unwrap();
3265 assert_eq!(route.paths[0].hops.len(), 2);
3267 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3268 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3269 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3270 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3271 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3272 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3274 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3275 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3276 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3277 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3278 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3279 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3283 fn disable_node_test() {
3284 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3285 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3286 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3287 let scorer = ln_test_utils::TestScorer::new();
3288 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3289 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3291 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3292 let mut unknown_features = NodeFeatures::empty();
3293 unknown_features.set_unknown_feature_required();
3294 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3295 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3296 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3298 // If all nodes require some features we don't understand, route should fail
3299 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3300 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3301 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3302 &Default::default(), &random_seed_bytes) {
3303 assert_eq!(err, "Failed to find a path to the given destination");
3304 } else { panic!(); }
3306 // If we specify a channel to node7, that overrides our local channel view and that gets used
3307 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3308 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3309 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3310 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3311 &Default::default(), &random_seed_bytes).unwrap();
3312 assert_eq!(route.paths[0].hops.len(), 2);
3314 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3315 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3316 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3317 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3318 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3319 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3321 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3322 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3323 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3324 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3325 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3326 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3328 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3329 // naively) assume that the user checked the feature bits on the invoice, which override
3330 // the node_announcement.
3334 fn our_chans_test() {
3335 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3336 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3337 let scorer = ln_test_utils::TestScorer::new();
3338 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3339 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3341 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3342 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3343 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3344 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3345 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3346 assert_eq!(route.paths[0].hops.len(), 3);
3348 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3349 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3350 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3351 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3352 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3353 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3355 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3356 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3357 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3358 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3359 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3360 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3362 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3363 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3364 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3365 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3366 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3367 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3369 // If we specify a channel to node7, that overrides our local channel view and that gets used
3370 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3371 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3372 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3373 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3374 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3375 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3376 &Default::default(), &random_seed_bytes).unwrap();
3377 assert_eq!(route.paths[0].hops.len(), 2);
3379 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3380 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3381 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3382 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3383 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3384 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3386 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3387 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3388 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3389 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3390 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3391 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3394 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3395 let zero_fees = RoutingFees {
3397 proportional_millionths: 0,
3399 vec![RouteHint(vec![RouteHintHop {
3400 src_node_id: nodes[3],
3401 short_channel_id: 8,
3403 cltv_expiry_delta: (8 << 4) | 1,
3404 htlc_minimum_msat: None,
3405 htlc_maximum_msat: None,
3407 ]), RouteHint(vec![RouteHintHop {
3408 src_node_id: nodes[4],
3409 short_channel_id: 9,
3412 proportional_millionths: 0,
3414 cltv_expiry_delta: (9 << 4) | 1,
3415 htlc_minimum_msat: None,
3416 htlc_maximum_msat: None,
3417 }]), RouteHint(vec![RouteHintHop {
3418 src_node_id: nodes[5],
3419 short_channel_id: 10,
3421 cltv_expiry_delta: (10 << 4) | 1,
3422 htlc_minimum_msat: None,
3423 htlc_maximum_msat: None,
3427 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3428 let zero_fees = RoutingFees {
3430 proportional_millionths: 0,
3432 vec![RouteHint(vec![RouteHintHop {
3433 src_node_id: nodes[2],
3434 short_channel_id: 5,
3437 proportional_millionths: 0,
3439 cltv_expiry_delta: (5 << 4) | 1,
3440 htlc_minimum_msat: None,
3441 htlc_maximum_msat: None,
3443 src_node_id: nodes[3],
3444 short_channel_id: 8,
3446 cltv_expiry_delta: (8 << 4) | 1,
3447 htlc_minimum_msat: None,
3448 htlc_maximum_msat: None,
3450 ]), RouteHint(vec![RouteHintHop {
3451 src_node_id: nodes[4],
3452 short_channel_id: 9,
3455 proportional_millionths: 0,
3457 cltv_expiry_delta: (9 << 4) | 1,
3458 htlc_minimum_msat: None,
3459 htlc_maximum_msat: None,
3460 }]), RouteHint(vec![RouteHintHop {
3461 src_node_id: nodes[5],
3462 short_channel_id: 10,
3464 cltv_expiry_delta: (10 << 4) | 1,
3465 htlc_minimum_msat: None,
3466 htlc_maximum_msat: None,
3471 fn partial_route_hint_test() {
3472 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3473 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3474 let scorer = ln_test_utils::TestScorer::new();
3475 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3476 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3478 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3479 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3480 // RouteHint may be partially used by the algo to build the best path.
3482 // First check that last hop can't have its source as the payee.
3483 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3484 src_node_id: nodes[6],
3485 short_channel_id: 8,
3488 proportional_millionths: 0,
3490 cltv_expiry_delta: (8 << 4) | 1,
3491 htlc_minimum_msat: None,
3492 htlc_maximum_msat: None,
3495 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3496 invalid_last_hops.push(invalid_last_hop);
3498 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3499 .with_route_hints(invalid_last_hops).unwrap();
3500 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3501 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3502 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3503 &Default::default(), &random_seed_bytes) {
3504 assert_eq!(err, "Route hint cannot have the payee as the source.");
3505 } else { panic!(); }
3508 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3509 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3510 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3511 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3512 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3513 assert_eq!(route.paths[0].hops.len(), 5);
3515 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3516 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3517 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3518 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3519 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3520 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3522 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3523 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3524 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3525 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3526 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3527 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3529 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3530 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3531 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3532 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3533 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3534 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3536 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3537 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3538 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3539 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3540 // If we have a peer in the node map, we'll use their features here since we don't have
3541 // a way of figuring out their features from the invoice:
3542 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3543 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3545 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3546 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3547 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3548 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3549 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3550 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3553 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3554 let zero_fees = RoutingFees {
3556 proportional_millionths: 0,
3558 vec![RouteHint(vec![RouteHintHop {
3559 src_node_id: nodes[3],
3560 short_channel_id: 8,
3562 cltv_expiry_delta: (8 << 4) | 1,
3563 htlc_minimum_msat: None,
3564 htlc_maximum_msat: None,
3565 }]), RouteHint(vec![
3567 ]), RouteHint(vec![RouteHintHop {
3568 src_node_id: nodes[5],
3569 short_channel_id: 10,
3571 cltv_expiry_delta: (10 << 4) | 1,
3572 htlc_minimum_msat: None,
3573 htlc_maximum_msat: None,
3578 fn ignores_empty_last_hops_test() {
3579 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3580 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3581 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3582 let scorer = ln_test_utils::TestScorer::new();
3583 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3584 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3586 // Test handling of an empty RouteHint passed in Invoice.
3587 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3588 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3589 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3590 assert_eq!(route.paths[0].hops.len(), 5);
3592 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3593 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3594 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3595 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3596 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3597 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3599 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3600 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3601 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3602 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3603 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3604 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3606 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3607 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3608 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3609 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3610 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3611 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3613 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3614 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3615 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3616 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3617 // If we have a peer in the node map, we'll use their features here since we don't have
3618 // a way of figuring out their features from the invoice:
3619 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3620 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3622 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3623 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3624 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3625 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3626 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3627 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3630 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3632 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3633 let zero_fees = RoutingFees {
3635 proportional_millionths: 0,
3637 vec![RouteHint(vec![RouteHintHop {
3638 src_node_id: hint_hops[0],
3639 short_channel_id: 0xff00,
3642 proportional_millionths: 0,
3644 cltv_expiry_delta: (5 << 4) | 1,
3645 htlc_minimum_msat: None,
3646 htlc_maximum_msat: None,
3648 src_node_id: hint_hops[1],
3649 short_channel_id: 0xff01,
3651 cltv_expiry_delta: (8 << 4) | 1,
3652 htlc_minimum_msat: None,
3653 htlc_maximum_msat: None,
3658 fn multi_hint_last_hops_test() {
3659 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3660 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3661 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3662 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3663 let scorer = ln_test_utils::TestScorer::new();
3664 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3665 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3666 // Test through channels 2, 3, 0xff00, 0xff01.
3667 // Test shows that multiple hop hints are considered.
3669 // Disabling channels 6 & 7 by flags=2
3670 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3671 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3672 short_channel_id: 6,
3674 flags: 2, // to disable
3675 cltv_expiry_delta: 0,
3676 htlc_minimum_msat: 0,
3677 htlc_maximum_msat: MAX_VALUE_MSAT,
3679 fee_proportional_millionths: 0,
3680 excess_data: Vec::new()
3682 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3683 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3684 short_channel_id: 7,
3686 flags: 2, // to disable
3687 cltv_expiry_delta: 0,
3688 htlc_minimum_msat: 0,
3689 htlc_maximum_msat: MAX_VALUE_MSAT,
3691 fee_proportional_millionths: 0,
3692 excess_data: Vec::new()
3695 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3696 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3697 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3698 assert_eq!(route.paths[0].hops.len(), 4);
3700 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3701 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3702 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3703 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3704 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3705 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3707 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3708 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3709 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3710 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3711 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3712 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3714 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3715 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3716 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3717 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3718 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3719 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3721 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3722 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3723 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3724 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3725 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3726 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 private_multi_hint_last_hops_test() {
3731 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3732 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3734 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3735 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3737 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3738 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3739 let scorer = ln_test_utils::TestScorer::new();
3740 // Test through channels 2, 3, 0xff00, 0xff01.
3741 // Test shows that multiple hop hints are considered.
3743 // Disabling channels 6 & 7 by flags=2
3744 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3746 short_channel_id: 6,
3748 flags: 2, // to disable
3749 cltv_expiry_delta: 0,
3750 htlc_minimum_msat: 0,
3751 htlc_maximum_msat: MAX_VALUE_MSAT,
3753 fee_proportional_millionths: 0,
3754 excess_data: Vec::new()
3756 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3757 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3758 short_channel_id: 7,
3760 flags: 2, // to disable
3761 cltv_expiry_delta: 0,
3762 htlc_minimum_msat: 0,
3763 htlc_maximum_msat: MAX_VALUE_MSAT,
3765 fee_proportional_millionths: 0,
3766 excess_data: Vec::new()
3769 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3770 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3771 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
3772 assert_eq!(route.paths[0].hops.len(), 4);
3774 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3775 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3776 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3777 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3778 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3779 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3781 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3782 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3783 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3784 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3785 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3786 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3788 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3789 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3790 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3791 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3792 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3793 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3795 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3796 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3797 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3798 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3799 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3800 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3803 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3804 let zero_fees = RoutingFees {
3806 proportional_millionths: 0,
3808 vec![RouteHint(vec![RouteHintHop {
3809 src_node_id: nodes[4],
3810 short_channel_id: 11,
3812 cltv_expiry_delta: (11 << 4) | 1,
3813 htlc_minimum_msat: None,
3814 htlc_maximum_msat: None,
3816 src_node_id: nodes[3],
3817 short_channel_id: 8,
3819 cltv_expiry_delta: (8 << 4) | 1,
3820 htlc_minimum_msat: None,
3821 htlc_maximum_msat: None,
3822 }]), RouteHint(vec![RouteHintHop {
3823 src_node_id: nodes[4],
3824 short_channel_id: 9,
3827 proportional_millionths: 0,
3829 cltv_expiry_delta: (9 << 4) | 1,
3830 htlc_minimum_msat: None,
3831 htlc_maximum_msat: None,
3832 }]), RouteHint(vec![RouteHintHop {
3833 src_node_id: nodes[5],
3834 short_channel_id: 10,
3836 cltv_expiry_delta: (10 << 4) | 1,
3837 htlc_minimum_msat: None,
3838 htlc_maximum_msat: None,
3843 fn last_hops_with_public_channel_test() {
3844 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3845 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3846 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
3847 let scorer = ln_test_utils::TestScorer::new();
3848 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3849 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3850 // This test shows that public routes can be present in the invoice
3851 // which would be handled in the same manner.
3853 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3854 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3855 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3856 assert_eq!(route.paths[0].hops.len(), 5);
3858 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3859 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3860 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3861 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3862 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3863 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3865 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3866 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3867 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3868 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3869 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3870 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3872 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3873 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3874 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3875 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3876 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3877 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3879 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3880 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3881 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3882 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3883 // If we have a peer in the node map, we'll use their features here since we don't have
3884 // a way of figuring out their features from the invoice:
3885 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3886 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3888 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3889 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3890 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3891 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3892 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3893 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3897 fn our_chans_last_hop_connect_test() {
3898 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3899 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3900 let scorer = ln_test_utils::TestScorer::new();
3901 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3902 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3904 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3905 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3906 let mut last_hops = last_hops(&nodes);
3907 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3908 .with_route_hints(last_hops.clone()).unwrap();
3909 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3910 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3911 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3912 &Default::default(), &random_seed_bytes).unwrap();
3913 assert_eq!(route.paths[0].hops.len(), 2);
3915 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3916 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3917 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3918 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3919 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3920 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3922 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3923 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3924 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3925 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3926 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3927 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3929 last_hops[0].0[0].fees.base_msat = 1000;
3931 // Revert to via 6 as the fee on 8 goes up
3932 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3933 .with_route_hints(last_hops).unwrap();
3934 let route_params = RouteParameters::from_payment_params_and_value(
3935 payment_params.clone(), 100);
3936 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3937 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3938 assert_eq!(route.paths[0].hops.len(), 4);
3940 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3941 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3942 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
3943 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3944 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3945 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3947 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3948 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3949 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3950 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
3951 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3952 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3954 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
3955 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3956 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3957 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3958 // If we have a peer in the node map, we'll use their features here since we don't have
3959 // a way of figuring out their features from the invoice:
3960 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3961 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3963 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3964 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3965 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3966 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3967 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3968 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3970 // ...but still use 8 for larger payments as 6 has a variable feerate
3971 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
3972 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3973 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3974 assert_eq!(route.paths[0].hops.len(), 5);
3976 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3977 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3978 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3979 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3980 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3981 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3983 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3984 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3985 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3986 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3987 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3988 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3990 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3991 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3992 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3993 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3994 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3995 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3997 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3998 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3999 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4000 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4001 // If we have a peer in the node map, we'll use their features here since we don't have
4002 // a way of figuring out their features from the invoice:
4003 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4004 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4006 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4007 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4008 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4009 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4010 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4011 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4014 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> {
4015 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4016 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4017 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4019 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4020 let last_hops = RouteHint(vec![RouteHintHop {
4021 src_node_id: middle_node_id,
4022 short_channel_id: 8,
4025 proportional_millionths: last_hop_fee_prop,
4027 cltv_expiry_delta: (8 << 4) | 1,
4028 htlc_minimum_msat: None,
4029 htlc_maximum_msat: last_hop_htlc_max,
4031 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4032 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4033 let scorer = ln_test_utils::TestScorer::new();
4034 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4035 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4036 let logger = ln_test_utils::TestLogger::new();
4037 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4038 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4039 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4040 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4041 &random_seed_bytes);
4046 fn unannounced_path_test() {
4047 // We should be able to send a payment to a destination without any help of a routing graph
4048 // if we have a channel with a common counterparty that appears in the first and last hop
4050 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4052 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4053 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4054 assert_eq!(route.paths[0].hops.len(), 2);
4056 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4057 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4058 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4059 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4060 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4061 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4063 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4064 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4065 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4066 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4067 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4068 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4072 fn overflow_unannounced_path_test_liquidity_underflow() {
4073 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4074 // the last-hop had a fee which overflowed a u64, we'd panic.
4075 // This was due to us adding the first-hop from us unconditionally, causing us to think
4076 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4077 // In this test, we previously hit a subtraction underflow due to having less available
4078 // liquidity at the last hop than 0.
4079 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());
4083 fn overflow_unannounced_path_test_feerate_overflow() {
4084 // This tests for the same case as above, except instead of hitting a subtraction
4085 // underflow, we hit a case where the fee charged at a hop overflowed.
4086 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());
4090 fn available_amount_while_routing_test() {
4091 // Tests whether we choose the correct available channel amount while routing.
4093 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4094 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4095 let scorer = ln_test_utils::TestScorer::new();
4096 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4097 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4098 let config = UserConfig::default();
4099 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4101 // We will use a simple single-path route from
4102 // our node to node2 via node0: channels {1, 3}.
4104 // First disable all other paths.
4105 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4106 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4107 short_channel_id: 2,
4110 cltv_expiry_delta: 0,
4111 htlc_minimum_msat: 0,
4112 htlc_maximum_msat: 100_000,
4114 fee_proportional_millionths: 0,
4115 excess_data: Vec::new()
4117 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4118 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4119 short_channel_id: 12,
4122 cltv_expiry_delta: 0,
4123 htlc_minimum_msat: 0,
4124 htlc_maximum_msat: 100_000,
4126 fee_proportional_millionths: 0,
4127 excess_data: Vec::new()
4130 // Make the first channel (#1) very permissive,
4131 // and we will be testing all limits on the second channel.
4132 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4133 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4134 short_channel_id: 1,
4137 cltv_expiry_delta: 0,
4138 htlc_minimum_msat: 0,
4139 htlc_maximum_msat: 1_000_000_000,
4141 fee_proportional_millionths: 0,
4142 excess_data: Vec::new()
4145 // First, let's see if routing works if we have absolutely no idea about the available amount.
4146 // In this case, it should be set to 250_000 sats.
4147 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4148 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4149 short_channel_id: 3,
4152 cltv_expiry_delta: 0,
4153 htlc_minimum_msat: 0,
4154 htlc_maximum_msat: 250_000_000,
4156 fee_proportional_millionths: 0,
4157 excess_data: Vec::new()
4161 // Attempt to route more than available results in a failure.
4162 let route_params = RouteParameters::from_payment_params_and_value(
4163 payment_params.clone(), 250_000_001);
4164 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4165 &our_id, &route_params, &network_graph.read_only(), None,
4166 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4167 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4168 } else { panic!(); }
4172 // Now, attempt to route an exact amount we have should be fine.
4173 let route_params = RouteParameters::from_payment_params_and_value(
4174 payment_params.clone(), 250_000_000);
4175 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4176 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4177 assert_eq!(route.paths.len(), 1);
4178 let path = route.paths.last().unwrap();
4179 assert_eq!(path.hops.len(), 2);
4180 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4181 assert_eq!(path.final_value_msat(), 250_000_000);
4184 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4185 // Disable channel #1 and use another first hop.
4186 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4187 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4188 short_channel_id: 1,
4191 cltv_expiry_delta: 0,
4192 htlc_minimum_msat: 0,
4193 htlc_maximum_msat: 1_000_000_000,
4195 fee_proportional_millionths: 0,
4196 excess_data: Vec::new()
4199 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4200 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4203 // Attempt to route more than available results in a failure.
4204 let route_params = RouteParameters::from_payment_params_and_value(
4205 payment_params.clone(), 200_000_001);
4206 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4207 &our_id, &route_params, &network_graph.read_only(),
4208 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4209 &Default::default(), &random_seed_bytes) {
4210 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4211 } else { panic!(); }
4215 // Now, attempt to route an exact amount we have should be fine.
4216 let route_params = RouteParameters::from_payment_params_and_value(
4217 payment_params.clone(), 200_000_000);
4218 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4219 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4220 &Default::default(), &random_seed_bytes).unwrap();
4221 assert_eq!(route.paths.len(), 1);
4222 let path = route.paths.last().unwrap();
4223 assert_eq!(path.hops.len(), 2);
4224 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4225 assert_eq!(path.final_value_msat(), 200_000_000);
4228 // Enable channel #1 back.
4229 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4230 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4231 short_channel_id: 1,
4234 cltv_expiry_delta: 0,
4235 htlc_minimum_msat: 0,
4236 htlc_maximum_msat: 1_000_000_000,
4238 fee_proportional_millionths: 0,
4239 excess_data: Vec::new()
4243 // Now let's see if routing works if we know only htlc_maximum_msat.
4244 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4245 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4246 short_channel_id: 3,
4249 cltv_expiry_delta: 0,
4250 htlc_minimum_msat: 0,
4251 htlc_maximum_msat: 15_000,
4253 fee_proportional_millionths: 0,
4254 excess_data: Vec::new()
4258 // Attempt to route more than available results in a failure.
4259 let route_params = RouteParameters::from_payment_params_and_value(
4260 payment_params.clone(), 15_001);
4261 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4262 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4263 &scorer, &Default::default(), &random_seed_bytes) {
4264 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4265 } else { panic!(); }
4269 // Now, attempt to route an exact amount we have should be fine.
4270 let route_params = RouteParameters::from_payment_params_and_value(
4271 payment_params.clone(), 15_000);
4272 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4273 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4274 assert_eq!(route.paths.len(), 1);
4275 let path = route.paths.last().unwrap();
4276 assert_eq!(path.hops.len(), 2);
4277 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4278 assert_eq!(path.final_value_msat(), 15_000);
4281 // Now let's see if routing works if we know only capacity from the UTXO.
4283 // We can't change UTXO capacity on the fly, so we'll disable
4284 // the existing channel and add another one with the capacity we need.
4285 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4286 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4287 short_channel_id: 3,
4290 cltv_expiry_delta: 0,
4291 htlc_minimum_msat: 0,
4292 htlc_maximum_msat: MAX_VALUE_MSAT,
4294 fee_proportional_millionths: 0,
4295 excess_data: Vec::new()
4298 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4299 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4300 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4301 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4302 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4304 *chain_monitor.utxo_ret.lock().unwrap() =
4305 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4306 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4308 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4309 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4310 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4311 short_channel_id: 333,
4314 cltv_expiry_delta: (3 << 4) | 1,
4315 htlc_minimum_msat: 0,
4316 htlc_maximum_msat: 15_000,
4318 fee_proportional_millionths: 0,
4319 excess_data: Vec::new()
4321 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4322 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4323 short_channel_id: 333,
4326 cltv_expiry_delta: (3 << 4) | 2,
4327 htlc_minimum_msat: 0,
4328 htlc_maximum_msat: 15_000,
4330 fee_proportional_millionths: 0,
4331 excess_data: Vec::new()
4335 // Attempt to route more than available results in a failure.
4336 let route_params = RouteParameters::from_payment_params_and_value(
4337 payment_params.clone(), 15_001);
4338 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4339 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4340 &scorer, &Default::default(), &random_seed_bytes) {
4341 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4342 } else { panic!(); }
4346 // Now, attempt to route an exact amount we have should be fine.
4347 let route_params = RouteParameters::from_payment_params_and_value(
4348 payment_params.clone(), 15_000);
4349 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4350 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4351 assert_eq!(route.paths.len(), 1);
4352 let path = route.paths.last().unwrap();
4353 assert_eq!(path.hops.len(), 2);
4354 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4355 assert_eq!(path.final_value_msat(), 15_000);
4358 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4359 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4360 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4361 short_channel_id: 333,
4364 cltv_expiry_delta: 0,
4365 htlc_minimum_msat: 0,
4366 htlc_maximum_msat: 10_000,
4368 fee_proportional_millionths: 0,
4369 excess_data: Vec::new()
4373 // Attempt to route more than available results in a failure.
4374 let route_params = RouteParameters::from_payment_params_and_value(
4375 payment_params.clone(), 10_001);
4376 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4377 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4378 &scorer, &Default::default(), &random_seed_bytes) {
4379 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4380 } else { panic!(); }
4384 // Now, attempt to route an exact amount we have should be fine.
4385 let route_params = RouteParameters::from_payment_params_and_value(
4386 payment_params.clone(), 10_000);
4387 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4388 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4389 assert_eq!(route.paths.len(), 1);
4390 let path = route.paths.last().unwrap();
4391 assert_eq!(path.hops.len(), 2);
4392 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4393 assert_eq!(path.final_value_msat(), 10_000);
4398 fn available_liquidity_last_hop_test() {
4399 // Check that available liquidity properly limits the path even when only
4400 // one of the latter hops is limited.
4401 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4402 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4403 let scorer = ln_test_utils::TestScorer::new();
4404 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4405 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4406 let config = UserConfig::default();
4407 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4409 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4410 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4411 // Total capacity: 50 sats.
4413 // Disable other potential paths.
4414 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4415 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4416 short_channel_id: 2,
4419 cltv_expiry_delta: 0,
4420 htlc_minimum_msat: 0,
4421 htlc_maximum_msat: 100_000,
4423 fee_proportional_millionths: 0,
4424 excess_data: Vec::new()
4426 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4427 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4428 short_channel_id: 7,
4431 cltv_expiry_delta: 0,
4432 htlc_minimum_msat: 0,
4433 htlc_maximum_msat: 100_000,
4435 fee_proportional_millionths: 0,
4436 excess_data: Vec::new()
4441 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4442 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4443 short_channel_id: 12,
4446 cltv_expiry_delta: 0,
4447 htlc_minimum_msat: 0,
4448 htlc_maximum_msat: 100_000,
4450 fee_proportional_millionths: 0,
4451 excess_data: Vec::new()
4453 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4454 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4455 short_channel_id: 13,
4458 cltv_expiry_delta: 0,
4459 htlc_minimum_msat: 0,
4460 htlc_maximum_msat: 100_000,
4462 fee_proportional_millionths: 0,
4463 excess_data: Vec::new()
4466 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4467 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4468 short_channel_id: 6,
4471 cltv_expiry_delta: 0,
4472 htlc_minimum_msat: 0,
4473 htlc_maximum_msat: 50_000,
4475 fee_proportional_millionths: 0,
4476 excess_data: Vec::new()
4478 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4479 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4480 short_channel_id: 11,
4483 cltv_expiry_delta: 0,
4484 htlc_minimum_msat: 0,
4485 htlc_maximum_msat: 100_000,
4487 fee_proportional_millionths: 0,
4488 excess_data: Vec::new()
4491 // Attempt to route more than available results in a failure.
4492 let route_params = RouteParameters::from_payment_params_and_value(
4493 payment_params.clone(), 60_000);
4494 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4495 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4496 &scorer, &Default::default(), &random_seed_bytes) {
4497 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4498 } else { panic!(); }
4502 // Now, attempt to route 49 sats (just a bit below the capacity).
4503 let route_params = RouteParameters::from_payment_params_and_value(
4504 payment_params.clone(), 49_000);
4505 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4506 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4507 assert_eq!(route.paths.len(), 1);
4508 let mut total_amount_paid_msat = 0;
4509 for path in &route.paths {
4510 assert_eq!(path.hops.len(), 4);
4511 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4512 total_amount_paid_msat += path.final_value_msat();
4514 assert_eq!(total_amount_paid_msat, 49_000);
4518 // Attempt to route an exact amount is also fine
4519 let route_params = RouteParameters::from_payment_params_and_value(
4520 payment_params, 50_000);
4521 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4522 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4523 assert_eq!(route.paths.len(), 1);
4524 let mut total_amount_paid_msat = 0;
4525 for path in &route.paths {
4526 assert_eq!(path.hops.len(), 4);
4527 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4528 total_amount_paid_msat += path.final_value_msat();
4530 assert_eq!(total_amount_paid_msat, 50_000);
4535 fn ignore_fee_first_hop_test() {
4536 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4537 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4538 let scorer = ln_test_utils::TestScorer::new();
4539 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4540 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4541 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4543 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4544 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4545 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4546 short_channel_id: 1,
4549 cltv_expiry_delta: 0,
4550 htlc_minimum_msat: 0,
4551 htlc_maximum_msat: 100_000,
4552 fee_base_msat: 1_000_000,
4553 fee_proportional_millionths: 0,
4554 excess_data: Vec::new()
4556 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4557 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4558 short_channel_id: 3,
4561 cltv_expiry_delta: 0,
4562 htlc_minimum_msat: 0,
4563 htlc_maximum_msat: 50_000,
4565 fee_proportional_millionths: 0,
4566 excess_data: Vec::new()
4570 let route_params = RouteParameters::from_payment_params_and_value(
4571 payment_params, 50_000);
4572 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4573 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4574 assert_eq!(route.paths.len(), 1);
4575 let mut total_amount_paid_msat = 0;
4576 for path in &route.paths {
4577 assert_eq!(path.hops.len(), 2);
4578 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4579 total_amount_paid_msat += path.final_value_msat();
4581 assert_eq!(total_amount_paid_msat, 50_000);
4586 fn simple_mpp_route_test() {
4587 let (secp_ctx, _, _, _, _) = build_graph();
4588 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4589 let config = UserConfig::default();
4590 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4591 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4592 do_simple_mpp_route_test(clear_payment_params);
4594 // MPP to a 1-hop blinded path for nodes[2]
4595 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
4596 let blinded_path = BlindedPath {
4597 introduction_node_id: nodes[2],
4598 blinding_point: ln_test_utils::pubkey(42),
4599 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4601 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4603 fee_proportional_millionths: 0,
4604 htlc_minimum_msat: 0,
4605 htlc_maximum_msat: 0,
4606 cltv_expiry_delta: 0,
4607 features: BlindedHopFeatures::empty(),
4609 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4610 .with_bolt12_features(bolt12_features.clone()).unwrap();
4611 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4613 // MPP to 3 2-hop blinded paths
4614 let mut blinded_path_node_0 = blinded_path.clone();
4615 blinded_path_node_0.introduction_node_id = nodes[0];
4616 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4617 let mut node_0_payinfo = blinded_payinfo.clone();
4618 node_0_payinfo.htlc_maximum_msat = 50_000;
4620 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4621 blinded_path_node_7.introduction_node_id = nodes[7];
4622 let mut node_7_payinfo = blinded_payinfo.clone();
4623 node_7_payinfo.htlc_maximum_msat = 60_000;
4625 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4626 blinded_path_node_1.introduction_node_id = nodes[1];
4627 let mut node_1_payinfo = blinded_payinfo.clone();
4628 node_1_payinfo.htlc_maximum_msat = 180_000;
4630 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4632 (node_0_payinfo, blinded_path_node_0),
4633 (node_7_payinfo, blinded_path_node_7),
4634 (node_1_payinfo, blinded_path_node_1)
4636 .with_bolt12_features(bolt12_features).unwrap();
4637 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4641 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4642 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4643 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4644 let scorer = ln_test_utils::TestScorer::new();
4645 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4646 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4648 // We need a route consisting of 3 paths:
4649 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4650 // To achieve this, the amount being transferred should be around
4651 // the total capacity of these 3 paths.
4653 // First, we set limits on these (previously unlimited) channels.
4654 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4656 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4657 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4658 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4659 short_channel_id: 1,
4662 cltv_expiry_delta: 0,
4663 htlc_minimum_msat: 0,
4664 htlc_maximum_msat: 100_000,
4666 fee_proportional_millionths: 0,
4667 excess_data: Vec::new()
4669 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4670 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4671 short_channel_id: 3,
4674 cltv_expiry_delta: 0,
4675 htlc_minimum_msat: 0,
4676 htlc_maximum_msat: 50_000,
4678 fee_proportional_millionths: 0,
4679 excess_data: Vec::new()
4682 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4683 // (total limit 60).
4684 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4685 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4686 short_channel_id: 12,
4689 cltv_expiry_delta: 0,
4690 htlc_minimum_msat: 0,
4691 htlc_maximum_msat: 60_000,
4693 fee_proportional_millionths: 0,
4694 excess_data: Vec::new()
4696 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4697 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4698 short_channel_id: 13,
4701 cltv_expiry_delta: 0,
4702 htlc_minimum_msat: 0,
4703 htlc_maximum_msat: 60_000,
4705 fee_proportional_millionths: 0,
4706 excess_data: Vec::new()
4709 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4710 // (total capacity 180 sats).
4711 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4712 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4713 short_channel_id: 2,
4716 cltv_expiry_delta: 0,
4717 htlc_minimum_msat: 0,
4718 htlc_maximum_msat: 200_000,
4720 fee_proportional_millionths: 0,
4721 excess_data: Vec::new()
4723 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4724 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4725 short_channel_id: 4,
4728 cltv_expiry_delta: 0,
4729 htlc_minimum_msat: 0,
4730 htlc_maximum_msat: 180_000,
4732 fee_proportional_millionths: 0,
4733 excess_data: Vec::new()
4737 // Attempt to route more than available results in a failure.
4738 let route_params = RouteParameters::from_payment_params_and_value(
4739 payment_params.clone(), 300_000);
4740 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4741 &our_id, &route_params, &network_graph.read_only(), None,
4742 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4743 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4744 } else { panic!(); }
4748 // Attempt to route while setting max_path_count to 0 results in a failure.
4749 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4750 let route_params = RouteParameters::from_payment_params_and_value(
4751 zero_payment_params, 100);
4752 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4753 &our_id, &route_params, &network_graph.read_only(), None,
4754 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4755 assert_eq!(err, "Can't find a route with no paths allowed.");
4756 } else { panic!(); }
4760 // Attempt to route while setting max_path_count to 3 results in a failure.
4761 // This is the case because the minimal_value_contribution_msat would require each path
4762 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4763 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4764 let route_params = RouteParameters::from_payment_params_and_value(
4765 fail_payment_params, 250_000);
4766 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4767 &our_id, &route_params, &network_graph.read_only(), None,
4768 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4769 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4770 } else { panic!(); }
4774 // Now, attempt to route 250 sats (just a bit below the capacity).
4775 // Our algorithm should provide us with these 3 paths.
4776 let route_params = RouteParameters::from_payment_params_and_value(
4777 payment_params.clone(), 250_000);
4778 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4779 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4780 assert_eq!(route.paths.len(), 3);
4781 let mut total_amount_paid_msat = 0;
4782 for path in &route.paths {
4783 if let Some(bt) = &path.blinded_tail {
4784 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4786 assert_eq!(path.hops.len(), 2);
4787 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4789 total_amount_paid_msat += path.final_value_msat();
4791 assert_eq!(total_amount_paid_msat, 250_000);
4795 // Attempt to route an exact amount is also fine
4796 let route_params = RouteParameters::from_payment_params_and_value(
4797 payment_params.clone(), 290_000);
4798 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4799 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4800 assert_eq!(route.paths.len(), 3);
4801 let mut total_amount_paid_msat = 0;
4802 for path in &route.paths {
4803 if payment_params.payee.blinded_route_hints().len() != 0 {
4804 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
4805 if let Some(bt) = &path.blinded_tail {
4806 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4807 if bt.hops.len() > 1 {
4808 assert_eq!(path.hops.last().unwrap().pubkey,
4809 payment_params.payee.blinded_route_hints().iter()
4810 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
4811 .map(|(_, p)| p.introduction_node_id).unwrap());
4813 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4816 assert_eq!(path.hops.len(), 2);
4817 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4819 total_amount_paid_msat += path.final_value_msat();
4821 assert_eq!(total_amount_paid_msat, 290_000);
4826 fn long_mpp_route_test() {
4827 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4828 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4829 let scorer = ln_test_utils::TestScorer::new();
4830 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4831 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4832 let config = UserConfig::default();
4833 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4834 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4836 // We need a route consisting of 3 paths:
4837 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4838 // Note that these paths overlap (channels 5, 12, 13).
4839 // We will route 300 sats.
4840 // Each path will have 100 sats capacity, those channels which
4841 // are used twice will have 200 sats capacity.
4843 // Disable other potential paths.
4844 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4845 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4846 short_channel_id: 2,
4849 cltv_expiry_delta: 0,
4850 htlc_minimum_msat: 0,
4851 htlc_maximum_msat: 100_000,
4853 fee_proportional_millionths: 0,
4854 excess_data: Vec::new()
4856 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4857 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4858 short_channel_id: 7,
4861 cltv_expiry_delta: 0,
4862 htlc_minimum_msat: 0,
4863 htlc_maximum_msat: 100_000,
4865 fee_proportional_millionths: 0,
4866 excess_data: Vec::new()
4869 // Path via {node0, node2} is channels {1, 3, 5}.
4870 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4871 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4872 short_channel_id: 1,
4875 cltv_expiry_delta: 0,
4876 htlc_minimum_msat: 0,
4877 htlc_maximum_msat: 100_000,
4879 fee_proportional_millionths: 0,
4880 excess_data: Vec::new()
4882 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4883 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4884 short_channel_id: 3,
4887 cltv_expiry_delta: 0,
4888 htlc_minimum_msat: 0,
4889 htlc_maximum_msat: 100_000,
4891 fee_proportional_millionths: 0,
4892 excess_data: Vec::new()
4895 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4896 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4897 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4898 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4899 short_channel_id: 5,
4902 cltv_expiry_delta: 0,
4903 htlc_minimum_msat: 0,
4904 htlc_maximum_msat: 200_000,
4906 fee_proportional_millionths: 0,
4907 excess_data: Vec::new()
4910 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4911 // Add 100 sats to the capacities of {12, 13}, because these channels
4912 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4913 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4914 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4915 short_channel_id: 12,
4918 cltv_expiry_delta: 0,
4919 htlc_minimum_msat: 0,
4920 htlc_maximum_msat: 200_000,
4922 fee_proportional_millionths: 0,
4923 excess_data: Vec::new()
4925 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4926 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4927 short_channel_id: 13,
4930 cltv_expiry_delta: 0,
4931 htlc_minimum_msat: 0,
4932 htlc_maximum_msat: 200_000,
4934 fee_proportional_millionths: 0,
4935 excess_data: Vec::new()
4938 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4939 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4940 short_channel_id: 6,
4943 cltv_expiry_delta: 0,
4944 htlc_minimum_msat: 0,
4945 htlc_maximum_msat: 100_000,
4947 fee_proportional_millionths: 0,
4948 excess_data: Vec::new()
4950 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4951 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4952 short_channel_id: 11,
4955 cltv_expiry_delta: 0,
4956 htlc_minimum_msat: 0,
4957 htlc_maximum_msat: 100_000,
4959 fee_proportional_millionths: 0,
4960 excess_data: Vec::new()
4963 // Path via {node7, node2} is channels {12, 13, 5}.
4964 // We already limited them to 200 sats (they are used twice for 100 sats).
4965 // Nothing to do here.
4968 // Attempt to route more than available results in a failure.
4969 let route_params = RouteParameters::from_payment_params_and_value(
4970 payment_params.clone(), 350_000);
4971 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4972 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4973 &scorer, &Default::default(), &random_seed_bytes) {
4974 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4975 } else { panic!(); }
4979 // Now, attempt to route 300 sats (exact amount we can route).
4980 // Our algorithm should provide us with these 3 paths, 100 sats each.
4981 let route_params = RouteParameters::from_payment_params_and_value(
4982 payment_params, 300_000);
4983 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4984 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4985 assert_eq!(route.paths.len(), 3);
4987 let mut total_amount_paid_msat = 0;
4988 for path in &route.paths {
4989 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4990 total_amount_paid_msat += path.final_value_msat();
4992 assert_eq!(total_amount_paid_msat, 300_000);
4998 fn mpp_cheaper_route_test() {
4999 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5000 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5001 let scorer = ln_test_utils::TestScorer::new();
5002 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5003 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5004 let config = UserConfig::default();
5005 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5007 // This test checks that if we have two cheaper paths and one more expensive path,
5008 // so that liquidity-wise any 2 of 3 combination is sufficient,
5009 // two cheaper paths will be taken.
5010 // These paths have equal available liquidity.
5012 // We need a combination of 3 paths:
5013 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5014 // Note that these paths overlap (channels 5, 12, 13).
5015 // Each path will have 100 sats capacity, those channels which
5016 // are used twice will have 200 sats capacity.
5018 // Disable other potential paths.
5019 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5020 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5021 short_channel_id: 2,
5024 cltv_expiry_delta: 0,
5025 htlc_minimum_msat: 0,
5026 htlc_maximum_msat: 100_000,
5028 fee_proportional_millionths: 0,
5029 excess_data: Vec::new()
5031 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5032 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5033 short_channel_id: 7,
5036 cltv_expiry_delta: 0,
5037 htlc_minimum_msat: 0,
5038 htlc_maximum_msat: 100_000,
5040 fee_proportional_millionths: 0,
5041 excess_data: Vec::new()
5044 // Path via {node0, node2} is channels {1, 3, 5}.
5045 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5046 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5047 short_channel_id: 1,
5050 cltv_expiry_delta: 0,
5051 htlc_minimum_msat: 0,
5052 htlc_maximum_msat: 100_000,
5054 fee_proportional_millionths: 0,
5055 excess_data: Vec::new()
5057 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5058 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5059 short_channel_id: 3,
5062 cltv_expiry_delta: 0,
5063 htlc_minimum_msat: 0,
5064 htlc_maximum_msat: 100_000,
5066 fee_proportional_millionths: 0,
5067 excess_data: Vec::new()
5070 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5071 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5072 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5073 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5074 short_channel_id: 5,
5077 cltv_expiry_delta: 0,
5078 htlc_minimum_msat: 0,
5079 htlc_maximum_msat: 200_000,
5081 fee_proportional_millionths: 0,
5082 excess_data: Vec::new()
5085 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5086 // Add 100 sats to the capacities of {12, 13}, because these channels
5087 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5088 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5089 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5090 short_channel_id: 12,
5093 cltv_expiry_delta: 0,
5094 htlc_minimum_msat: 0,
5095 htlc_maximum_msat: 200_000,
5097 fee_proportional_millionths: 0,
5098 excess_data: Vec::new()
5100 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5101 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5102 short_channel_id: 13,
5105 cltv_expiry_delta: 0,
5106 htlc_minimum_msat: 0,
5107 htlc_maximum_msat: 200_000,
5109 fee_proportional_millionths: 0,
5110 excess_data: Vec::new()
5113 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5114 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5115 short_channel_id: 6,
5118 cltv_expiry_delta: 0,
5119 htlc_minimum_msat: 0,
5120 htlc_maximum_msat: 100_000,
5121 fee_base_msat: 1_000,
5122 fee_proportional_millionths: 0,
5123 excess_data: Vec::new()
5125 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5126 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5127 short_channel_id: 11,
5130 cltv_expiry_delta: 0,
5131 htlc_minimum_msat: 0,
5132 htlc_maximum_msat: 100_000,
5134 fee_proportional_millionths: 0,
5135 excess_data: Vec::new()
5138 // Path via {node7, node2} is channels {12, 13, 5}.
5139 // We already limited them to 200 sats (they are used twice for 100 sats).
5140 // Nothing to do here.
5143 // Now, attempt to route 180 sats.
5144 // Our algorithm should provide us with these 2 paths.
5145 let route_params = RouteParameters::from_payment_params_and_value(
5146 payment_params, 180_000);
5147 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5148 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5149 assert_eq!(route.paths.len(), 2);
5151 let mut total_value_transferred_msat = 0;
5152 let mut total_paid_msat = 0;
5153 for path in &route.paths {
5154 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5155 total_value_transferred_msat += path.final_value_msat();
5156 for hop in &path.hops {
5157 total_paid_msat += hop.fee_msat;
5160 // If we paid fee, this would be higher.
5161 assert_eq!(total_value_transferred_msat, 180_000);
5162 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5163 assert_eq!(total_fees_paid, 0);
5168 fn fees_on_mpp_route_test() {
5169 // This test makes sure that MPP algorithm properly takes into account
5170 // fees charged on the channels, by making the fees impactful:
5171 // if the fee is not properly accounted for, the behavior is different.
5172 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5173 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5174 let scorer = ln_test_utils::TestScorer::new();
5175 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5176 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5177 let config = UserConfig::default();
5178 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5180 // We need a route consisting of 2 paths:
5181 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5182 // We will route 200 sats, Each path will have 100 sats capacity.
5184 // This test is not particularly stable: e.g.,
5185 // there's a way to route via {node0, node2, node4}.
5186 // It works while pathfinding is deterministic, but can be broken otherwise.
5187 // It's fine to ignore this concern for now.
5189 // Disable other potential paths.
5190 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5191 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5192 short_channel_id: 2,
5195 cltv_expiry_delta: 0,
5196 htlc_minimum_msat: 0,
5197 htlc_maximum_msat: 100_000,
5199 fee_proportional_millionths: 0,
5200 excess_data: Vec::new()
5203 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5204 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5205 short_channel_id: 7,
5208 cltv_expiry_delta: 0,
5209 htlc_minimum_msat: 0,
5210 htlc_maximum_msat: 100_000,
5212 fee_proportional_millionths: 0,
5213 excess_data: Vec::new()
5216 // Path via {node0, node2} is channels {1, 3, 5}.
5217 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5218 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5219 short_channel_id: 1,
5222 cltv_expiry_delta: 0,
5223 htlc_minimum_msat: 0,
5224 htlc_maximum_msat: 100_000,
5226 fee_proportional_millionths: 0,
5227 excess_data: Vec::new()
5229 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5230 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5231 short_channel_id: 3,
5234 cltv_expiry_delta: 0,
5235 htlc_minimum_msat: 0,
5236 htlc_maximum_msat: 100_000,
5238 fee_proportional_millionths: 0,
5239 excess_data: Vec::new()
5242 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5243 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5244 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5245 short_channel_id: 5,
5248 cltv_expiry_delta: 0,
5249 htlc_minimum_msat: 0,
5250 htlc_maximum_msat: 100_000,
5252 fee_proportional_millionths: 0,
5253 excess_data: Vec::new()
5256 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5257 // All channels should be 100 sats capacity. But for the fee experiment,
5258 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5259 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5260 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5261 // so no matter how large are other channels,
5262 // the whole path will be limited by 100 sats with just these 2 conditions:
5263 // - channel 12 capacity is 250 sats
5264 // - fee for channel 6 is 150 sats
5265 // Let's test this by enforcing these 2 conditions and removing other limits.
5266 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5267 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5268 short_channel_id: 12,
5271 cltv_expiry_delta: 0,
5272 htlc_minimum_msat: 0,
5273 htlc_maximum_msat: 250_000,
5275 fee_proportional_millionths: 0,
5276 excess_data: Vec::new()
5278 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5279 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5280 short_channel_id: 13,
5283 cltv_expiry_delta: 0,
5284 htlc_minimum_msat: 0,
5285 htlc_maximum_msat: MAX_VALUE_MSAT,
5287 fee_proportional_millionths: 0,
5288 excess_data: Vec::new()
5291 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5292 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5293 short_channel_id: 6,
5296 cltv_expiry_delta: 0,
5297 htlc_minimum_msat: 0,
5298 htlc_maximum_msat: MAX_VALUE_MSAT,
5299 fee_base_msat: 150_000,
5300 fee_proportional_millionths: 0,
5301 excess_data: Vec::new()
5303 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5304 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5305 short_channel_id: 11,
5308 cltv_expiry_delta: 0,
5309 htlc_minimum_msat: 0,
5310 htlc_maximum_msat: MAX_VALUE_MSAT,
5312 fee_proportional_millionths: 0,
5313 excess_data: Vec::new()
5317 // Attempt to route more than available results in a failure.
5318 let route_params = RouteParameters::from_payment_params_and_value(
5319 payment_params.clone(), 210_000);
5320 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5321 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5322 &scorer, &Default::default(), &random_seed_bytes) {
5323 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5324 } else { panic!(); }
5328 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5329 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5330 max_total_routing_fee_msat: Some(149_999) };
5331 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5332 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5333 &scorer, &(), &random_seed_bytes) {
5334 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5335 } else { panic!(); }
5339 // Now, attempt to route 200 sats (exact amount we can route).
5340 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5341 max_total_routing_fee_msat: Some(150_000) };
5342 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5343 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5344 assert_eq!(route.paths.len(), 2);
5346 let mut total_amount_paid_msat = 0;
5347 for path in &route.paths {
5348 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5349 total_amount_paid_msat += path.final_value_msat();
5351 assert_eq!(total_amount_paid_msat, 200_000);
5352 assert_eq!(route.get_total_fees(), 150_000);
5357 fn mpp_with_last_hops() {
5358 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5359 // via a single last-hop route hint, we'd fail to route if we first collected routes
5360 // totaling close but not quite enough to fund the full payment.
5362 // This was because we considered last-hop hints to have exactly the sought payment amount
5363 // instead of the amount we were trying to collect, needlessly limiting our path searching
5364 // at the very first hop.
5366 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5367 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5368 // to only have the remaining to-collect amount in available liquidity.
5370 // This bug appeared in production in some specific channel configurations.
5371 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5372 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5373 let scorer = ln_test_utils::TestScorer::new();
5374 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5375 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5376 let config = UserConfig::default();
5377 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5378 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5379 src_node_id: nodes[2],
5380 short_channel_id: 42,
5381 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5382 cltv_expiry_delta: 42,
5383 htlc_minimum_msat: None,
5384 htlc_maximum_msat: None,
5385 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5387 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5388 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5389 // would first use the no-fee route and then fail to find a path along the second route as
5390 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5391 // under 5% of our payment amount.
5392 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5393 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5394 short_channel_id: 1,
5397 cltv_expiry_delta: (5 << 4) | 5,
5398 htlc_minimum_msat: 0,
5399 htlc_maximum_msat: 99_000,
5400 fee_base_msat: u32::max_value(),
5401 fee_proportional_millionths: u32::max_value(),
5402 excess_data: Vec::new()
5404 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5405 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5406 short_channel_id: 2,
5409 cltv_expiry_delta: (5 << 4) | 3,
5410 htlc_minimum_msat: 0,
5411 htlc_maximum_msat: 99_000,
5412 fee_base_msat: u32::max_value(),
5413 fee_proportional_millionths: u32::max_value(),
5414 excess_data: Vec::new()
5416 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5417 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5418 short_channel_id: 4,
5421 cltv_expiry_delta: (4 << 4) | 1,
5422 htlc_minimum_msat: 0,
5423 htlc_maximum_msat: MAX_VALUE_MSAT,
5425 fee_proportional_millionths: 0,
5426 excess_data: Vec::new()
5428 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5429 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5430 short_channel_id: 13,
5432 flags: 0|2, // Channel disabled
5433 cltv_expiry_delta: (13 << 4) | 1,
5434 htlc_minimum_msat: 0,
5435 htlc_maximum_msat: MAX_VALUE_MSAT,
5437 fee_proportional_millionths: 2000000,
5438 excess_data: Vec::new()
5441 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5443 let route_params = RouteParameters::from_payment_params_and_value(
5444 payment_params, 100_000);
5445 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5446 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5447 assert_eq!(route.paths.len(), 2);
5448 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5449 // Paths are manually ordered ordered by SCID, so:
5450 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5451 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5452 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5453 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5454 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5455 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5456 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5457 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5458 assert_eq!(route.get_total_fees(), 1);
5459 assert_eq!(route.get_total_amount(), 100_000);
5463 fn drop_lowest_channel_mpp_route_test() {
5464 // This test checks that low-capacity channel is dropped when after
5465 // path finding we realize that we found more capacity than we need.
5466 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5467 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5468 let scorer = ln_test_utils::TestScorer::new();
5469 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5470 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5471 let config = UserConfig::default();
5472 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5473 .with_max_channel_saturation_power_of_half(0);
5475 // We need a route consisting of 3 paths:
5476 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5478 // The first and the second paths should be sufficient, but the third should be
5479 // cheaper, so that we select it but drop later.
5481 // First, we set limits on these (previously unlimited) channels.
5482 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5484 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5485 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5486 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5487 short_channel_id: 1,
5490 cltv_expiry_delta: 0,
5491 htlc_minimum_msat: 0,
5492 htlc_maximum_msat: 100_000,
5494 fee_proportional_millionths: 0,
5495 excess_data: Vec::new()
5497 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5498 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5499 short_channel_id: 3,
5502 cltv_expiry_delta: 0,
5503 htlc_minimum_msat: 0,
5504 htlc_maximum_msat: 50_000,
5506 fee_proportional_millionths: 0,
5507 excess_data: Vec::new()
5510 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5511 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5512 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5513 short_channel_id: 12,
5516 cltv_expiry_delta: 0,
5517 htlc_minimum_msat: 0,
5518 htlc_maximum_msat: 60_000,
5520 fee_proportional_millionths: 0,
5521 excess_data: Vec::new()
5523 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5524 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5525 short_channel_id: 13,
5528 cltv_expiry_delta: 0,
5529 htlc_minimum_msat: 0,
5530 htlc_maximum_msat: 60_000,
5532 fee_proportional_millionths: 0,
5533 excess_data: Vec::new()
5536 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5537 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5538 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5539 short_channel_id: 2,
5542 cltv_expiry_delta: 0,
5543 htlc_minimum_msat: 0,
5544 htlc_maximum_msat: 20_000,
5546 fee_proportional_millionths: 0,
5547 excess_data: Vec::new()
5549 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5550 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5551 short_channel_id: 4,
5554 cltv_expiry_delta: 0,
5555 htlc_minimum_msat: 0,
5556 htlc_maximum_msat: 20_000,
5558 fee_proportional_millionths: 0,
5559 excess_data: Vec::new()
5563 // Attempt to route more than available results in a failure.
5564 let route_params = RouteParameters::from_payment_params_and_value(
5565 payment_params.clone(), 150_000);
5566 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5567 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5568 &scorer, &Default::default(), &random_seed_bytes) {
5569 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5570 } else { panic!(); }
5574 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5575 // Our algorithm should provide us with these 3 paths.
5576 let route_params = RouteParameters::from_payment_params_and_value(
5577 payment_params.clone(), 125_000);
5578 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5579 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5580 assert_eq!(route.paths.len(), 3);
5581 let mut total_amount_paid_msat = 0;
5582 for path in &route.paths {
5583 assert_eq!(path.hops.len(), 2);
5584 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5585 total_amount_paid_msat += path.final_value_msat();
5587 assert_eq!(total_amount_paid_msat, 125_000);
5591 // Attempt to route without the last small cheap channel
5592 let route_params = RouteParameters::from_payment_params_and_value(
5593 payment_params, 90_000);
5594 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5595 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5596 assert_eq!(route.paths.len(), 2);
5597 let mut total_amount_paid_msat = 0;
5598 for path in &route.paths {
5599 assert_eq!(path.hops.len(), 2);
5600 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5601 total_amount_paid_msat += path.final_value_msat();
5603 assert_eq!(total_amount_paid_msat, 90_000);
5608 fn min_criteria_consistency() {
5609 // Test that we don't use an inconsistent metric between updating and walking nodes during
5610 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5611 // was updated with a different criterion from the heap sorting, resulting in loops in
5612 // calculated paths. We test for that specific case here.
5614 // We construct a network that looks like this:
5616 // node2 -1(3)2- node3
5620 // node1 -1(5)2- node4 -1(1)2- node6
5626 // We create a loop on the side of our real path - our destination is node 6, with a
5627 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5628 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5629 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5630 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5631 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5632 // "previous hop" being set to node 3, creating a loop in the path.
5633 let secp_ctx = Secp256k1::new();
5634 let logger = Arc::new(ln_test_utils::TestLogger::new());
5635 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5636 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5637 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5638 let scorer = ln_test_utils::TestScorer::new();
5639 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5640 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5641 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5643 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5644 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5645 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5646 short_channel_id: 6,
5649 cltv_expiry_delta: (6 << 4) | 0,
5650 htlc_minimum_msat: 0,
5651 htlc_maximum_msat: MAX_VALUE_MSAT,
5653 fee_proportional_millionths: 0,
5654 excess_data: Vec::new()
5656 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5658 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5659 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5660 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5661 short_channel_id: 5,
5664 cltv_expiry_delta: (5 << 4) | 0,
5665 htlc_minimum_msat: 0,
5666 htlc_maximum_msat: MAX_VALUE_MSAT,
5668 fee_proportional_millionths: 0,
5669 excess_data: Vec::new()
5671 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5673 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5674 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5675 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5676 short_channel_id: 4,
5679 cltv_expiry_delta: (4 << 4) | 0,
5680 htlc_minimum_msat: 0,
5681 htlc_maximum_msat: MAX_VALUE_MSAT,
5683 fee_proportional_millionths: 0,
5684 excess_data: Vec::new()
5686 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5688 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5689 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5690 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5691 short_channel_id: 3,
5694 cltv_expiry_delta: (3 << 4) | 0,
5695 htlc_minimum_msat: 0,
5696 htlc_maximum_msat: MAX_VALUE_MSAT,
5698 fee_proportional_millionths: 0,
5699 excess_data: Vec::new()
5701 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5703 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5704 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5705 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5706 short_channel_id: 2,
5709 cltv_expiry_delta: (2 << 4) | 0,
5710 htlc_minimum_msat: 0,
5711 htlc_maximum_msat: MAX_VALUE_MSAT,
5713 fee_proportional_millionths: 0,
5714 excess_data: Vec::new()
5717 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5718 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5719 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5720 short_channel_id: 1,
5723 cltv_expiry_delta: (1 << 4) | 0,
5724 htlc_minimum_msat: 100,
5725 htlc_maximum_msat: MAX_VALUE_MSAT,
5727 fee_proportional_millionths: 0,
5728 excess_data: Vec::new()
5730 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5733 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5734 let route_params = RouteParameters::from_payment_params_and_value(
5735 payment_params, 10_000);
5736 let route = get_route(&our_id, &route_params, &network.read_only(), None,
5737 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5738 assert_eq!(route.paths.len(), 1);
5739 assert_eq!(route.paths[0].hops.len(), 3);
5741 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5742 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5743 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5744 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5745 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5746 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5748 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5749 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5750 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5751 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5752 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5753 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5755 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5756 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5757 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5758 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5759 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5760 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5766 fn exact_fee_liquidity_limit() {
5767 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5768 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5769 // we calculated fees on a higher value, resulting in us ignoring such paths.
5770 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5771 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5772 let scorer = ln_test_utils::TestScorer::new();
5773 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5774 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5775 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5777 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5779 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5780 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5781 short_channel_id: 2,
5784 cltv_expiry_delta: 0,
5785 htlc_minimum_msat: 0,
5786 htlc_maximum_msat: 85_000,
5788 fee_proportional_millionths: 0,
5789 excess_data: Vec::new()
5792 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5793 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5794 short_channel_id: 12,
5797 cltv_expiry_delta: (4 << 4) | 1,
5798 htlc_minimum_msat: 0,
5799 htlc_maximum_msat: 270_000,
5801 fee_proportional_millionths: 1000000,
5802 excess_data: Vec::new()
5806 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5807 // 200% fee charged channel 13 in the 1-to-2 direction.
5808 let mut route_params = RouteParameters::from_payment_params_and_value(
5809 payment_params, 90_000);
5810 route_params.max_total_routing_fee_msat = Some(90_000*2);
5811 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5812 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5813 assert_eq!(route.paths.len(), 1);
5814 assert_eq!(route.paths[0].hops.len(), 2);
5816 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5817 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5818 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5819 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5820 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5821 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5823 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5824 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5825 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5826 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5827 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5828 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5833 fn htlc_max_reduction_below_min() {
5834 // Test that if, while walking the graph, we reduce the value being sent to meet an
5835 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5836 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5837 // resulting in us thinking there is no possible path, even if other paths exist.
5838 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5839 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5840 let scorer = ln_test_utils::TestScorer::new();
5841 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5842 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5843 let config = UserConfig::default();
5844 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5846 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5847 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5848 // then try to send 90_000.
5849 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5850 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5851 short_channel_id: 2,
5854 cltv_expiry_delta: 0,
5855 htlc_minimum_msat: 0,
5856 htlc_maximum_msat: 80_000,
5858 fee_proportional_millionths: 0,
5859 excess_data: Vec::new()
5861 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5862 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5863 short_channel_id: 4,
5866 cltv_expiry_delta: (4 << 4) | 1,
5867 htlc_minimum_msat: 90_000,
5868 htlc_maximum_msat: MAX_VALUE_MSAT,
5870 fee_proportional_millionths: 0,
5871 excess_data: Vec::new()
5875 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5876 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5877 // expensive) channels 12-13 path.
5878 let mut route_params = RouteParameters::from_payment_params_and_value(
5879 payment_params, 90_000);
5880 route_params.max_total_routing_fee_msat = Some(90_000*2);
5881 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5882 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5883 assert_eq!(route.paths.len(), 1);
5884 assert_eq!(route.paths[0].hops.len(), 2);
5886 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5887 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5888 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5889 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5890 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5891 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5893 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5894 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5895 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5896 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5897 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5898 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5903 fn multiple_direct_first_hops() {
5904 // Previously we'd only ever considered one first hop path per counterparty.
5905 // However, as we don't restrict users to one channel per peer, we really need to support
5906 // looking at all first hop paths.
5907 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5908 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5909 // route over multiple channels with the same first hop.
5910 let secp_ctx = Secp256k1::new();
5911 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5912 let logger = Arc::new(ln_test_utils::TestLogger::new());
5913 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5914 let scorer = ln_test_utils::TestScorer::new();
5915 let config = UserConfig::default();
5916 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5917 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5918 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5921 let route_params = RouteParameters::from_payment_params_and_value(
5922 payment_params.clone(), 100_000);
5923 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5924 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5925 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5926 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5927 assert_eq!(route.paths.len(), 1);
5928 assert_eq!(route.paths[0].hops.len(), 1);
5930 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5931 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5932 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5935 let route_params = RouteParameters::from_payment_params_and_value(
5936 payment_params.clone(), 100_000);
5937 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5938 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5939 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5940 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5941 assert_eq!(route.paths.len(), 2);
5942 assert_eq!(route.paths[0].hops.len(), 1);
5943 assert_eq!(route.paths[1].hops.len(), 1);
5945 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5946 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5948 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5949 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5951 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5952 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5956 // If we have a bunch of outbound channels to the same node, where most are not
5957 // sufficient to pay the full payment, but one is, we should default to just using the
5958 // one single channel that has sufficient balance, avoiding MPP.
5960 // If we have several options above the 3xpayment value threshold, we should pick the
5961 // smallest of them, avoiding further fragmenting our available outbound balance to
5963 let route_params = RouteParameters::from_payment_params_and_value(
5964 payment_params, 100_000);
5965 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5966 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5967 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5968 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5969 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5970 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5971 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5972 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5973 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5974 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5975 assert_eq!(route.paths.len(), 1);
5976 assert_eq!(route.paths[0].hops.len(), 1);
5978 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5979 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5980 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5985 fn prefers_shorter_route_with_higher_fees() {
5986 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5987 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5988 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5990 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5991 let scorer = ln_test_utils::TestScorer::new();
5992 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5993 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5994 let route_params = RouteParameters::from_payment_params_and_value(
5995 payment_params.clone(), 100);
5996 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
5997 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5998 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6000 assert_eq!(route.get_total_fees(), 100);
6001 assert_eq!(route.get_total_amount(), 100);
6002 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6004 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6005 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6006 let scorer = FixedPenaltyScorer::with_penalty(100);
6007 let route_params = RouteParameters::from_payment_params_and_value(
6008 payment_params, 100);
6009 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6010 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6011 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6013 assert_eq!(route.get_total_fees(), 300);
6014 assert_eq!(route.get_total_amount(), 100);
6015 assert_eq!(path, vec![2, 4, 7, 10]);
6018 struct BadChannelScorer {
6019 short_channel_id: u64,
6023 impl Writeable for BadChannelScorer {
6024 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6026 impl ScoreLookUp for BadChannelScorer {
6027 type ScoreParams = ();
6028 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6029 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
6033 struct BadNodeScorer {
6038 impl Writeable for BadNodeScorer {
6039 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6042 impl ScoreLookUp for BadNodeScorer {
6043 type ScoreParams = ();
6044 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6045 if *target == self.node_id { u64::max_value() } else { 0 }
6050 fn avoids_routing_through_bad_channels_and_nodes() {
6051 let (secp_ctx, network, _, _, logger) = build_graph();
6052 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6053 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6054 let network_graph = network.read_only();
6056 // A path to nodes[6] exists when no penalties are applied to any channel.
6057 let scorer = ln_test_utils::TestScorer::new();
6058 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6059 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6060 let route_params = RouteParameters::from_payment_params_and_value(
6061 payment_params, 100);
6062 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6063 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6064 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6066 assert_eq!(route.get_total_fees(), 100);
6067 assert_eq!(route.get_total_amount(), 100);
6068 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6070 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6071 let scorer = BadChannelScorer { short_channel_id: 6 };
6072 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6073 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6074 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6076 assert_eq!(route.get_total_fees(), 300);
6077 assert_eq!(route.get_total_amount(), 100);
6078 assert_eq!(path, vec![2, 4, 7, 10]);
6080 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6081 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6082 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6083 &scorer, &Default::default(), &random_seed_bytes) {
6084 Err(LightningError { err, .. } ) => {
6085 assert_eq!(err, "Failed to find a path to the given destination");
6087 Ok(_) => panic!("Expected error"),
6092 fn total_fees_single_path() {
6094 paths: vec![Path { hops: vec![
6096 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6097 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6098 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6101 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6102 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6103 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6106 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6107 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6108 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6110 ], blinded_tail: None }],
6114 assert_eq!(route.get_total_fees(), 250);
6115 assert_eq!(route.get_total_amount(), 225);
6119 fn total_fees_multi_path() {
6121 paths: vec![Path { hops: vec![
6123 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6124 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6125 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6128 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6129 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6130 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6132 ], blinded_tail: None }, Path { hops: vec![
6134 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6135 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6136 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6139 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6140 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6141 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6143 ], blinded_tail: None }],
6147 assert_eq!(route.get_total_fees(), 200);
6148 assert_eq!(route.get_total_amount(), 300);
6152 fn total_empty_route_no_panic() {
6153 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6154 // would both panic if the route was completely empty. We test to ensure they return 0
6155 // here, even though its somewhat nonsensical as a route.
6156 let route = Route { paths: Vec::new(), route_params: None };
6158 assert_eq!(route.get_total_fees(), 0);
6159 assert_eq!(route.get_total_amount(), 0);
6163 fn limits_total_cltv_delta() {
6164 let (secp_ctx, network, _, _, logger) = build_graph();
6165 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6166 let network_graph = network.read_only();
6168 let scorer = ln_test_utils::TestScorer::new();
6170 // Make sure that generally there is at least one route available
6171 let feasible_max_total_cltv_delta = 1008;
6172 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6173 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6174 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6175 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6176 let route_params = RouteParameters::from_payment_params_and_value(
6177 feasible_payment_params, 100);
6178 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6179 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6180 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6181 assert_ne!(path.len(), 0);
6183 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6184 let fail_max_total_cltv_delta = 23;
6185 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6186 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6187 let route_params = RouteParameters::from_payment_params_and_value(
6188 fail_payment_params, 100);
6189 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6190 &Default::default(), &random_seed_bytes)
6192 Err(LightningError { err, .. } ) => {
6193 assert_eq!(err, "Failed to find a path to the given destination");
6195 Ok(_) => panic!("Expected error"),
6200 fn avoids_recently_failed_paths() {
6201 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6202 // randomly inserting channels into it until we can't find a route anymore.
6203 let (secp_ctx, network, _, _, logger) = build_graph();
6204 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6205 let network_graph = network.read_only();
6207 let scorer = ln_test_utils::TestScorer::new();
6208 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6209 .with_max_path_count(1);
6210 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6211 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6213 // We should be able to find a route initially, and then after we fail a few random
6214 // channels eventually we won't be able to any longer.
6215 let route_params = RouteParameters::from_payment_params_and_value(
6216 payment_params.clone(), 100);
6217 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6218 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6220 let route_params = RouteParameters::from_payment_params_and_value(
6221 payment_params.clone(), 100);
6222 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6223 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6225 for chan in route.paths[0].hops.iter() {
6226 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6228 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6229 % route.paths[0].hops.len();
6230 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6236 fn limits_path_length() {
6237 let (secp_ctx, network, _, _, logger) = build_line_graph();
6238 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6239 let network_graph = network.read_only();
6241 let scorer = ln_test_utils::TestScorer::new();
6242 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6243 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6245 // First check we can actually create a long route on this graph.
6246 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6247 let route_params = RouteParameters::from_payment_params_and_value(
6248 feasible_payment_params, 100);
6249 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6250 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6251 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6252 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6254 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6255 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6256 let route_params = RouteParameters::from_payment_params_and_value(
6257 fail_payment_params, 100);
6258 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6259 &Default::default(), &random_seed_bytes)
6261 Err(LightningError { err, .. } ) => {
6262 assert_eq!(err, "Failed to find a path to the given destination");
6264 Ok(_) => panic!("Expected error"),
6269 fn adds_and_limits_cltv_offset() {
6270 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6271 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6273 let scorer = ln_test_utils::TestScorer::new();
6275 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6276 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6277 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6278 let route_params = RouteParameters::from_payment_params_and_value(
6279 payment_params.clone(), 100);
6280 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6281 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6282 assert_eq!(route.paths.len(), 1);
6284 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6286 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6287 let mut route_default = route.clone();
6288 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6289 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6290 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6291 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6292 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6294 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6295 let mut route_limited = route.clone();
6296 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6297 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6298 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6299 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6300 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6304 fn adds_plausible_cltv_offset() {
6305 let (secp_ctx, network, _, _, logger) = build_graph();
6306 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6307 let network_graph = network.read_only();
6308 let network_nodes = network_graph.nodes();
6309 let network_channels = network_graph.channels();
6310 let scorer = ln_test_utils::TestScorer::new();
6311 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6312 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6313 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6315 let route_params = RouteParameters::from_payment_params_and_value(
6316 payment_params.clone(), 100);
6317 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6318 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6319 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6321 let mut path_plausibility = vec![];
6323 for p in route.paths {
6324 // 1. Select random observation point
6325 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6326 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6328 prng.process_in_place(&mut random_bytes);
6329 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6330 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6332 // 2. Calculate what CLTV expiry delta we would observe there
6333 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6335 // 3. Starting from the observation point, find candidate paths
6336 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6337 candidates.push_back((observation_point, vec![]));
6339 let mut found_plausible_candidate = false;
6341 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6342 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6343 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6344 found_plausible_candidate = true;
6345 break 'candidate_loop;
6349 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6350 for channel_id in &cur_node.channels {
6351 if let Some(channel_info) = network_channels.get(&channel_id) {
6352 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6353 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6354 if cur_path_cltv_deltas.iter().sum::<u32>()
6355 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6356 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6357 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6358 candidates.push_back((*next_id, new_path_cltv_deltas));
6366 path_plausibility.push(found_plausible_candidate);
6368 assert!(path_plausibility.iter().all(|x| *x));
6372 fn builds_correct_path_from_hops() {
6373 let (secp_ctx, network, _, _, logger) = build_graph();
6374 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6375 let network_graph = network.read_only();
6377 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6378 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6380 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6381 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6382 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6383 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6384 Arc::clone(&logger), &random_seed_bytes).unwrap();
6385 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6386 assert_eq!(hops.len(), route.paths[0].hops.len());
6387 for (idx, hop_pubkey) in hops.iter().enumerate() {
6388 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6393 fn avoids_saturating_channels() {
6394 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6395 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6396 let decay_params = ProbabilisticScoringDecayParameters::default();
6397 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6399 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6400 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6401 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6402 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6403 short_channel_id: 4,
6406 cltv_expiry_delta: (4 << 4) | 1,
6407 htlc_minimum_msat: 0,
6408 htlc_maximum_msat: 250_000_000,
6410 fee_proportional_millionths: 0,
6411 excess_data: Vec::new()
6413 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6414 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6415 short_channel_id: 13,
6418 cltv_expiry_delta: (13 << 4) | 1,
6419 htlc_minimum_msat: 0,
6420 htlc_maximum_msat: 250_000_000,
6422 fee_proportional_millionths: 0,
6423 excess_data: Vec::new()
6426 let config = UserConfig::default();
6427 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6428 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6429 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6430 // 100,000 sats is less than the available liquidity on each channel, set above.
6431 let route_params = RouteParameters::from_payment_params_and_value(
6432 payment_params, 100_000_000);
6433 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6434 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6435 assert_eq!(route.paths.len(), 2);
6436 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6437 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6440 #[cfg(not(feature = "no-std"))]
6441 pub(super) fn random_init_seed() -> u64 {
6442 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6443 use core::hash::{BuildHasher, Hasher};
6444 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6445 println!("Using seed of {}", seed);
6450 #[cfg(not(feature = "no-std"))]
6451 fn generate_routes() {
6452 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6454 let logger = ln_test_utils::TestLogger::new();
6455 let graph = match super::bench_utils::read_network_graph(&logger) {
6463 let params = ProbabilisticScoringFeeParameters::default();
6464 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6465 let features = super::Bolt11InvoiceFeatures::empty();
6467 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6471 #[cfg(not(feature = "no-std"))]
6472 fn generate_routes_mpp() {
6473 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6475 let logger = ln_test_utils::TestLogger::new();
6476 let graph = match super::bench_utils::read_network_graph(&logger) {
6484 let params = ProbabilisticScoringFeeParameters::default();
6485 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6486 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6488 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6492 #[cfg(not(feature = "no-std"))]
6493 fn generate_large_mpp_routes() {
6494 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6496 let logger = ln_test_utils::TestLogger::new();
6497 let graph = match super::bench_utils::read_network_graph(&logger) {
6505 let params = ProbabilisticScoringFeeParameters::default();
6506 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6507 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6509 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6513 fn honors_manual_penalties() {
6514 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6515 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6517 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6518 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6520 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6521 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6523 // First check set manual penalties are returned by the scorer.
6524 let usage = ChannelUsage {
6526 inflight_htlc_msat: 0,
6527 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6529 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6530 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6531 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
6533 // Then check we can get a normal route
6534 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6535 let route_params = RouteParameters::from_payment_params_and_value(
6536 payment_params, 100);
6537 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6538 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6539 assert!(route.is_ok());
6541 // Then check that we can't get a route if we ban an intermediate node.
6542 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6543 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6544 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6545 assert!(route.is_err());
6547 // Finally make sure we can route again, when we remove the ban.
6548 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6549 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6550 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6551 assert!(route.is_ok());
6555 fn abide_by_route_hint_max_htlc() {
6556 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6557 // params in the final route.
6558 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6559 let netgraph = network_graph.read_only();
6560 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6561 let scorer = ln_test_utils::TestScorer::new();
6562 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6563 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6564 let config = UserConfig::default();
6566 let max_htlc_msat = 50_000;
6567 let route_hint_1 = RouteHint(vec![RouteHintHop {
6568 src_node_id: nodes[2],
6569 short_channel_id: 42,
6572 proportional_millionths: 0,
6574 cltv_expiry_delta: 10,
6575 htlc_minimum_msat: None,
6576 htlc_maximum_msat: Some(max_htlc_msat),
6578 let dest_node_id = ln_test_utils::pubkey(42);
6579 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6580 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6581 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6583 // Make sure we'll error if our route hints don't have enough liquidity according to their
6584 // htlc_maximum_msat.
6585 let mut route_params = RouteParameters::from_payment_params_and_value(
6586 payment_params, max_htlc_msat + 1);
6587 route_params.max_total_routing_fee_msat = None;
6588 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6589 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
6592 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6593 } else { panic!(); }
6595 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6596 let mut route_hint_2 = route_hint_1.clone();
6597 route_hint_2.0[0].short_channel_id = 43;
6598 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6599 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6600 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6601 let mut route_params = RouteParameters::from_payment_params_and_value(
6602 payment_params, max_htlc_msat + 1);
6603 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
6604 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
6605 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6606 assert_eq!(route.paths.len(), 2);
6607 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6608 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6612 fn direct_channel_to_hints_with_max_htlc() {
6613 // Check that if we have a first hop channel peer that's connected to multiple provided route
6614 // hints, that we properly split the payment between the route hints if needed.
6615 let logger = Arc::new(ln_test_utils::TestLogger::new());
6616 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6617 let scorer = ln_test_utils::TestScorer::new();
6618 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6619 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6620 let config = UserConfig::default();
6622 let our_node_id = ln_test_utils::pubkey(42);
6623 let intermed_node_id = ln_test_utils::pubkey(43);
6624 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6626 let amt_msat = 900_000;
6627 let max_htlc_msat = 500_000;
6628 let route_hint_1 = RouteHint(vec![RouteHintHop {
6629 src_node_id: intermed_node_id,
6630 short_channel_id: 44,
6633 proportional_millionths: 0,
6635 cltv_expiry_delta: 10,
6636 htlc_minimum_msat: None,
6637 htlc_maximum_msat: Some(max_htlc_msat),
6639 src_node_id: intermed_node_id,
6640 short_channel_id: 45,
6643 proportional_millionths: 0,
6645 cltv_expiry_delta: 10,
6646 htlc_minimum_msat: None,
6647 // Check that later route hint max htlcs don't override earlier ones
6648 htlc_maximum_msat: Some(max_htlc_msat - 50),
6650 let mut route_hint_2 = route_hint_1.clone();
6651 route_hint_2.0[0].short_channel_id = 46;
6652 route_hint_2.0[1].short_channel_id = 47;
6653 let dest_node_id = ln_test_utils::pubkey(44);
6654 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6655 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6656 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6658 let route_params = RouteParameters::from_payment_params_and_value(
6659 payment_params, amt_msat);
6660 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6661 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6662 &Default::default(), &random_seed_bytes).unwrap();
6663 assert_eq!(route.paths.len(), 2);
6664 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6665 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6666 assert_eq!(route.get_total_amount(), amt_msat);
6668 // Re-run but with two first hop channels connected to the same route hint peers that must be
6670 let first_hops = vec![
6671 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6672 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6674 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6675 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6676 &Default::default(), &random_seed_bytes).unwrap();
6677 assert_eq!(route.paths.len(), 2);
6678 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6679 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6680 assert_eq!(route.get_total_amount(), amt_msat);
6682 // Make sure this works for blinded route hints.
6683 let blinded_path = BlindedPath {
6684 introduction_node_id: intermed_node_id,
6685 blinding_point: ln_test_utils::pubkey(42),
6687 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6688 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6691 let blinded_payinfo = BlindedPayInfo {
6693 fee_proportional_millionths: 0,
6694 htlc_minimum_msat: 1,
6695 htlc_maximum_msat: max_htlc_msat,
6696 cltv_expiry_delta: 10,
6697 features: BlindedHopFeatures::empty(),
6699 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6700 let payment_params = PaymentParameters::blinded(vec![
6701 (blinded_payinfo.clone(), blinded_path.clone()),
6702 (blinded_payinfo.clone(), blinded_path.clone())])
6703 .with_bolt12_features(bolt12_features).unwrap();
6704 let route_params = RouteParameters::from_payment_params_and_value(
6705 payment_params, amt_msat);
6706 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6707 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6708 &Default::default(), &random_seed_bytes).unwrap();
6709 assert_eq!(route.paths.len(), 2);
6710 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6711 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6712 assert_eq!(route.get_total_amount(), amt_msat);
6716 fn blinded_route_ser() {
6717 let blinded_path_1 = BlindedPath {
6718 introduction_node_id: ln_test_utils::pubkey(42),
6719 blinding_point: ln_test_utils::pubkey(43),
6721 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6722 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6725 let blinded_path_2 = BlindedPath {
6726 introduction_node_id: ln_test_utils::pubkey(46),
6727 blinding_point: ln_test_utils::pubkey(47),
6729 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6730 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6733 // (De)serialize a Route with 1 blinded path out of two total paths.
6734 let mut route = Route { paths: vec![Path {
6735 hops: vec![RouteHop {
6736 pubkey: ln_test_utils::pubkey(50),
6737 node_features: NodeFeatures::empty(),
6738 short_channel_id: 42,
6739 channel_features: ChannelFeatures::empty(),
6741 cltv_expiry_delta: 0,
6742 maybe_announced_channel: true,
6744 blinded_tail: Some(BlindedTail {
6745 hops: blinded_path_1.blinded_hops,
6746 blinding_point: blinded_path_1.blinding_point,
6747 excess_final_cltv_expiry_delta: 40,
6748 final_value_msat: 100,
6750 hops: vec![RouteHop {
6751 pubkey: ln_test_utils::pubkey(51),
6752 node_features: NodeFeatures::empty(),
6753 short_channel_id: 43,
6754 channel_features: ChannelFeatures::empty(),
6756 cltv_expiry_delta: 0,
6757 maybe_announced_channel: true,
6758 }], blinded_tail: None }],
6761 let encoded_route = route.encode();
6762 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6763 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6764 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6766 // (De)serialize a Route with two paths, each containing a blinded tail.
6767 route.paths[1].blinded_tail = Some(BlindedTail {
6768 hops: blinded_path_2.blinded_hops,
6769 blinding_point: blinded_path_2.blinding_point,
6770 excess_final_cltv_expiry_delta: 41,
6771 final_value_msat: 101,
6773 let encoded_route = route.encode();
6774 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6775 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6776 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6780 fn blinded_path_inflight_processing() {
6781 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6782 // account for the blinded tail's final amount_msat.
6783 let mut inflight_htlcs = InFlightHtlcs::new();
6784 let blinded_path = BlindedPath {
6785 introduction_node_id: ln_test_utils::pubkey(43),
6786 blinding_point: ln_test_utils::pubkey(48),
6787 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
6790 hops: vec![RouteHop {
6791 pubkey: ln_test_utils::pubkey(42),
6792 node_features: NodeFeatures::empty(),
6793 short_channel_id: 42,
6794 channel_features: ChannelFeatures::empty(),
6796 cltv_expiry_delta: 0,
6797 maybe_announced_channel: false,
6800 pubkey: blinded_path.introduction_node_id,
6801 node_features: NodeFeatures::empty(),
6802 short_channel_id: 43,
6803 channel_features: ChannelFeatures::empty(),
6805 cltv_expiry_delta: 0,
6806 maybe_announced_channel: false,
6808 blinded_tail: Some(BlindedTail {
6809 hops: blinded_path.blinded_hops,
6810 blinding_point: blinded_path.blinding_point,
6811 excess_final_cltv_expiry_delta: 0,
6812 final_value_msat: 200,
6815 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
6816 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
6817 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
6821 fn blinded_path_cltv_shadow_offset() {
6822 // Make sure we add a shadow offset when sending to blinded paths.
6823 let blinded_path = BlindedPath {
6824 introduction_node_id: ln_test_utils::pubkey(43),
6825 blinding_point: ln_test_utils::pubkey(44),
6827 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
6828 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
6831 let mut route = Route { paths: vec![Path {
6832 hops: vec![RouteHop {
6833 pubkey: ln_test_utils::pubkey(42),
6834 node_features: NodeFeatures::empty(),
6835 short_channel_id: 42,
6836 channel_features: ChannelFeatures::empty(),
6838 cltv_expiry_delta: 0,
6839 maybe_announced_channel: false,
6842 pubkey: blinded_path.introduction_node_id,
6843 node_features: NodeFeatures::empty(),
6844 short_channel_id: 43,
6845 channel_features: ChannelFeatures::empty(),
6847 cltv_expiry_delta: 0,
6848 maybe_announced_channel: false,
6851 blinded_tail: Some(BlindedTail {
6852 hops: blinded_path.blinded_hops,
6853 blinding_point: blinded_path.blinding_point,
6854 excess_final_cltv_expiry_delta: 0,
6855 final_value_msat: 200,
6857 }], route_params: None};
6859 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
6860 let (_, network_graph, _, _, _) = build_line_graph();
6861 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
6862 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
6863 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
6867 fn simple_blinded_route_hints() {
6868 do_simple_blinded_route_hints(1);
6869 do_simple_blinded_route_hints(2);
6870 do_simple_blinded_route_hints(3);
6873 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
6874 // Check that we can generate a route to a blinded path with the expected hops.
6875 let (secp_ctx, network, _, _, logger) = build_graph();
6876 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6877 let network_graph = network.read_only();
6879 let scorer = ln_test_utils::TestScorer::new();
6880 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6881 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6883 let mut blinded_path = BlindedPath {
6884 introduction_node_id: nodes[2],
6885 blinding_point: ln_test_utils::pubkey(42),
6886 blinded_hops: Vec::with_capacity(num_blinded_hops),
6888 for i in 0..num_blinded_hops {
6889 blinded_path.blinded_hops.push(
6890 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
6893 let blinded_payinfo = BlindedPayInfo {
6895 fee_proportional_millionths: 500,
6896 htlc_minimum_msat: 1000,
6897 htlc_maximum_msat: 100_000_000,
6898 cltv_expiry_delta: 15,
6899 features: BlindedHopFeatures::empty(),
6902 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
6903 let route_params = RouteParameters::from_payment_params_and_value(
6904 payment_params, 1001);
6905 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6906 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6907 assert_eq!(route.paths.len(), 1);
6908 assert_eq!(route.paths[0].hops.len(), 2);
6910 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
6911 assert_eq!(tail.hops, blinded_path.blinded_hops);
6912 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
6913 assert_eq!(tail.final_value_msat, 1001);
6915 let final_hop = route.paths[0].hops.last().unwrap();
6916 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
6917 if tail.hops.len() > 1 {
6918 assert_eq!(final_hop.fee_msat,
6919 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
6920 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
6922 assert_eq!(final_hop.fee_msat, 0);
6923 assert_eq!(final_hop.cltv_expiry_delta, 0);
6928 fn blinded_path_routing_errors() {
6929 // Check that we can generate a route to a blinded path with the expected hops.
6930 let (secp_ctx, network, _, _, logger) = build_graph();
6931 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6932 let network_graph = network.read_only();
6934 let scorer = ln_test_utils::TestScorer::new();
6935 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6936 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6938 let mut invalid_blinded_path = BlindedPath {
6939 introduction_node_id: nodes[2],
6940 blinding_point: ln_test_utils::pubkey(42),
6942 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
6945 let blinded_payinfo = BlindedPayInfo {
6947 fee_proportional_millionths: 500,
6948 htlc_minimum_msat: 1000,
6949 htlc_maximum_msat: 100_000_000,
6950 cltv_expiry_delta: 15,
6951 features: BlindedHopFeatures::empty(),
6954 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
6955 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
6956 let payment_params = PaymentParameters::blinded(vec![
6957 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
6958 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
6959 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6960 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6961 &scorer, &Default::default(), &random_seed_bytes)
6963 Err(LightningError { err, .. }) => {
6964 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
6966 _ => panic!("Expected error")
6969 invalid_blinded_path.introduction_node_id = our_id;
6970 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
6971 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6972 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6973 &Default::default(), &random_seed_bytes)
6975 Err(LightningError { err, .. }) => {
6976 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
6978 _ => panic!("Expected error")
6981 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
6982 invalid_blinded_path.blinded_hops.clear();
6983 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
6984 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6985 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6986 &Default::default(), &random_seed_bytes)
6988 Err(LightningError { err, .. }) => {
6989 assert_eq!(err, "0-hop blinded path provided");
6991 _ => panic!("Expected error")
6996 fn matching_intro_node_paths_provided() {
6997 // Check that if multiple blinded paths with the same intro node are provided in payment
6998 // parameters, we'll return the correct paths in the resulting MPP route.
6999 let (secp_ctx, network, _, _, logger) = build_graph();
7000 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7001 let network_graph = network.read_only();
7003 let scorer = ln_test_utils::TestScorer::new();
7004 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7005 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7006 let config = UserConfig::default();
7008 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7009 let blinded_path_1 = BlindedPath {
7010 introduction_node_id: nodes[2],
7011 blinding_point: ln_test_utils::pubkey(42),
7013 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7014 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7017 let blinded_payinfo_1 = BlindedPayInfo {
7019 fee_proportional_millionths: 0,
7020 htlc_minimum_msat: 0,
7021 htlc_maximum_msat: 30_000,
7022 cltv_expiry_delta: 0,
7023 features: BlindedHopFeatures::empty(),
7026 let mut blinded_path_2 = blinded_path_1.clone();
7027 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7028 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7029 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7031 let blinded_hints = vec![
7032 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7033 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7035 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7036 .with_bolt12_features(bolt12_features.clone()).unwrap();
7038 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7039 route_params.max_total_routing_fee_msat = Some(100_000);
7040 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7041 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7042 assert_eq!(route.paths.len(), 2);
7043 let mut total_amount_paid_msat = 0;
7044 for path in route.paths.into_iter() {
7045 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7046 if let Some(bt) = &path.blinded_tail {
7047 assert_eq!(bt.blinding_point,
7048 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7049 .map(|(_, bp)| bp.blinding_point).unwrap());
7050 } else { panic!(); }
7051 total_amount_paid_msat += path.final_value_msat();
7053 assert_eq!(total_amount_paid_msat, 100_000);
7057 fn direct_to_intro_node() {
7058 // This previously caused a debug panic in the router when asserting
7059 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7060 // direct channels we failed to account for the fee charged for use of the blinded path.
7063 // node0 -1(1)2 - node1
7064 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7065 // doesn't account for the blinded path fee.
7067 let secp_ctx = Secp256k1::new();
7068 let logger = Arc::new(ln_test_utils::TestLogger::new());
7069 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7070 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7071 let scorer = ln_test_utils::TestScorer::new();
7072 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7073 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7075 let amt_msat = 10_000_000;
7076 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7077 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7078 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7079 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7080 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
7081 short_channel_id: 1,
7084 cltv_expiry_delta: 42,
7085 htlc_minimum_msat: 1_000,
7086 htlc_maximum_msat: 10_000_000,
7088 fee_proportional_millionths: 0,
7089 excess_data: Vec::new()
7091 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7092 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
7093 short_channel_id: 1,
7096 cltv_expiry_delta: 42,
7097 htlc_minimum_msat: 1_000,
7098 htlc_maximum_msat: 10_000_000,
7100 fee_proportional_millionths: 0,
7101 excess_data: Vec::new()
7103 let first_hops = vec![
7104 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7106 let blinded_path = BlindedPath {
7107 introduction_node_id: nodes[1],
7108 blinding_point: ln_test_utils::pubkey(42),
7110 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7111 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7114 let blinded_payinfo = BlindedPayInfo {
7115 fee_base_msat: 1000,
7116 fee_proportional_millionths: 0,
7117 htlc_minimum_msat: 1000,
7118 htlc_maximum_msat: MAX_VALUE_MSAT,
7119 cltv_expiry_delta: 0,
7120 features: BlindedHopFeatures::empty(),
7122 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7124 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7126 let netgraph = network_graph.read_only();
7127 let route_params = RouteParameters::from_payment_params_and_value(
7128 payment_params.clone(), amt_msat);
7129 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7130 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7131 &Default::default(), &random_seed_bytes) {
7132 assert_eq!(err, "Failed to find a path to the given destination");
7133 } else { panic!("Expected error") }
7135 // Sending an exact amount accounting for the blinded path fee works.
7136 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7137 let route_params = RouteParameters::from_payment_params_and_value(
7138 payment_params, amt_minus_blinded_path_fee);
7139 let route = get_route(&nodes[0], &route_params, &netgraph,
7140 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7141 &Default::default(), &random_seed_bytes).unwrap();
7142 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7143 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7147 fn direct_to_matching_intro_nodes() {
7148 // This previously caused us to enter `unreachable` code in the following situation:
7149 // 1. We add a route candidate for intro_node contributing a high amount
7150 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7151 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7152 // amount, and update our route candidate for intro_node for the lower amount
7153 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7154 // lower contribution amount, but fail (this was previously caused by failure to account for
7155 // blinded path fees when adding first_hop<>intro_node candidates)
7156 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7157 // candidate still thinks its path is contributing the original higher amount. This caused us
7158 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7160 let secp_ctx = Secp256k1::new();
7161 let logger = Arc::new(ln_test_utils::TestLogger::new());
7162 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7163 let scorer = ln_test_utils::TestScorer::new();
7164 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7165 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7166 let config = UserConfig::default();
7168 // Values are taken from the fuzz input that uncovered this panic.
7169 let amt_msat = 21_7020_5185_1403_2640;
7170 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7171 let first_hops = vec![
7172 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7173 18446744073709551615)];
7175 let blinded_path = BlindedPath {
7176 introduction_node_id: nodes[1],
7177 blinding_point: ln_test_utils::pubkey(42),
7179 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7180 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7183 let blinded_payinfo = BlindedPayInfo {
7184 fee_base_msat: 5046_2720,
7185 fee_proportional_millionths: 0,
7186 htlc_minimum_msat: 4503_5996_2737_0496,
7187 htlc_maximum_msat: 45_0359_9627_3704_9600,
7188 cltv_expiry_delta: 0,
7189 features: BlindedHopFeatures::empty(),
7191 let mut blinded_hints = vec![
7192 (blinded_payinfo.clone(), blinded_path.clone()),
7193 (blinded_payinfo.clone(), blinded_path.clone()),
7195 blinded_hints[1].0.fee_base_msat = 419_4304;
7196 blinded_hints[1].0.fee_proportional_millionths = 257;
7197 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7198 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7199 blinded_hints[1].0.cltv_expiry_delta = 0;
7201 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7202 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7203 .with_bolt12_features(bolt12_features.clone()).unwrap();
7205 let netgraph = network_graph.read_only();
7206 let route_params = RouteParameters::from_payment_params_and_value(
7207 payment_params, amt_msat);
7208 let route = get_route(&nodes[0], &route_params, &netgraph,
7209 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7210 &Default::default(), &random_seed_bytes).unwrap();
7211 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7212 assert_eq!(route.get_total_amount(), amt_msat);
7216 fn we_are_intro_node_candidate_hops() {
7217 // This previously led to a panic in the router because we'd generate a Path with only a
7218 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7219 // where the origin node is the intro node. We now fully disallow considering candidate hops
7220 // where the origin node is the intro node.
7221 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7222 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7223 let scorer = ln_test_utils::TestScorer::new();
7224 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7225 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7226 let config = UserConfig::default();
7228 // Values are taken from the fuzz input that uncovered this panic.
7229 let amt_msat = 21_7020_5185_1423_0019;
7231 let blinded_path = BlindedPath {
7232 introduction_node_id: our_id,
7233 blinding_point: ln_test_utils::pubkey(42),
7235 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7236 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7239 let blinded_payinfo = BlindedPayInfo {
7240 fee_base_msat: 5052_9027,
7241 fee_proportional_millionths: 0,
7242 htlc_minimum_msat: 21_7020_5185_1423_0019,
7243 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7244 cltv_expiry_delta: 0,
7245 features: BlindedHopFeatures::empty(),
7247 let mut blinded_hints = vec![
7248 (blinded_payinfo.clone(), blinded_path.clone()),
7249 (blinded_payinfo.clone(), blinded_path.clone()),
7251 blinded_hints[1].1.introduction_node_id = nodes[6];
7253 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7254 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7255 .with_bolt12_features(bolt12_features.clone()).unwrap();
7257 let netgraph = network_graph.read_only();
7258 let route_params = RouteParameters::from_payment_params_and_value(
7259 payment_params, amt_msat);
7260 if let Err(LightningError { err, .. }) = get_route(
7261 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &(), &random_seed_bytes
7263 assert_eq!(err, "Failed to find a path to the given destination");
7268 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7269 // This previously led to a debug panic in the router because we'd find an invalid Path with
7270 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7271 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7272 // the payment, when it was intended to only include the final value of the payment.
7273 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7274 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7275 let scorer = ln_test_utils::TestScorer::new();
7276 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7277 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7278 let config = UserConfig::default();
7280 // Values are taken from the fuzz input that uncovered this panic.
7281 let amt_msat = 21_7020_5185_1423_0019;
7283 let blinded_path = BlindedPath {
7284 introduction_node_id: our_id,
7285 blinding_point: ln_test_utils::pubkey(42),
7287 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7288 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7291 let blinded_payinfo = BlindedPayInfo {
7292 fee_base_msat: 10_4425_1395,
7293 fee_proportional_millionths: 0,
7294 htlc_minimum_msat: 21_7301_9934_9094_0931,
7295 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7296 cltv_expiry_delta: 0,
7297 features: BlindedHopFeatures::empty(),
7299 let mut blinded_hints = vec![
7300 (blinded_payinfo.clone(), blinded_path.clone()),
7301 (blinded_payinfo.clone(), blinded_path.clone()),
7302 (blinded_payinfo.clone(), blinded_path.clone()),
7304 blinded_hints[1].0.fee_base_msat = 5052_9027;
7305 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7306 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7308 blinded_hints[2].1.introduction_node_id = nodes[6];
7310 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7311 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7312 .with_bolt12_features(bolt12_features.clone()).unwrap();
7314 let netgraph = network_graph.read_only();
7315 let route_params = RouteParameters::from_payment_params_and_value(
7316 payment_params, amt_msat);
7317 if let Err(LightningError { err, .. }) = get_route(
7318 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &(), &random_seed_bytes
7320 assert_eq!(err, "Failed to find a path to the given destination");
7325 fn min_htlc_overpay_violates_max_htlc() {
7326 do_min_htlc_overpay_violates_max_htlc(true);
7327 do_min_htlc_overpay_violates_max_htlc(false);
7329 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7330 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7331 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7332 // to `targets` and build an invalid path with it, and subsquently hit a debug panic asserting
7333 // that the used liquidity for a hop was less than its available liquidity limit.
7334 let secp_ctx = Secp256k1::new();
7335 let logger = Arc::new(ln_test_utils::TestLogger::new());
7336 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7337 let scorer = ln_test_utils::TestScorer::new();
7338 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7339 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7340 let config = UserConfig::default();
7342 // Values are taken from the fuzz input that uncovered this panic.
7343 let amt_msat = 7_4009_8048;
7344 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7345 let first_hop_outbound_capacity = 2_7345_2000;
7346 let first_hops = vec![get_channel_details(
7347 Some(200), nodes[0], channelmanager::provided_init_features(&config),
7348 first_hop_outbound_capacity
7351 let base_fee = 1_6778_3453;
7352 let htlc_min = 2_5165_8240;
7353 let payment_params = if blinded_payee {
7354 let blinded_path = BlindedPath {
7355 introduction_node_id: nodes[0],
7356 blinding_point: ln_test_utils::pubkey(42),
7358 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7359 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7362 let blinded_payinfo = BlindedPayInfo {
7363 fee_base_msat: base_fee,
7364 fee_proportional_millionths: 0,
7365 htlc_minimum_msat: htlc_min,
7366 htlc_maximum_msat: htlc_min * 1000,
7367 cltv_expiry_delta: 0,
7368 features: BlindedHopFeatures::empty(),
7370 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7371 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
7372 .with_bolt12_features(bolt12_features.clone()).unwrap()
7374 let route_hint = RouteHint(vec![RouteHintHop {
7375 src_node_id: nodes[0],
7376 short_channel_id: 42,
7378 base_msat: base_fee,
7379 proportional_millionths: 0,
7381 cltv_expiry_delta: 10,
7382 htlc_minimum_msat: Some(htlc_min),
7383 htlc_maximum_msat: None,
7386 PaymentParameters::from_node_id(nodes[1], 42)
7387 .with_route_hints(vec![route_hint]).unwrap()
7388 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
7391 let netgraph = network_graph.read_only();
7392 let route_params = RouteParameters::from_payment_params_and_value(
7393 payment_params, amt_msat);
7394 if let Err(LightningError { err, .. }) = get_route(
7395 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7396 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
7398 assert_eq!(err, "Failed to find a path to the given destination");
7403 fn previously_used_liquidity_violates_max_htlc() {
7404 do_previously_used_liquidity_violates_max_htlc(true);
7405 do_previously_used_liquidity_violates_max_htlc(false);
7408 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
7409 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
7410 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
7411 // candidate. In this case, the candidate does not have enough due to a previous path taking up
7412 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
7413 // asserting that the used liquidity for a hop was less than its available liquidity limit.
7414 let secp_ctx = Secp256k1::new();
7415 let logger = Arc::new(ln_test_utils::TestLogger::new());
7416 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7417 let scorer = ln_test_utils::TestScorer::new();
7418 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7419 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7420 let config = UserConfig::default();
7422 // Values are taken from the fuzz input that uncovered this panic.
7423 let amt_msat = 52_4288;
7424 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7425 let first_hops = vec![get_channel_details(
7426 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
7427 ), get_channel_details(
7428 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
7431 let base_fees = [0, 425_9840, 0, 0];
7432 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
7433 let payment_params = if blinded_payee {
7434 let blinded_path = BlindedPath {
7435 introduction_node_id: nodes[0],
7436 blinding_point: ln_test_utils::pubkey(42),
7438 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7439 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7442 let mut blinded_hints = Vec::new();
7443 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
7444 blinded_hints.push((BlindedPayInfo {
7445 fee_base_msat: *base_fee,
7446 fee_proportional_millionths: 0,
7447 htlc_minimum_msat: *htlc_min,
7448 htlc_maximum_msat: htlc_min * 100,
7449 cltv_expiry_delta: 10,
7450 features: BlindedHopFeatures::empty(),
7451 }, blinded_path.clone()));
7453 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7454 PaymentParameters::blinded(blinded_hints.clone())
7455 .with_bolt12_features(bolt12_features.clone()).unwrap()
7457 let mut route_hints = Vec::new();
7458 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
7459 route_hints.push(RouteHint(vec![RouteHintHop {
7460 src_node_id: nodes[0],
7461 short_channel_id: 42 + idx as u64,
7463 base_msat: *base_fee,
7464 proportional_millionths: 0,
7466 cltv_expiry_delta: 10,
7467 htlc_minimum_msat: Some(*htlc_min),
7468 htlc_maximum_msat: Some(htlc_min * 100),
7471 PaymentParameters::from_node_id(nodes[1], 42)
7472 .with_route_hints(route_hints).unwrap()
7473 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
7476 let netgraph = network_graph.read_only();
7477 let route_params = RouteParameters::from_payment_params_and_value(
7478 payment_params, amt_msat);
7480 let route = get_route(
7481 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7482 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
7484 assert_eq!(route.paths.len(), 1);
7485 assert_eq!(route.get_total_amount(), amt_msat);
7489 fn candidate_path_min() {
7490 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
7491 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
7492 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
7493 // would add a connecting first_hop node that did not have enough contribution amount, leading
7494 // to a debug panic upon invalid path construction.
7495 let secp_ctx = Secp256k1::new();
7496 let logger = Arc::new(ln_test_utils::TestLogger::new());
7497 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7498 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
7499 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
7500 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7501 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7502 let config = UserConfig::default();
7504 // Values are taken from the fuzz input that uncovered this panic.
7505 let amt_msat = 7_4009_8048;
7506 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
7507 let first_hops = vec![get_channel_details(
7508 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
7511 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
7512 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7513 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
7514 short_channel_id: 6,
7517 cltv_expiry_delta: (6 << 4) | 0,
7518 htlc_minimum_msat: 0,
7519 htlc_maximum_msat: MAX_VALUE_MSAT,
7521 fee_proportional_millionths: 0,
7522 excess_data: Vec::new()
7524 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
7526 let htlc_min = 2_5165_8240;
7527 let blinded_hints = vec![
7529 fee_base_msat: 1_6778_3453,
7530 fee_proportional_millionths: 0,
7531 htlc_minimum_msat: htlc_min,
7532 htlc_maximum_msat: htlc_min * 100,
7533 cltv_expiry_delta: 10,
7534 features: BlindedHopFeatures::empty(),
7536 introduction_node_id: nodes[0],
7537 blinding_point: ln_test_utils::pubkey(42),
7539 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7540 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7544 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7545 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7546 .with_bolt12_features(bolt12_features.clone()).unwrap();
7547 let route_params = RouteParameters::from_payment_params_and_value(
7548 payment_params, amt_msat);
7549 let netgraph = network_graph.read_only();
7551 if let Err(LightningError { err, .. }) = get_route(
7552 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7553 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
7556 assert_eq!(err, "Failed to find a path to the given destination");
7561 fn path_contribution_includes_min_htlc_overpay() {
7562 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
7563 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
7564 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
7565 // selection, both tested here.
7566 let secp_ctx = Secp256k1::new();
7567 let logger = Arc::new(ln_test_utils::TestLogger::new());
7568 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7569 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
7570 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7571 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7572 let config = UserConfig::default();
7574 // Values are taken from the fuzz input that uncovered this panic.
7575 let amt_msat = 562_0000;
7576 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7577 let first_hops = vec![
7578 get_channel_details(
7579 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
7583 let htlc_mins = [49_0000, 1125_0000];
7584 let payment_params = {
7585 let blinded_path = BlindedPath {
7586 introduction_node_id: nodes[0],
7587 blinding_point: ln_test_utils::pubkey(42),
7589 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7590 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7593 let mut blinded_hints = Vec::new();
7594 for htlc_min in htlc_mins.iter() {
7595 blinded_hints.push((BlindedPayInfo {
7597 fee_proportional_millionths: 0,
7598 htlc_minimum_msat: *htlc_min,
7599 htlc_maximum_msat: *htlc_min * 100,
7600 cltv_expiry_delta: 10,
7601 features: BlindedHopFeatures::empty(),
7602 }, blinded_path.clone()));
7604 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7605 PaymentParameters::blinded(blinded_hints.clone())
7606 .with_bolt12_features(bolt12_features.clone()).unwrap()
7609 let netgraph = network_graph.read_only();
7610 let route_params = RouteParameters::from_payment_params_and_value(
7611 payment_params, amt_msat);
7612 let route = get_route(
7613 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7614 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
7617 assert_eq!(route.paths.len(), 1);
7618 assert_eq!(route.get_total_amount(), amt_msat);
7622 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
7623 pub(crate) mod bench_utils {
7627 use bitcoin::hashes::Hash;
7628 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
7630 use crate::chain::transaction::OutPoint;
7631 use crate::routing::scoring::ScoreUpdate;
7632 use crate::sign::{EntropySource, KeysManager};
7633 use crate::ln::ChannelId;
7634 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
7635 use crate::ln::features::Bolt11InvoiceFeatures;
7636 use crate::routing::gossip::NetworkGraph;
7637 use crate::util::config::UserConfig;
7638 use crate::util::ser::ReadableArgs;
7639 use crate::util::test_utils::TestLogger;
7641 /// Tries to open a network graph file, or panics with a URL to fetch it.
7642 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
7643 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
7644 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
7645 .or_else(|_| { // Fall back to guessing based on the binary location
7646 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
7647 let mut path = std::env::current_exe().unwrap();
7648 path.pop(); // lightning-...
7650 path.pop(); // debug
7651 path.pop(); // target
7652 path.push("lightning");
7653 path.push("net_graph-2023-01-18.bin");
7656 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
7657 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
7658 let mut path = std::env::current_exe().unwrap();
7659 path.pop(); // bench...
7661 path.pop(); // debug
7662 path.pop(); // target
7663 path.pop(); // bench
7664 path.push("lightning");
7665 path.push("net_graph-2023-01-18.bin");
7668 .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");
7669 #[cfg(require_route_graph_test)]
7670 return Ok(res.unwrap());
7671 #[cfg(not(require_route_graph_test))]
7675 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
7676 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
7679 pub(crate) fn payer_pubkey() -> PublicKey {
7680 let secp_ctx = Secp256k1::new();
7681 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
7685 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
7687 channel_id: ChannelId::new_zero(),
7688 counterparty: ChannelCounterparty {
7689 features: channelmanager::provided_init_features(&UserConfig::default()),
7691 unspendable_punishment_reserve: 0,
7692 forwarding_info: None,
7693 outbound_htlc_minimum_msat: None,
7694 outbound_htlc_maximum_msat: None,
7696 funding_txo: Some(OutPoint {
7697 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
7700 short_channel_id: Some(1),
7701 inbound_scid_alias: None,
7702 outbound_scid_alias: None,
7703 channel_value_satoshis: 10_000_000_000,
7705 outbound_capacity_msat: 10_000_000_000,
7706 next_outbound_htlc_minimum_msat: 0,
7707 next_outbound_htlc_limit_msat: 10_000_000_000,
7708 inbound_capacity_msat: 0,
7709 unspendable_punishment_reserve: None,
7710 confirmations_required: None,
7711 confirmations: None,
7712 force_close_spend_delay: None,
7714 is_channel_ready: true,
7717 inbound_htlc_minimum_msat: None,
7718 inbound_htlc_maximum_msat: None,
7720 feerate_sat_per_1000_weight: None,
7721 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
7725 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
7726 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
7727 starting_amount: u64, route_count: usize,
7728 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
7729 let payer = payer_pubkey();
7730 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7731 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7733 let nodes = graph.read_only().nodes().clone();
7734 let mut route_endpoints = Vec::new();
7735 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
7736 // with some routes we picked being un-routable.
7737 for _ in 0..route_count * 3 / 2 {
7739 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7740 let src = PublicKey::from_slice(nodes.unordered_keys()
7741 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
7742 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7743 let dst = PublicKey::from_slice(nodes.unordered_keys()
7744 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
7745 let params = PaymentParameters::from_node_id(dst, 42)
7746 .with_bolt11_features(features.clone()).unwrap();
7747 let first_hop = first_hop(src);
7748 let amt_msat = starting_amount + seed % 1_000_000;
7749 let route_params = RouteParameters::from_payment_params_and_value(
7750 params.clone(), amt_msat);
7752 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
7753 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
7755 // ...and seed the scorer with success and failure data...
7756 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7757 let mut score_amt = seed % 1_000_000_000;
7759 // Generate fail/success paths for a wider range of potential amounts with
7760 // MPP enabled to give us a chance to apply penalties for more potential
7762 let mpp_features = channelmanager::provided_invoice_features(&UserConfig::default());
7763 let params = PaymentParameters::from_node_id(dst, 42)
7764 .with_bolt11_features(mpp_features).unwrap();
7765 let route_params = RouteParameters::from_payment_params_and_value(
7766 params.clone(), score_amt);
7767 let route_res = get_route(&payer, &route_params, &graph.read_only(),
7768 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
7769 &random_seed_bytes);
7770 if let Ok(route) = route_res {
7771 for path in route.paths {
7772 if seed & 0x80 == 0 {
7773 scorer.payment_path_successful(&path);
7775 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
7776 scorer.payment_path_failed(&path, short_channel_id);
7778 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7782 // If we couldn't find a path with a higer amount, reduce and try again.
7786 route_endpoints.push((first_hop, params, amt_msat));
7792 // Because we've changed channel scores, it's possible we'll take different routes to the
7793 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
7794 // requires a too-high CLTV delta.
7795 route_endpoints.retain(|(first_hop, params, amt_msat)| {
7796 let route_params = RouteParameters::from_payment_params_and_value(
7797 params.clone(), *amt_msat);
7798 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
7799 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
7801 route_endpoints.truncate(route_count);
7802 assert_eq!(route_endpoints.len(), route_count);
7810 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
7811 use crate::sign::{EntropySource, KeysManager};
7812 use crate::ln::channelmanager;
7813 use crate::ln::features::Bolt11InvoiceFeatures;
7814 use crate::routing::gossip::NetworkGraph;
7815 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
7816 use crate::util::config::UserConfig;
7817 use crate::util::logger::{Logger, Record};
7818 use crate::util::test_utils::TestLogger;
7820 use criterion::Criterion;
7822 struct DummyLogger {}
7823 impl Logger for DummyLogger {
7824 fn log(&self, _record: &Record) {}
7827 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7828 let logger = TestLogger::new();
7829 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7830 let scorer = FixedPenaltyScorer::with_penalty(0);
7831 generate_routes(bench, &network_graph, scorer, &Default::default(),
7832 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
7835 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7836 let logger = TestLogger::new();
7837 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7838 let scorer = FixedPenaltyScorer::with_penalty(0);
7839 generate_routes(bench, &network_graph, scorer, &Default::default(),
7840 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7841 "generate_mpp_routes_with_zero_penalty_scorer");
7844 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7845 let logger = TestLogger::new();
7846 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7847 let params = ProbabilisticScoringFeeParameters::default();
7848 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7849 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
7850 "generate_routes_with_probabilistic_scorer");
7853 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7854 let logger = TestLogger::new();
7855 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7856 let params = ProbabilisticScoringFeeParameters::default();
7857 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7858 generate_routes(bench, &network_graph, scorer, ¶ms,
7859 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7860 "generate_mpp_routes_with_probabilistic_scorer");
7863 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7864 let logger = TestLogger::new();
7865 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7866 let params = ProbabilisticScoringFeeParameters::default();
7867 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7868 generate_routes(bench, &network_graph, scorer, ¶ms,
7869 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
7870 "generate_large_mpp_routes_with_probabilistic_scorer");
7873 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
7874 let logger = TestLogger::new();
7875 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7876 let mut params = ProbabilisticScoringFeeParameters::default();
7877 params.linear_success_probability = false;
7878 let scorer = ProbabilisticScorer::new(
7879 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7880 generate_routes(bench, &network_graph, scorer, ¶ms,
7881 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7882 "generate_routes_with_nonlinear_probabilistic_scorer");
7885 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
7886 let logger = TestLogger::new();
7887 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7888 let mut params = ProbabilisticScoringFeeParameters::default();
7889 params.linear_success_probability = false;
7890 let scorer = ProbabilisticScorer::new(
7891 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7892 generate_routes(bench, &network_graph, scorer, ¶ms,
7893 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7894 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
7897 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
7898 let logger = TestLogger::new();
7899 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7900 let mut params = ProbabilisticScoringFeeParameters::default();
7901 params.linear_success_probability = false;
7902 let scorer = ProbabilisticScorer::new(
7903 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7904 generate_routes(bench, &network_graph, scorer, ¶ms,
7905 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
7906 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
7909 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
7910 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
7911 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
7912 bench_name: &'static str,
7914 let payer = bench_utils::payer_pubkey();
7915 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7916 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7918 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
7919 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
7921 // ...then benchmark finding paths between the nodes we learned.
7923 bench.bench_function(bench_name, |b| b.iter(|| {
7924 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
7925 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
7926 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
7927 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());