1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The router finds paths within a [`NetworkGraph`] for a payment.
12 use bitcoin::secp256k1::PublicKey;
13 use bitcoin::hashes::Hash;
14 use bitcoin::hashes::sha256::Hash as Sha256;
16 use crate::blinded_path::{BlindedHop, BlindedPath};
17 use crate::ln::PaymentHash;
18 use crate::ln::channelmanager::{ChannelDetails, PaymentId};
19 use crate::ln::features::{Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
20 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
21 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice};
22 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
23 use crate::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp};
24 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
25 use crate::util::logger::{Level, Logger};
26 use crate::util::chacha20::ChaCha20;
29 use crate::prelude::*;
30 use crate::sync::Mutex;
31 use alloc::collections::BinaryHeap;
35 /// A [`Router`] implemented using [`find_route`].
36 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> where
38 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
42 random_seed_bytes: Mutex<[u8; 32]>,
47 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> DefaultRouter<G, L, S, SP, Sc> where
49 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
51 /// Creates a new router.
52 pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32], scorer: S, score_params: SP) -> Self {
53 let random_seed_bytes = Mutex::new(random_seed_bytes);
54 Self { network_graph, logger, random_seed_bytes, scorer, score_params }
58 impl< G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> Router for DefaultRouter<G, L, S, SP, Sc> where
60 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
65 params: &RouteParameters,
66 first_hops: Option<&[&ChannelDetails]>,
67 inflight_htlcs: InFlightHtlcs
68 ) -> Result<Route, LightningError> {
69 let random_seed_bytes = {
70 let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
71 *locked_random_seed_bytes = Sha256::hash(&*locked_random_seed_bytes).into_inner();
72 *locked_random_seed_bytes
75 payer, params, &self.network_graph, first_hops, &*self.logger,
76 &ScorerAccountingForInFlightHtlcs::new(self.scorer.read_lock(), &inflight_htlcs),
83 /// A trait defining behavior for routing a payment.
85 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
87 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
88 /// and [`RouteParameters::final_value_msat`], respectively.
90 &self, payer: &PublicKey, route_params: &RouteParameters,
91 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
92 ) -> Result<Route, LightningError>;
93 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
95 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
96 /// and [`RouteParameters::final_value_msat`], respectively.
98 /// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
100 fn find_route_with_id(
101 &self, payer: &PublicKey, route_params: &RouteParameters,
102 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
103 _payment_hash: PaymentHash, _payment_id: PaymentId
104 ) -> Result<Route, LightningError> {
105 self.find_route(payer, route_params, first_hops, inflight_htlcs)
109 /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
111 /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
114 /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
115 pub struct ScorerAccountingForInFlightHtlcs<'a, SP: Sized, Sc: 'a + ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> {
117 // Maps a channel's short channel id and its direction to the liquidity used up.
118 inflight_htlcs: &'a InFlightHtlcs,
120 impl<'a, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> ScorerAccountingForInFlightHtlcs<'a, SP, Sc, S> {
121 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
122 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
123 ScorerAccountingForInFlightHtlcs {
131 impl<'a, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> Writeable for ScorerAccountingForInFlightHtlcs<'a, SP, Sc, S> {
132 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.scorer.write(writer) }
135 impl<'a, SP: Sized, Sc: 'a + ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, SP, Sc, S> {
136 type ScoreParams = Sc::ScoreParams;
137 fn channel_penalty_msat(&self, short_channel_id: u64, source: &NodeId, target: &NodeId, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
138 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
139 source, target, short_channel_id
141 let usage = ChannelUsage {
142 inflight_htlc_msat: usage.inflight_htlc_msat + used_liquidity,
146 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
148 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
153 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
154 /// in-use channel liquidity.
156 pub struct InFlightHtlcs(
157 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
158 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
159 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
161 HashMap<(u64, bool), u64>
165 /// Constructs an empty `InFlightHtlcs`.
166 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
168 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
169 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
170 if path.hops.is_empty() { return };
172 let mut cumulative_msat = 0;
173 if let Some(tail) = &path.blinded_tail {
174 cumulative_msat += tail.final_value_msat;
177 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
178 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
179 // the router excludes the payer node. In the following lines, the payer's information is
180 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
181 // in our sliding window of two.
182 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
183 .map(|hop| hop.pubkey)
184 .chain(core::iter::once(payer_node_id));
186 // Taking the reversed vector from above, we zip it with just the reversed hops list to
187 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
188 // the total amount sent.
189 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
190 cumulative_msat += next_hop.fee_msat;
192 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
193 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
194 .or_insert(cumulative_msat);
198 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
200 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
202 .entry((channel_scid, source < target))
203 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
204 .or_insert(used_msat);
207 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
209 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
210 self.0.get(&(channel_scid, source < target)).map(|v| *v)
214 impl Writeable for InFlightHtlcs {
215 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
218 impl Readable for InFlightHtlcs {
219 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
220 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
221 Ok(Self(infight_map))
225 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
226 /// that leads to it.
227 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
228 pub struct RouteHop {
229 /// The node_id of the node at this hop.
230 pub pubkey: PublicKey,
231 /// The node_announcement features of the node at this hop. For the last hop, these may be
232 /// amended to match the features present in the invoice this node generated.
233 pub node_features: NodeFeatures,
234 /// The channel that should be used from the previous hop to reach this node.
235 pub short_channel_id: u64,
236 /// The channel_announcement features of the channel that should be used from the previous hop
237 /// to reach this node.
238 pub channel_features: ChannelFeatures,
239 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
240 /// If this is the last hop in [`Path::hops`]:
241 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
242 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
244 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
246 /// The CLTV delta added for this hop.
247 /// If this is the last hop in [`Path::hops`]:
248 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
249 /// * otherwise, this is the CLTV delta expected at the destination
251 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
252 pub cltv_expiry_delta: u32,
255 impl_writeable_tlv_based!(RouteHop, {
256 (0, pubkey, required),
257 (2, node_features, required),
258 (4, short_channel_id, required),
259 (6, channel_features, required),
260 (8, fee_msat, required),
261 (10, cltv_expiry_delta, required),
264 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
265 /// their [`Bolt12Invoice`].
267 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
268 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
269 pub struct BlindedTail {
270 /// The hops of the [`BlindedPath`] provided by the recipient.
272 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
273 pub hops: Vec<BlindedHop>,
274 /// The blinding point of the [`BlindedPath`] provided by the recipient.
276 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
277 pub blinding_point: PublicKey,
278 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
279 /// inferring the destination. May be 0.
280 pub excess_final_cltv_expiry_delta: u32,
281 /// The total amount paid on this [`Path`], excluding the fees.
282 pub final_value_msat: u64,
285 impl_writeable_tlv_based!(BlindedTail, {
286 (0, hops, required_vec),
287 (2, blinding_point, required),
288 (4, excess_final_cltv_expiry_delta, required),
289 (6, final_value_msat, required),
292 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
293 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
294 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
296 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
297 pub hops: Vec<RouteHop>,
298 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
299 pub blinded_tail: Option<BlindedTail>,
303 /// Gets the fees for a given path, excluding any excess paid to the recipient.
304 pub fn fee_msat(&self) -> u64 {
305 match &self.blinded_tail {
306 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
308 // Do not count last hop of each path since that's the full value of the payment
309 self.hops.split_last().map_or(0,
310 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
315 /// Gets the total amount paid on this [`Path`], excluding the fees.
316 pub fn final_value_msat(&self) -> u64 {
317 match &self.blinded_tail {
318 Some(blinded_tail) => blinded_tail.final_value_msat,
319 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
323 /// Gets the final hop's CLTV expiry delta.
324 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
325 match &self.blinded_tail {
327 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
332 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
333 /// it can take multiple paths. Each path is composed of one or more hops through the network.
334 #[derive(Clone, Hash, PartialEq, Eq)]
336 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
337 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
339 pub paths: Vec<Path>,
340 /// The `payment_params` parameter passed via [`RouteParameters`] to [`find_route`].
342 /// This is used by `ChannelManager` to track information which may be required for retries.
343 pub payment_params: Option<PaymentParameters>,
347 /// Returns the total amount of fees paid on this [`Route`].
349 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
350 /// the amount passed to [`find_route`]'s `route_params.final_value_msat`.
351 pub fn get_total_fees(&self) -> u64 {
352 self.paths.iter().map(|path| path.fee_msat()).sum()
355 /// Returns the total amount paid on this [`Route`], excluding the fees. Might be more than
356 /// requested if we had to reach htlc_minimum_msat.
357 pub fn get_total_amount(&self) -> u64 {
358 self.paths.iter().map(|path| path.final_value_msat()).sum()
362 const SERIALIZATION_VERSION: u8 = 1;
363 const MIN_SERIALIZATION_VERSION: u8 = 1;
365 impl Writeable for Route {
366 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
367 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
368 (self.paths.len() as u64).write(writer)?;
369 let mut blinded_tails = Vec::new();
370 for path in self.paths.iter() {
371 (path.hops.len() as u8).write(writer)?;
372 for (idx, hop) in path.hops.iter().enumerate() {
374 if let Some(blinded_tail) = &path.blinded_tail {
375 if blinded_tails.is_empty() {
376 blinded_tails = Vec::with_capacity(path.hops.len());
378 blinded_tails.push(None);
381 blinded_tails.push(Some(blinded_tail));
382 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
385 write_tlv_fields!(writer, {
386 (1, self.payment_params, option),
387 (2, blinded_tails, optional_vec),
393 impl Readable for Route {
394 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
395 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
396 let path_count: u64 = Readable::read(reader)?;
397 if path_count == 0 { return Err(DecodeError::InvalidValue); }
398 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
399 let mut min_final_cltv_expiry_delta = u32::max_value();
400 for _ in 0..path_count {
401 let hop_count: u8 = Readable::read(reader)?;
402 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
403 for _ in 0..hop_count {
404 hops.push(Readable::read(reader)?);
406 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
407 min_final_cltv_expiry_delta =
408 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
409 paths.push(Path { hops, blinded_tail: None });
411 _init_and_read_len_prefixed_tlv_fields!(reader, {
412 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
413 (2, blinded_tails, optional_vec),
415 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
416 if blinded_tails.len() != 0 {
417 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
418 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
419 path.blinded_tail = blinded_tail_opt;
422 Ok(Route { paths, payment_params })
426 /// Parameters needed to find a [`Route`].
428 /// Passed to [`find_route`] and [`build_route_from_hops`].
429 #[derive(Clone, Debug, PartialEq, Eq)]
430 pub struct RouteParameters {
431 /// The parameters of the failed payment path.
432 pub payment_params: PaymentParameters,
434 /// The amount in msats sent on the failed payment path.
435 pub final_value_msat: u64,
438 impl Writeable for RouteParameters {
439 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
440 write_tlv_fields!(writer, {
441 (0, self.payment_params, required),
442 (2, self.final_value_msat, required),
443 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
444 // `RouteParameters` directly. For compatibility, we write it here.
445 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
451 impl Readable for RouteParameters {
452 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
453 _init_and_read_len_prefixed_tlv_fields!(reader, {
454 (0, payment_params, (required: ReadableArgs, 0)),
455 (2, final_value_msat, required),
456 (4, final_cltv_delta, option),
458 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
459 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
460 if final_cltv_expiry_delta == &0 {
461 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
466 final_value_msat: final_value_msat.0.unwrap(),
471 /// Maximum total CTLV difference we allow for a full payment path.
472 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
474 /// Maximum number of paths we allow an (MPP) payment to have.
475 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
476 // limits, but for now more than 10 paths likely carries too much one-path failure.
477 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
479 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
481 // The median hop CLTV expiry delta currently seen in the network.
482 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
484 // During routing, we only consider paths shorter than our maximum length estimate.
485 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
486 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
487 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
489 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
490 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
491 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
492 // (payment_secret and total_msat) = 93 bytes for the final hop.
493 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
494 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
495 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
497 /// Information used to route a payment.
498 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
499 pub struct PaymentParameters {
500 /// Information about the payee, such as their features and route hints for their channels.
503 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
504 pub expiry_time: Option<u64>,
506 /// The maximum total CLTV delta we accept for the route.
507 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
508 pub max_total_cltv_expiry_delta: u32,
510 /// The maximum number of paths that may be used by (MPP) payments.
511 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
512 pub max_path_count: u8,
514 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
515 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
516 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
517 /// increasing failure probability for those paths.
519 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
520 /// restriction have been found. While paths which meet this criteria will be searched for, it
521 /// is ultimately up to the scorer to select them over other paths.
523 /// A value of 0 will allow payments up to and including a channel's total announced usable
524 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
527 pub max_channel_saturation_power_of_half: u8,
529 /// A list of SCIDs which this payment was previously attempted over and which caused the
530 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
532 pub previously_failed_channels: Vec<u64>,
535 impl Writeable for PaymentParameters {
536 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
537 let mut clear_hints = &vec![];
538 let mut blinded_hints = &vec![];
540 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
541 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
543 write_tlv_fields!(writer, {
544 (0, self.payee.node_id(), option),
545 (1, self.max_total_cltv_expiry_delta, required),
546 (2, self.payee.features(), option),
547 (3, self.max_path_count, required),
548 (4, *clear_hints, required_vec),
549 (5, self.max_channel_saturation_power_of_half, required),
550 (6, self.expiry_time, option),
551 (7, self.previously_failed_channels, required_vec),
552 (8, *blinded_hints, optional_vec),
553 (9, self.payee.final_cltv_expiry_delta(), option),
559 impl ReadableArgs<u32> for PaymentParameters {
560 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
561 _init_and_read_len_prefixed_tlv_fields!(reader, {
562 (0, payee_pubkey, option),
563 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
564 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
565 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
566 (4, clear_route_hints, required_vec),
567 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
568 (6, expiry_time, option),
569 (7, previously_failed_channels, optional_vec),
570 (8, blinded_route_hints, optional_vec),
571 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
573 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
574 let payee = if blinded_route_hints.len() != 0 {
575 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
577 route_hints: blinded_route_hints,
578 features: features.and_then(|f: Features| f.bolt12()),
582 route_hints: clear_route_hints,
583 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
584 features: features.and_then(|f| f.bolt11()),
585 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
589 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
590 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
592 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
594 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
600 impl PaymentParameters {
601 /// Creates a payee with the node id of the given `pubkey`.
603 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
605 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
607 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
609 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
610 max_path_count: DEFAULT_MAX_PATH_COUNT,
611 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
612 previously_failed_channels: Vec::new(),
616 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
618 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
621 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
622 /// whether your router will be allowed to find a multi-part route for this payment. If you
623 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
624 /// [`RecipientOnionFields::secret_only`].
626 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
627 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
628 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
629 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
630 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
633 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
634 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
635 /// [`PaymentParameters::expiry_time`].
636 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
637 Self::blinded(invoice.payment_paths().to_vec())
638 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
639 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
642 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
643 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
645 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
647 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
648 max_path_count: DEFAULT_MAX_PATH_COUNT,
649 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
650 previously_failed_channels: Vec::new(),
654 /// Includes the payee's features. Errors if the parameters were not initialized with
655 /// [`PaymentParameters::from_bolt12_invoice`].
657 /// This is not exported to bindings users since bindings don't support move semantics
658 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
660 Payee::Clear { .. } => Err(()),
661 Payee::Blinded { route_hints, .. } =>
662 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
666 /// Includes the payee's features. Errors if the parameters were initialized with
667 /// [`PaymentParameters::from_bolt12_invoice`].
669 /// This is not exported to bindings users since bindings don't support move semantics
670 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
672 Payee::Blinded { .. } => Err(()),
673 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
675 payee: Payee::Clear {
676 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
682 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
683 /// [`PaymentParameters::from_bolt12_invoice`].
685 /// This is not exported to bindings users since bindings don't support move semantics
686 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
688 Payee::Blinded { .. } => Err(()),
689 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
691 payee: Payee::Clear {
692 route_hints, node_id, features, final_cltv_expiry_delta,
698 /// Includes a payment expiration in seconds relative to the UNIX epoch.
700 /// This is not exported to bindings users since bindings don't support move semantics
701 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
702 Self { expiry_time: Some(expiry_time), ..self }
705 /// Includes a limit for the total CLTV expiry delta which is considered during routing
707 /// This is not exported to bindings users since bindings don't support move semantics
708 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
709 Self { max_total_cltv_expiry_delta, ..self }
712 /// Includes a limit for the maximum number of payment paths that may be used.
714 /// This is not exported to bindings users since bindings don't support move semantics
715 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
716 Self { max_path_count, ..self }
719 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
720 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
722 /// This is not exported to bindings users since bindings don't support move semantics
723 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
724 Self { max_channel_saturation_power_of_half, ..self }
728 /// The recipient of a payment, differing based on whether they've hidden their identity with route
730 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
732 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
733 /// will be included in the final [`Route`].
735 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
737 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
738 /// Features supported by the payee.
740 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
742 features: Option<Bolt12InvoiceFeatures>,
744 /// The recipient included these route hints in their BOLT11 invoice.
746 /// The node id of the payee.
748 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
749 route_hints: Vec<RouteHint>,
750 /// Features supported by the payee.
752 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
753 /// does not contain any features.
755 /// [`for_keysend`]: PaymentParameters::for_keysend
756 features: Option<Bolt11InvoiceFeatures>,
757 /// The minimum CLTV delta at the end of the route. This value must not be zero.
758 final_cltv_expiry_delta: u32,
763 fn node_id(&self) -> Option<PublicKey> {
765 Self::Clear { node_id, .. } => Some(*node_id),
769 fn node_features(&self) -> Option<NodeFeatures> {
771 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
772 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
775 fn supports_basic_mpp(&self) -> bool {
777 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
778 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
781 fn features(&self) -> Option<FeaturesRef> {
783 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
784 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
787 fn final_cltv_expiry_delta(&self) -> Option<u32> {
789 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
793 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
795 Self::Blinded { route_hints, .. } => &route_hints[..],
796 Self::Clear { .. } => &[]
800 fn unblinded_route_hints(&self) -> &[RouteHint] {
802 Self::Blinded { .. } => &[],
803 Self::Clear { route_hints, .. } => &route_hints[..]
808 enum FeaturesRef<'a> {
809 Bolt11(&'a Bolt11InvoiceFeatures),
810 Bolt12(&'a Bolt12InvoiceFeatures),
813 Bolt11(Bolt11InvoiceFeatures),
814 Bolt12(Bolt12InvoiceFeatures),
818 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
820 Self::Bolt12(f) => Some(f),
824 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
826 Self::Bolt11(f) => Some(f),
832 impl<'a> Writeable for FeaturesRef<'a> {
833 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
835 Self::Bolt11(f) => Ok(f.write(w)?),
836 Self::Bolt12(f) => Ok(f.write(w)?),
841 impl ReadableArgs<bool> for Features {
842 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
843 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
844 Ok(Self::Bolt12(Readable::read(reader)?))
848 /// A list of hops along a payment path terminating with a channel to the recipient.
849 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
850 pub struct RouteHint(pub Vec<RouteHintHop>);
852 impl Writeable for RouteHint {
853 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
854 (self.0.len() as u64).write(writer)?;
855 for hop in self.0.iter() {
862 impl Readable for RouteHint {
863 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
864 let hop_count: u64 = Readable::read(reader)?;
865 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
866 for _ in 0..hop_count {
867 hops.push(Readable::read(reader)?);
873 /// A channel descriptor for a hop along a payment path.
874 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
875 pub struct RouteHintHop {
876 /// The node_id of the non-target end of the route
877 pub src_node_id: PublicKey,
878 /// The short_channel_id of this channel
879 pub short_channel_id: u64,
880 /// The fees which must be paid to use this channel
881 pub fees: RoutingFees,
882 /// The difference in CLTV values between this node and the next node.
883 pub cltv_expiry_delta: u16,
884 /// The minimum value, in msat, which must be relayed to the next hop.
885 pub htlc_minimum_msat: Option<u64>,
886 /// The maximum value in msat available for routing with a single HTLC.
887 pub htlc_maximum_msat: Option<u64>,
890 impl_writeable_tlv_based!(RouteHintHop, {
891 (0, src_node_id, required),
892 (1, htlc_minimum_msat, option),
893 (2, short_channel_id, required),
894 (3, htlc_maximum_msat, option),
896 (6, cltv_expiry_delta, required),
899 #[derive(Eq, PartialEq)]
900 struct RouteGraphNode {
902 lowest_fee_to_node: u64,
903 total_cltv_delta: u32,
904 // The maximum value a yet-to-be-constructed payment path might flow through this node.
905 // This value is upper-bounded by us by:
906 // - how much is needed for a path being constructed
907 // - how much value can channels following this node (up to the destination) can contribute,
908 // considering their capacity and fees
909 value_contribution_msat: u64,
910 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
911 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
912 path_htlc_minimum_msat: u64,
913 /// All penalties incurred from this hop on the way to the destination, as calculated using
915 path_penalty_msat: u64,
916 /// The number of hops walked up to this node.
917 path_length_to_node: u8,
920 impl cmp::Ord for RouteGraphNode {
921 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
922 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
923 .saturating_add(other.path_penalty_msat);
924 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
925 .saturating_add(self.path_penalty_msat);
926 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
930 impl cmp::PartialOrd for RouteGraphNode {
931 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
932 Some(self.cmp(other))
936 /// A wrapper around the various hop representations.
938 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
939 #[derive(Clone, Debug)]
940 enum CandidateRouteHop<'a> {
941 /// A hop from the payer, where the outbound liquidity is known.
943 details: &'a ChannelDetails,
945 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
947 info: DirectedChannelInfo<'a>,
948 short_channel_id: u64,
950 /// A hop to the payee found in the BOLT 11 payment invoice, though not necessarily a direct
953 hint: &'a RouteHintHop,
955 /// The payee's identity is concealed behind blinded paths provided in a BOLT 12 invoice.
957 hint: &'a (BlindedPayInfo, BlindedPath),
960 /// Similar to [`Self::Blinded`], but the path here has 1 blinded hop. `BlindedPayInfo` provided
961 /// for 1-hop blinded paths is ignored because it is meant to apply to the hops *between* the
962 /// introduction node and the destination. Useful for tracking that we need to include a blinded
963 /// path at the end of our [`Route`].
965 hint: &'a (BlindedPayInfo, BlindedPath),
970 impl<'a> CandidateRouteHop<'a> {
971 fn short_channel_id(&self) -> Option<u64> {
973 CandidateRouteHop::FirstHop { details } => Some(details.get_outbound_payment_scid().unwrap()),
974 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
975 CandidateRouteHop::PrivateHop { hint } => Some(hint.short_channel_id),
976 CandidateRouteHop::Blinded { .. } => None,
977 CandidateRouteHop::OneHopBlinded { .. } => None,
981 // NOTE: This may alloc memory so avoid calling it in a hot code path.
982 fn features(&self) -> ChannelFeatures {
984 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
985 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
986 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
987 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
988 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
992 fn cltv_expiry_delta(&self) -> u32 {
994 CandidateRouteHop::FirstHop { .. } => 0,
995 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
996 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
997 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
998 CandidateRouteHop::OneHopBlinded { .. } => 0,
1002 fn htlc_minimum_msat(&self) -> u64 {
1004 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_minimum_msat,
1005 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1006 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
1007 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1008 CandidateRouteHop::OneHopBlinded { .. } => 0,
1012 fn fees(&self) -> RoutingFees {
1014 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1015 base_msat: 0, proportional_millionths: 0,
1017 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1018 CandidateRouteHop::PrivateHop { hint } => hint.fees,
1019 CandidateRouteHop::Blinded { hint, .. } => {
1021 base_msat: hint.0.fee_base_msat,
1022 proportional_millionths: hint.0.fee_proportional_millionths
1025 CandidateRouteHop::OneHopBlinded { .. } =>
1026 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1030 fn effective_capacity(&self) -> EffectiveCapacity {
1032 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
1033 liquidity_msat: details.next_outbound_htlc_limit_msat,
1035 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1036 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }} =>
1037 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1038 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }} =>
1039 EffectiveCapacity::Infinite,
1040 CandidateRouteHop::Blinded { hint, .. } =>
1041 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1042 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1046 fn id(&self, channel_direction: bool /* src_node_id < target_node_id */) -> CandidateHopId {
1048 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1049 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1050 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), channel_direction)),
1053 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1055 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1063 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1064 enum CandidateHopId {
1065 /// Contains (scid, src_node_id < target_node_id)
1067 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1072 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1073 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1075 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1076 EffectiveCapacity::Infinite => u64::max_value(),
1077 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1078 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1079 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1080 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1081 // expected to have been generated from up-to-date capacity information.
1082 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1083 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1084 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1088 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1089 -> bool where I1::Item: PartialEq<I2::Item> {
1091 let a = iter_a.next();
1092 let b = iter_b.next();
1093 if a.is_none() && b.is_none() { return true; }
1094 if a.is_none() || b.is_none() { return false; }
1095 if a.unwrap().ne(&b.unwrap()) { return false; }
1099 /// It's useful to keep track of the hops associated with the fees required to use them,
1100 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1101 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1102 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1104 struct PathBuildingHop<'a> {
1105 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
1106 // is a larger refactor and will require careful performance analysis.
1108 candidate: CandidateRouteHop<'a>,
1111 /// All the fees paid *after* this channel on the way to the destination
1112 next_hops_fee_msat: u64,
1113 /// Fee paid for the use of the current channel (see candidate.fees()).
1114 /// The value will be actually deducted from the counterparty balance on the previous link.
1115 hop_use_fee_msat: u64,
1116 /// Used to compare channels when choosing the for routing.
1117 /// Includes paying for the use of a hop and the following hops, as well as
1118 /// an estimated cost of reaching this hop.
1119 /// Might get stale when fees are recomputed. Primarily for internal use.
1120 total_fee_msat: u64,
1121 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1122 /// walk and may be invalid thereafter.
1123 path_htlc_minimum_msat: u64,
1124 /// All penalties incurred from this channel on the way to the destination, as calculated using
1125 /// channel scoring.
1126 path_penalty_msat: u64,
1127 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1128 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1129 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1130 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1131 /// avoid processing them again.
1132 was_processed: bool,
1133 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1134 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1135 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1136 // value_contribution_msat, which requires tracking it here. See comments below where it is
1137 // used for more info.
1138 value_contribution_msat: u64,
1141 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1142 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1143 let mut debug_struct = f.debug_struct("PathBuildingHop");
1145 .field("node_id", &self.node_id)
1146 .field("short_channel_id", &self.candidate.short_channel_id())
1147 .field("total_fee_msat", &self.total_fee_msat)
1148 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1149 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1150 .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)))
1151 .field("path_penalty_msat", &self.path_penalty_msat)
1152 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1153 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1154 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1155 let debug_struct = debug_struct
1156 .field("value_contribution_msat", &self.value_contribution_msat);
1157 debug_struct.finish()
1161 // Instantiated with a list of hops with correct data in them collected during path finding,
1162 // an instance of this struct should be further modified only via given methods.
1164 struct PaymentPath<'a> {
1165 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1168 impl<'a> PaymentPath<'a> {
1169 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1170 fn get_value_msat(&self) -> u64 {
1171 self.hops.last().unwrap().0.fee_msat
1174 fn get_path_penalty_msat(&self) -> u64 {
1175 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1178 fn get_total_fee_paid_msat(&self) -> u64 {
1179 if self.hops.len() < 1 {
1183 // Can't use next_hops_fee_msat because it gets outdated.
1184 for (i, (hop, _)) in self.hops.iter().enumerate() {
1185 if i != self.hops.len() - 1 {
1186 result += hop.fee_msat;
1192 fn get_cost_msat(&self) -> u64 {
1193 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1196 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1197 // to change fees may result in an inconsistency.
1199 // Sometimes we call this function right after constructing a path which is inconsistent in
1200 // that it the value being transferred has decreased while we were doing path finding, leading
1201 // to the fees being paid not lining up with the actual limits.
1203 // Note that this function is not aware of the available_liquidity limit, and thus does not
1204 // support increasing the value being transferred beyond what was selected during the initial
1206 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
1207 let mut total_fee_paid_msat = 0 as u64;
1208 for i in (0..self.hops.len()).rev() {
1209 let last_hop = i == self.hops.len() - 1;
1211 // For non-last-hop, this value will represent the fees paid on the current hop. It
1212 // will consist of the fees for the use of the next hop, and extra fees to match
1213 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1214 let mut cur_hop_fees_msat = 0;
1216 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1219 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1220 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1221 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1222 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1223 // set it too high just to maliciously take more fees by exploiting this
1224 // match htlc_minimum_msat logic.
1225 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1226 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1227 // Note that there is a risk that *previous hops* (those closer to us, as we go
1228 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1230 // This might make us end up with a broken route, although this should be super-rare
1231 // in practice, both because of how healthy channels look like, and how we pick
1232 // channels in add_entry.
1233 // Also, this can't be exploited more heavily than *announce a free path and fail
1235 cur_hop_transferred_amount_msat += extra_fees_msat;
1236 total_fee_paid_msat += extra_fees_msat;
1237 cur_hop_fees_msat += extra_fees_msat;
1241 // Final hop is a special case: it usually has just value_msat (by design), but also
1242 // it still could overpay for the htlc_minimum_msat.
1243 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1245 // Propagate updated fees for the use of the channels to one hop back, where they
1246 // will be actually paid (fee_msat). The last hop is handled above separately.
1247 cur_hop.fee_msat = cur_hop_fees_msat;
1250 // Fee for the use of the current hop which will be deducted on the previous hop.
1251 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1252 // this channel is free for us.
1254 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1255 cur_hop.hop_use_fee_msat = new_fee;
1256 total_fee_paid_msat += new_fee;
1258 // It should not be possible because this function is called only to reduce the
1259 // value. In that case, compute_fee was already called with the same fees for
1260 // larger amount and there was no overflow.
1269 /// Calculate the fees required to route the given amount over a channel with the given fees.
1270 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1271 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1272 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1276 /// Calculate the fees required to route the given amount over a channel with the given fees,
1277 /// saturating to [`u64::max_value`].
1278 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1279 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1280 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1281 .saturating_add(channel_fees.base_msat as u64)
1284 /// The default `features` we assume for a node in a route, when no `features` are known about that
1287 /// Default features are:
1288 /// * variable_length_onion_optional
1289 fn default_node_features() -> NodeFeatures {
1290 let mut features = NodeFeatures::empty();
1291 features.set_variable_length_onion_optional();
1295 struct LoggedPayeePubkey(Option<PublicKey>);
1296 impl fmt::Display for LoggedPayeePubkey {
1297 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1300 "payee node id ".fmt(f)?;
1304 "blinded payee".fmt(f)
1310 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1311 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1312 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1314 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1315 "blinded route hint with introduction node id ".fmt(f)?;
1316 hint.1.introduction_node_id.fmt(f)?;
1317 " and blinding point ".fmt(f)?;
1318 hint.1.blinding_point.fmt(f)
1320 CandidateRouteHop::FirstHop { .. } => {
1321 "first hop with SCID ".fmt(f)?;
1322 self.0.short_channel_id().unwrap().fmt(f)
1324 CandidateRouteHop::PrivateHop { .. } => {
1325 "route hint with SCID ".fmt(f)?;
1326 self.0.short_channel_id().unwrap().fmt(f)
1330 self.0.short_channel_id().unwrap().fmt(f)
1337 fn sort_first_hop_channels(
1338 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1339 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1341 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1342 // most like to use.
1344 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1345 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1348 // Second, because simply always sorting in descending order would always use our largest
1349 // available outbound capacity, needlessly fragmenting our available channel capacities,
1350 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1351 // which have enough, but not too much, capacity for the payment.
1353 // Available outbound balances factor in liquidity already reserved for previously found paths.
1354 channels.sort_unstable_by(|chan_a, chan_b| {
1355 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1356 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1357 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1358 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1359 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1360 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1361 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1362 // Sort in descending order
1363 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1365 // Sort in ascending order
1366 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1371 /// Finds a route from us (payer) to the given target node (payee).
1373 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1374 /// in the given [`RouteParameters::payment_params`].
1375 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1377 /// Private routing paths between a public node and the target may be included in the `payee` field
1378 /// of [`RouteParameters::payment_params`].
1380 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1381 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1382 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1384 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1385 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1386 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1390 /// Panics if first_hops contains channels without `short_channel_id`s;
1391 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1393 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1394 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1395 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1396 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1397 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1398 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1399 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1400 ) -> Result<Route, LightningError>
1401 where L::Target: Logger, GL::Target: Logger {
1402 let graph_lock = network_graph.read_only();
1403 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
1404 route_params.final_value_msat, logger, scorer, score_params,
1405 random_seed_bytes)?;
1406 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1410 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1411 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
1412 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, logger: L, scorer: &S, score_params: &S::ScoreParams,
1413 _random_seed_bytes: &[u8; 32]
1414 ) -> Result<Route, LightningError>
1415 where L::Target: Logger {
1416 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1417 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1418 // so use a dummy id for this in the blinded case.
1419 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1420 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1421 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1422 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1423 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1425 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1426 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1429 if final_value_msat > MAX_VALUE_MSAT {
1430 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1433 if final_value_msat == 0 {
1434 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1437 match &payment_params.payee {
1438 Payee::Clear { route_hints, node_id, .. } => {
1439 for route in route_hints.iter() {
1440 for hop in &route.0 {
1441 if hop.src_node_id == *node_id {
1442 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1447 Payee::Blinded { route_hints, .. } => {
1448 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1449 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});
1451 for (_, blinded_path) in route_hints.iter() {
1452 if blinded_path.blinded_hops.len() == 0 {
1453 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1454 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1455 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1456 } else if blinded_path.blinded_hops.len() == 1 &&
1457 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1458 && p.introduction_node_id != blinded_path.introduction_node_id)
1460 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1465 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1466 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1467 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});
1470 // The general routing idea is the following:
1471 // 1. Fill first/last hops communicated by the caller.
1472 // 2. Attempt to construct a path from payer to payee for transferring
1473 // any ~sufficient (described later) value.
1474 // If succeed, remember which channels were used and how much liquidity they have available,
1475 // so that future paths don't rely on the same liquidity.
1476 // 3. Proceed to the next step if:
1477 // - we hit the recommended target value;
1478 // - OR if we could not construct a new path. Any next attempt will fail too.
1479 // Otherwise, repeat step 2.
1480 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1481 // (not recommended value).
1482 // 5. If yes, proceed. If not, fail routing.
1483 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1484 // transferred up to the transfer target value.
1485 // 7. Reduce the value of the last path until we are sending only the target value.
1486 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1487 // them so that we're not sending two HTLCs along the same path.
1489 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1490 // distance from the payee
1492 // We are not a faithful Dijkstra's implementation because we can change values which impact
1493 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1494 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1495 // the value we are currently attempting to send over a path, we simply reduce the value being
1496 // sent along the path for any hops after that channel. This may imply that later fees (which
1497 // we've already tabulated) are lower because a smaller value is passing through the channels
1498 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1499 // channels which were selected earlier (and which may still be used for other paths without a
1500 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1503 // One potentially problematic case for this algorithm would be if there are many
1504 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1505 // graph walking), we may never find a path which is not liquidity-limited and has lower
1506 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1507 // Because we only consider paths with at least 5% of the total value being sent, the damage
1508 // from such a case should be limited, however this could be further reduced in the future by
1509 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1510 // limits for the purposes of fee calculation.
1512 // Alternatively, we could store more detailed path information in the heap (targets, below)
1513 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1514 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1515 // and practically (as we would need to store dynamically-allocated path information in heap
1516 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1517 // results of such an algorithm would likely be biased towards lower-value paths.
1519 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1520 // outside of our current search value, running a path search more times to gather candidate
1521 // paths at different values. While this may be acceptable, further path searches may increase
1522 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1523 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1524 // the same time, remaining generic across different payment values.
1526 let network_channels = network_graph.channels();
1527 let network_nodes = network_graph.nodes();
1529 if payment_params.max_path_count == 0 {
1530 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1533 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1534 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1536 let allow_mpp = if payment_params.max_path_count == 1 {
1538 } else if payment_params.payee.supports_basic_mpp() {
1540 } else if let Some(payee) = payee_node_id_opt {
1541 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1542 |info| info.features.supports_basic_mpp()))
1545 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1546 LoggedPayeePubkey(payment_params.payee.node_id()), if allow_mpp { "with" } else { "without" },
1547 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1550 // Prepare the data we'll use for payee-to-payer search by
1551 // inserting first hops suggested by the caller as targets.
1552 // Our search will then attempt to reach them while traversing from the payee node.
1553 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1554 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1555 if let Some(hops) = first_hops {
1557 if chan.get_outbound_payment_scid().is_none() {
1558 panic!("first_hops should be filled in with usable channels, not pending ones");
1560 if chan.counterparty.node_id == *our_node_pubkey {
1561 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1564 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1565 .or_insert(Vec::new())
1568 if first_hop_targets.is_empty() {
1569 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1573 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1574 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1575 // adding duplicate entries when we find a better path to a given node.
1576 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1578 // Map from node_id to information about the best current path to that node, including feerate
1580 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1582 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1583 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1584 // htlc_minimum with extra fees while still finding a cheaper path.
1585 let mut hit_minimum_limit;
1587 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1588 // We start with a path_value of the exact amount we want, and if that generates a route we may
1589 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1590 // amount we want in total across paths, selecting the best subset at the end.
1591 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1592 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1593 let mut path_value_msat = final_value_msat;
1595 // Routing Fragmentation Mitigation heuristic:
1597 // Routing fragmentation across many payment paths increases the overall routing
1598 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1599 // Taking too many smaller paths also increases the chance of payment failure.
1600 // Thus to avoid this effect, we require from our collected links to provide
1601 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1602 // This requirement is currently set to be 1/max_path_count of the payment
1603 // value to ensure we only ever return routes that do not violate this limit.
1604 let minimal_value_contribution_msat: u64 = if allow_mpp {
1605 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1610 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1611 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1612 // drop the requirement by setting this to 0.
1613 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1615 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1616 // determine if the channel can be used by additional MPP paths or to inform path finding
1617 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1618 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1620 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1621 HashMap::with_capacity(network_nodes.len());
1623 // Keeping track of how much value we already collected across other paths. Helps to decide
1624 // when we want to stop looking for new paths.
1625 let mut already_collected_value_msat = 0;
1627 for (_, channels) in first_hop_targets.iter_mut() {
1628 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1632 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1633 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1635 // Remember how many candidates we ignored to allow for some logging afterwards.
1636 let mut num_ignored_value_contribution = 0;
1637 let mut num_ignored_path_length_limit = 0;
1638 let mut num_ignored_cltv_delta_limit = 0;
1639 let mut num_ignored_previously_failed = 0;
1641 macro_rules! add_entry {
1642 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1643 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1644 // since that value has to be transferred over this channel.
1645 // Returns whether this channel caused an update to `targets`.
1646 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1647 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1648 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1649 // We "return" whether we updated the path at the end, and how much we can route via
1650 // this channel, via this:
1651 let mut did_add_update_path_to_src_node = None;
1652 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1653 // practice these cases should be caught earlier:
1654 // - for regular channels at channel announcement (TODO)
1655 // - for first and last hops early in get_route
1656 if $src_node_id != $dest_node_id {
1657 let scid_opt = $candidate.short_channel_id();
1658 let effective_capacity = $candidate.effective_capacity();
1659 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1661 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1662 // It may be misleading because we might later choose to reduce the value transferred
1663 // over these channels, and the channel which was insufficient might become sufficient.
1664 // Worst case: we drop a good channel here because it can't cover the high following
1665 // fees caused by one expensive channel, but then this channel could have been used
1666 // if the amount being transferred over this path is lower.
1667 // We do this for now, but this is a subject for removal.
1668 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1669 let used_liquidity_msat = used_liquidities
1670 .get(&$candidate.id($src_node_id < $dest_node_id))
1671 .map_or(0, |used_liquidity_msat| {
1672 available_value_contribution_msat = available_value_contribution_msat
1673 .saturating_sub(*used_liquidity_msat);
1674 *used_liquidity_msat
1677 // Verify the liquidity offered by this channel complies to the minimal contribution.
1678 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1679 // Do not consider candidate hops that would exceed the maximum path length.
1680 let path_length_to_node = $next_hops_path_length + 1;
1681 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1683 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1684 // In order to already account for some of the privacy enhancing random CLTV
1685 // expiry delta offset we add on top later, we subtract a rough estimate
1686 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1687 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1688 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1689 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1690 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1691 .saturating_add($candidate.cltv_expiry_delta());
1692 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1694 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1695 // Includes paying fees for the use of the following channels.
1696 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1697 Some(result) => result,
1698 // Can't overflow due to how the values were computed right above.
1699 None => unreachable!(),
1701 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1702 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1703 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1705 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1706 let may_overpay_to_meet_path_minimum_msat =
1707 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1708 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1709 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1710 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1712 let payment_failed_on_this_channel = scid_opt.map_or(false,
1713 |scid| payment_params.previously_failed_channels.contains(&scid));
1715 let should_log_candidate = match $candidate {
1716 CandidateRouteHop::FirstHop { .. } => true,
1717 CandidateRouteHop::PrivateHop { .. } => true,
1718 CandidateRouteHop::Blinded { .. } => true,
1722 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1723 // bother considering this channel. If retrying with recommended_value_msat may
1724 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1725 // around again with a higher amount.
1726 if !contributes_sufficient_value {
1727 if should_log_candidate {
1728 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
1730 num_ignored_value_contribution += 1;
1731 } else if exceeds_max_path_length {
1732 if should_log_candidate {
1733 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
1735 num_ignored_path_length_limit += 1;
1736 } else if exceeds_cltv_delta_limit {
1737 if should_log_candidate {
1738 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
1740 num_ignored_cltv_delta_limit += 1;
1741 } else if payment_failed_on_this_channel {
1742 if should_log_candidate {
1743 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
1745 num_ignored_previously_failed += 1;
1746 } else if may_overpay_to_meet_path_minimum_msat {
1747 hit_minimum_limit = true;
1748 } else if over_path_minimum_msat {
1749 // Note that low contribution here (limited by available_liquidity_msat)
1750 // might violate htlc_minimum_msat on the hops which are next along the
1751 // payment path (upstream to the payee). To avoid that, we recompute
1752 // path fees knowing the final path contribution after constructing it.
1753 let path_htlc_minimum_msat = cmp::max(
1754 compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1755 .saturating_add($next_hops_path_htlc_minimum_msat),
1756 $candidate.htlc_minimum_msat());
1757 let hm_entry = dist.entry($src_node_id);
1758 let old_entry = hm_entry.or_insert_with(|| {
1759 // If there was previously no known way to access the source node
1760 // (recall it goes payee-to-payer) of short_channel_id, first add a
1761 // semi-dummy record just to compute the fees to reach the source node.
1762 // This will affect our decision on selecting short_channel_id
1763 // as a way to reach the $dest_node_id.
1765 node_id: $dest_node_id.clone(),
1766 candidate: $candidate.clone(),
1768 next_hops_fee_msat: u64::max_value(),
1769 hop_use_fee_msat: u64::max_value(),
1770 total_fee_msat: u64::max_value(),
1771 path_htlc_minimum_msat,
1772 path_penalty_msat: u64::max_value(),
1773 was_processed: false,
1774 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1775 value_contribution_msat,
1779 #[allow(unused_mut)] // We only use the mut in cfg(test)
1780 let mut should_process = !old_entry.was_processed;
1781 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1783 // In test/fuzzing builds, we do extra checks to make sure the skipping
1784 // of already-seen nodes only happens in cases we expect (see below).
1785 if !should_process { should_process = true; }
1789 let mut hop_use_fee_msat = 0;
1790 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1792 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1793 // will have the same effective-fee
1794 if $src_node_id != our_node_id {
1795 // Note that `u64::max_value` means we'll always fail the
1796 // `old_entry.total_fee_msat > total_fee_msat` check below
1797 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1798 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1801 let channel_usage = ChannelUsage {
1802 amount_msat: amount_to_transfer_over_msat,
1803 inflight_htlc_msat: used_liquidity_msat,
1806 let channel_penalty_msat = scid_opt.map_or(0,
1807 |scid| scorer.channel_penalty_msat(scid, &$src_node_id, &$dest_node_id,
1808 channel_usage, score_params));
1809 let path_penalty_msat = $next_hops_path_penalty_msat
1810 .saturating_add(channel_penalty_msat);
1811 let new_graph_node = RouteGraphNode {
1812 node_id: $src_node_id,
1813 lowest_fee_to_node: total_fee_msat,
1814 total_cltv_delta: hop_total_cltv_delta,
1815 value_contribution_msat,
1816 path_htlc_minimum_msat,
1818 path_length_to_node,
1821 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1822 // if this way is cheaper than the already known
1823 // (considering the cost to "reach" this channel from the route destination,
1824 // the cost of using this channel,
1825 // and the cost of routing to the source node of this channel).
1826 // Also, consider that htlc_minimum_msat_difference, because we might end up
1827 // paying it. Consider the following exploit:
1828 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1829 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1830 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1831 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1833 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1834 // but it may require additional tracking - we don't want to double-count
1835 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1836 // can't use something that may decrease on future hops.
1837 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1838 .saturating_add(old_entry.path_penalty_msat);
1839 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1840 .saturating_add(path_penalty_msat);
1842 if !old_entry.was_processed && new_cost < old_cost {
1843 targets.push(new_graph_node);
1844 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1845 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1846 old_entry.total_fee_msat = total_fee_msat;
1847 old_entry.node_id = $dest_node_id.clone();
1848 old_entry.candidate = $candidate.clone();
1849 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1850 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1851 old_entry.path_penalty_msat = path_penalty_msat;
1852 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1854 old_entry.value_contribution_msat = value_contribution_msat;
1856 did_add_update_path_to_src_node = Some(value_contribution_msat);
1857 } else if old_entry.was_processed && new_cost < old_cost {
1858 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1860 // If we're skipping processing a node which was previously
1861 // processed even though we found another path to it with a
1862 // cheaper fee, check that it was because the second path we
1863 // found (which we are processing now) has a lower value
1864 // contribution due to an HTLC minimum limit.
1866 // e.g. take a graph with two paths from node 1 to node 2, one
1867 // through channel A, and one through channel B. Channel A and
1868 // B are both in the to-process heap, with their scores set by
1869 // a higher htlc_minimum than fee.
1870 // Channel A is processed first, and the channels onwards from
1871 // node 1 are added to the to-process heap. Thereafter, we pop
1872 // Channel B off of the heap, note that it has a much more
1873 // restrictive htlc_maximum_msat, and recalculate the fees for
1874 // all of node 1's channels using the new, reduced, amount.
1876 // This would be bogus - we'd be selecting a higher-fee path
1877 // with a lower htlc_maximum_msat instead of the one we'd
1878 // already decided to use.
1879 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1881 value_contribution_msat + path_penalty_msat <
1882 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1890 did_add_update_path_to_src_node
1894 let default_node_features = default_node_features();
1896 // Find ways (channels with destination) to reach a given node and store them
1897 // in the corresponding data structures (routing graph etc).
1898 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1899 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1900 // This data can later be helpful to optimize routing (pay lower fees).
1901 macro_rules! add_entries_to_cheapest_to_target_node {
1902 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1903 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1904 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1905 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1906 let was_processed = elem.was_processed;
1907 elem.was_processed = true;
1910 // Entries are added to dist in add_entry!() when there is a channel from a node.
1911 // Because there are no channels from payee, it will not have a dist entry at this point.
1912 // If we're processing any other node, it is always be the result of a channel from it.
1913 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
1918 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1919 for details in first_channels {
1920 let candidate = CandidateRouteHop::FirstHop { details };
1921 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1922 $next_hops_value_contribution,
1923 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1924 $next_hops_cltv_delta, $next_hops_path_length);
1928 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1931 &default_node_features
1934 if !features.requires_unknown_bits() {
1935 for chan_id in $node.channels.iter() {
1936 let chan = network_channels.get(chan_id).unwrap();
1937 if !chan.features.requires_unknown_bits() {
1938 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1939 if first_hops.is_none() || *source != our_node_id {
1940 if directed_channel.direction().enabled {
1941 let candidate = CandidateRouteHop::PublicHop {
1942 info: directed_channel,
1943 short_channel_id: *chan_id,
1945 add_entry!(candidate, *source, $node_id,
1946 $fee_to_target_msat,
1947 $next_hops_value_contribution,
1948 $next_hops_path_htlc_minimum_msat,
1949 $next_hops_path_penalty_msat,
1950 $next_hops_cltv_delta, $next_hops_path_length);
1961 let mut payment_paths = Vec::<PaymentPath>::new();
1963 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1964 'paths_collection: loop {
1965 // For every new path, start from scratch, except for used_liquidities, which
1966 // helps to avoid reusing previously selected paths in future iterations.
1969 hit_minimum_limit = false;
1971 // If first hop is a private channel and the only way to reach the payee, this is the only
1972 // place where it could be added.
1973 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
1974 for details in first_channels {
1975 let candidate = CandidateRouteHop::FirstHop { details };
1976 let added = add_entry!(candidate, our_node_id, payee, 0, path_value_msat,
1977 0, 0u64, 0, 0).is_some();
1978 log_trace!(logger, "{} direct route to payee via {}",
1979 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
1983 // Add the payee as a target, so that the payee-to-payer
1984 // search algorithm knows what to start with.
1985 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
1986 // The payee is not in our network graph, so nothing to add here.
1987 // There is still a chance of reaching them via last_hops though,
1988 // so don't yet fail the payment here.
1989 // If not, targets.pop() will not even let us enter the loop in step 2.
1992 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
1997 // If a caller provided us with last hops, add them to routing targets. Since this happens
1998 // earlier than general path finding, they will be somewhat prioritized, although currently
1999 // it matters only if the fees are exactly the same.
2000 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2001 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2002 let have_intro_node_in_graph =
2003 // Only add the hops in this route to our candidate set if either
2004 // we have a direct channel to the first hop or the first hop is
2005 // in the regular network graph.
2006 first_hop_targets.get(&intro_node_id).is_some() ||
2007 network_nodes.get(&intro_node_id).is_some();
2008 if !have_intro_node_in_graph { continue }
2009 let candidate = if hint.1.blinded_hops.len() == 1 {
2010 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
2011 } else { CandidateRouteHop::Blinded { hint, hint_idx } };
2012 let mut path_contribution_msat = path_value_msat;
2013 if let Some(hop_used_msat) = add_entry!(candidate, intro_node_id, maybe_dummy_payee_node_id,
2014 0, path_contribution_msat, 0, 0_u64, 0, 0)
2016 path_contribution_msat = hop_used_msat;
2018 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2019 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2021 for details in first_channels {
2022 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2023 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2027 add_entry!(first_hop_candidate, our_node_id, intro_node_id, blinded_path_fee,
2028 path_contribution_msat, candidate.htlc_minimum_msat(), 0_u64,
2029 candidate.cltv_expiry_delta(),
2030 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2034 for route in payment_params.payee.unblinded_route_hints().iter()
2035 .filter(|route| !route.0.is_empty())
2037 let first_hop_in_route = &(route.0)[0];
2038 let have_hop_src_in_graph =
2039 // Only add the hops in this route to our candidate set if either
2040 // we have a direct channel to the first hop or the first hop is
2041 // in the regular network graph.
2042 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
2043 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
2044 if have_hop_src_in_graph {
2045 // We start building the path from reverse, i.e., from payee
2046 // to the first RouteHintHop in the path.
2047 let hop_iter = route.0.iter().rev();
2048 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2049 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2050 let mut hop_used = true;
2051 let mut aggregate_next_hops_fee_msat: u64 = 0;
2052 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2053 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2054 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2055 let mut aggregate_next_hops_path_length: u8 = 0;
2056 let mut aggregate_path_contribution_msat = path_value_msat;
2058 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2059 let source = NodeId::from_pubkey(&hop.src_node_id);
2060 let target = NodeId::from_pubkey(&prev_hop_id);
2061 let candidate = network_channels
2062 .get(&hop.short_channel_id)
2063 .and_then(|channel| channel.as_directed_to(&target))
2064 .map(|(info, _)| CandidateRouteHop::PublicHop {
2066 short_channel_id: hop.short_channel_id,
2068 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
2070 if let Some(hop_used_msat) = add_entry!(candidate, source, target,
2071 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2072 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2073 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2075 aggregate_path_contribution_msat = hop_used_msat;
2077 // If this hop was not used then there is no use checking the preceding
2078 // hops in the RouteHint. We can break by just searching for a direct
2079 // channel between last checked hop and first_hop_targets.
2083 let used_liquidity_msat = used_liquidities
2084 .get(&candidate.id(source < target)).copied()
2086 let channel_usage = ChannelUsage {
2087 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2088 inflight_htlc_msat: used_liquidity_msat,
2089 effective_capacity: candidate.effective_capacity(),
2091 let channel_penalty_msat = scorer.channel_penalty_msat(
2092 hop.short_channel_id, &source, &target, channel_usage, score_params
2094 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2095 .saturating_add(channel_penalty_msat);
2097 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2098 .saturating_add(hop.cltv_expiry_delta as u32);
2100 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2103 // Searching for a direct channel between last checked hop and first_hop_targets
2104 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&prev_hop_id)) {
2105 sort_first_hop_channels(first_channels, &used_liquidities,
2106 recommended_value_msat, our_node_pubkey);
2107 for details in first_channels {
2108 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2109 add_entry!(first_hop_candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
2110 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2111 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2112 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2120 // In the next values of the iterator, the aggregate fees already reflects
2121 // the sum of value sent from payer (final_value_msat) and routing fees
2122 // for the last node in the RouteHint. We need to just add the fees to
2123 // route through the current node so that the preceding node (next iteration)
2125 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2126 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2127 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2129 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
2130 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
2131 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
2132 .checked_add(hop_htlc_minimum_msat_inc);
2133 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
2135 if idx == route.0.len() - 1 {
2136 // The last hop in this iterator is the first hop in
2137 // overall RouteHint.
2138 // If this hop connects to a node with which we have a direct channel,
2139 // ignore the network graph and, if the last hop was added, add our
2140 // direct channel to the candidate set.
2142 // Note that we *must* check if the last hop was added as `add_entry`
2143 // always assumes that the third argument is a node to which we have a
2145 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2146 sort_first_hop_channels(first_channels, &used_liquidities,
2147 recommended_value_msat, our_node_pubkey);
2148 for details in first_channels {
2149 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2150 add_entry!(first_hop_candidate, our_node_id,
2151 NodeId::from_pubkey(&hop.src_node_id),
2152 aggregate_next_hops_fee_msat,
2153 aggregate_path_contribution_msat,
2154 aggregate_next_hops_path_htlc_minimum_msat,
2155 aggregate_next_hops_path_penalty_msat,
2156 aggregate_next_hops_cltv_delta,
2157 aggregate_next_hops_path_length);
2165 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2167 // At this point, targets are filled with the data from first and
2168 // last hops communicated by the caller, and the payment receiver.
2169 let mut found_new_path = false;
2172 // If this loop terminates due the exhaustion of targets, two situations are possible:
2173 // - not enough outgoing liquidity:
2174 // 0 < already_collected_value_msat < final_value_msat
2175 // - enough outgoing liquidity:
2176 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2177 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2178 // paths_collection will be stopped because found_new_path==false.
2179 // This is not necessarily a routing failure.
2180 '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() {
2182 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2183 // traversing the graph and arrange the path out of what we found.
2184 if node_id == our_node_id {
2185 let mut new_entry = dist.remove(&our_node_id).unwrap();
2186 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2189 let mut features_set = false;
2190 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
2191 for details in first_channels {
2192 if let Some(scid) = ordered_hops.last().unwrap().0.candidate.short_channel_id() {
2193 if details.get_outbound_payment_scid().unwrap() == scid {
2194 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2195 features_set = true;
2202 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
2203 if let Some(node_info) = node.announcement_info.as_ref() {
2204 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2206 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2209 // We can fill in features for everything except hops which were
2210 // provided via the invoice we're paying. We could guess based on the
2211 // recipient's features but for now we simply avoid guessing at all.
2215 // Means we succesfully traversed from the payer to the payee, now
2216 // save this path for the payment route. Also, update the liquidity
2217 // remaining on the used hops, so that we take them into account
2218 // while looking for more paths.
2219 if ordered_hops.last().unwrap().0.node_id == maybe_dummy_payee_node_id {
2223 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
2224 Some(payment_hop) => payment_hop,
2225 // We can't arrive at None because, if we ever add an entry to targets,
2226 // we also fill in the entry in dist (see add_entry!).
2227 None => unreachable!(),
2229 // We "propagate" the fees one hop backward (topologically) here,
2230 // so that fees paid for a HTLC forwarding on the current channel are
2231 // associated with the previous channel (where they will be subtracted).
2232 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2233 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2235 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2236 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2238 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2239 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2241 let mut payment_path = PaymentPath {hops: ordered_hops};
2243 // We could have possibly constructed a slightly inconsistent path: since we reduce
2244 // value being transferred along the way, we could have violated htlc_minimum_msat
2245 // on some channels we already passed (assuming dest->source direction). Here, we
2246 // recompute the fees again, so that if that's the case, we match the currently
2247 // underpaid htlc_minimum_msat with fees.
2248 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2249 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
2250 payment_path.update_value_and_recompute_fees(value_contribution_msat);
2252 // Since a path allows to transfer as much value as
2253 // the smallest channel it has ("bottleneck"), we should recompute
2254 // the fees so sender HTLC don't overpay fees when traversing
2255 // larger channels than the bottleneck. This may happen because
2256 // when we were selecting those channels we were not aware how much value
2257 // this path will transfer, and the relative fee for them
2258 // might have been computed considering a larger value.
2259 // Remember that we used these channels so that we don't rely
2260 // on the same liquidity in future paths.
2261 let mut prevented_redundant_path_selection = false;
2262 let prev_hop_iter = core::iter::once(&our_node_id)
2263 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
2264 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
2265 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2266 let used_liquidity_msat = used_liquidities
2267 .entry(hop.candidate.id(*prev_hop < hop.node_id))
2268 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2269 .or_insert(spent_on_hop_msat);
2270 let hop_capacity = hop.candidate.effective_capacity();
2271 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2272 if *used_liquidity_msat == hop_max_msat {
2273 // If this path used all of this channel's available liquidity, we know
2274 // this path will not be selected again in the next loop iteration.
2275 prevented_redundant_path_selection = true;
2277 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2279 if !prevented_redundant_path_selection {
2280 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2281 // we'll probably end up picking the same path again on the next iteration.
2282 // Decrease the available liquidity of a hop in the middle of the path.
2283 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2284 let exhausted = u64::max_value();
2285 log_trace!(logger, "Disabling route candidate {} for future path building iterations to
2286 avoid duplicates.", LoggedCandidateHop(victim_candidate));
2287 *used_liquidities.entry(victim_candidate.id(false)).or_default() = exhausted;
2288 *used_liquidities.entry(victim_candidate.id(true)).or_default() = exhausted;
2291 // Track the total amount all our collected paths allow to send so that we know
2292 // when to stop looking for more paths
2293 already_collected_value_msat += value_contribution_msat;
2295 payment_paths.push(payment_path);
2296 found_new_path = true;
2297 break 'path_construction;
2300 // If we found a path back to the payee, we shouldn't try to process it again. This is
2301 // the equivalent of the `elem.was_processed` check in
2302 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2303 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2305 // Otherwise, since the current target node is not us,
2306 // keep "unrolling" the payment graph from payee to payer by
2307 // finding a way to reach the current target from the payer side.
2308 match network_nodes.get(&node_id) {
2311 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2312 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2313 total_cltv_delta, path_length_to_node);
2319 if !found_new_path && channel_saturation_pow_half != 0 {
2320 channel_saturation_pow_half = 0;
2321 continue 'paths_collection;
2323 // If we don't support MPP, no use trying to gather more value ever.
2324 break 'paths_collection;
2328 // Stop either when the recommended value is reached or if no new path was found in this
2330 // In the latter case, making another path finding attempt won't help,
2331 // because we deterministically terminated the search due to low liquidity.
2332 if !found_new_path && channel_saturation_pow_half != 0 {
2333 channel_saturation_pow_half = 0;
2334 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2335 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2336 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2337 break 'paths_collection;
2338 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2339 // Further, if this was our first walk of the graph, and we weren't limited by an
2340 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2341 // limited by an htlc_minimum_msat value, find another path with a higher value,
2342 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2343 // still keeping a lower total fee than this path.
2344 if !hit_minimum_limit {
2345 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2346 break 'paths_collection;
2348 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
2349 path_value_msat = recommended_value_msat;
2353 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2354 num_ignored_cltv_delta_limit + num_ignored_previously_failed;
2355 if num_ignored_total > 0 {
2356 log_trace!(logger, "Ignored {} candidate hops due to insufficient value contribution, {} due to path length limit, {} due to CLTV delta limit, {} due to previous payment failure. Total: {} ignored candidates.", num_ignored_value_contribution, num_ignored_path_length_limit, num_ignored_cltv_delta_limit, num_ignored_previously_failed, num_ignored_total);
2360 if payment_paths.len() == 0 {
2361 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2364 if already_collected_value_msat < final_value_msat {
2365 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2369 let mut selected_route = payment_paths;
2371 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2372 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2374 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2375 // the value they contribute towards the payment amount.
2376 // We sort in descending order as we will remove from the front in `retain`, next.
2377 selected_route.sort_unstable_by(|a, b|
2378 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2379 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2382 // We should make sure that at least 1 path left.
2383 let mut paths_left = selected_route.len();
2384 selected_route.retain(|path| {
2385 if paths_left == 1 {
2388 let path_value_msat = path.get_value_msat();
2389 if path_value_msat <= overpaid_value_msat {
2390 overpaid_value_msat -= path_value_msat;
2396 debug_assert!(selected_route.len() > 0);
2398 if overpaid_value_msat != 0 {
2400 // Now, subtract the remaining overpaid value from the most-expensive path.
2401 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2402 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2403 selected_route.sort_unstable_by(|a, b| {
2404 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2405 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2406 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2408 let expensive_payment_path = selected_route.first_mut().unwrap();
2410 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2411 // can't go negative.
2412 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2413 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2417 // Sort by the path itself and combine redundant paths.
2418 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2419 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2421 selected_route.sort_unstable_by_key(|path| {
2422 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2423 debug_assert!(path.hops.len() <= key.len());
2424 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id(true)).zip(key.iter_mut()) {
2429 for idx in 0..(selected_route.len() - 1) {
2430 if idx + 1 >= selected_route.len() { break; }
2431 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id)),
2432 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id))) {
2433 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2434 selected_route[idx].update_value_and_recompute_fees(new_value);
2435 selected_route.remove(idx + 1);
2439 let mut paths = Vec::new();
2440 for payment_path in selected_route {
2441 let mut hops = Vec::with_capacity(payment_path.hops.len());
2442 for (hop, node_features) in payment_path.hops.iter()
2443 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2445 hops.push(RouteHop {
2446 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)})?,
2447 node_features: node_features.clone(),
2448 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2449 channel_features: hop.candidate.features(),
2450 fee_msat: hop.fee_msat,
2451 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2454 let mut final_cltv_delta = final_cltv_expiry_delta;
2455 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2456 if let Some(blinded_path) = h.candidate.blinded_path() {
2457 final_cltv_delta = h.candidate.cltv_expiry_delta();
2459 hops: blinded_path.blinded_hops.clone(),
2460 blinding_point: blinded_path.blinding_point,
2461 excess_final_cltv_expiry_delta: 0,
2462 final_value_msat: h.fee_msat,
2466 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2467 // applicable for the previous hop.
2468 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2469 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2472 paths.push(Path { hops, blinded_tail });
2474 // Make sure we would never create a route with more paths than we allow.
2475 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2477 if let Some(node_features) = payment_params.payee.node_features() {
2478 for path in paths.iter_mut() {
2479 path.hops.last_mut().unwrap().node_features = node_features.clone();
2483 let route = Route { paths, payment_params: Some(payment_params.clone()) };
2484 log_info!(logger, "Got route: {}", log_route!(route));
2488 // When an adversarial intermediary node observes a payment, it may be able to infer its
2489 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2490 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2491 // payment path by adding a randomized 'shadow route' offset to the final hop.
2492 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2493 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2495 let network_channels = network_graph.channels();
2496 let network_nodes = network_graph.nodes();
2498 for path in route.paths.iter_mut() {
2499 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2501 // Remember the last three nodes of the random walk and avoid looping back on them.
2502 // Init with the last three nodes from the actual path, if possible.
2503 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2504 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2505 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2507 // Choose the last publicly known node as the starting point for the random walk.
2508 let mut cur_hop: Option<NodeId> = None;
2509 let mut path_nonce = [0u8; 12];
2510 if let Some(starting_hop) = path.hops.iter().rev()
2511 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2512 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2513 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2516 // Init PRNG with the path-dependant nonce, which is static for private paths.
2517 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2518 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2520 // Pick a random path length in [1 .. 3]
2521 prng.process_in_place(&mut random_path_bytes);
2522 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2524 for random_hop in 0..random_walk_length {
2525 // If we don't find a suitable offset in the public network graph, we default to
2526 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2527 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2529 if let Some(cur_node_id) = cur_hop {
2530 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2531 // Randomly choose the next unvisited hop.
2532 prng.process_in_place(&mut random_path_bytes);
2533 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2534 .checked_rem(cur_node.channels.len())
2535 .and_then(|index| cur_node.channels.get(index))
2536 .and_then(|id| network_channels.get(id)) {
2537 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2538 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2539 nodes_to_avoid[random_hop] = *next_id;
2540 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2541 cur_hop = Some(*next_id);
2548 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2549 .checked_add(random_hop_offset)
2550 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2553 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2554 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2555 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2557 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2558 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2559 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2560 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2561 max_path_offset = cmp::max(
2562 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2563 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2564 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2566 // Add 'shadow' CLTV offset to the final hop
2567 if let Some(tail) = path.blinded_tail.as_mut() {
2568 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2569 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2571 if let Some(last_hop) = path.hops.last_mut() {
2572 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2573 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2578 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2579 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2581 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2582 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2583 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2584 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2585 ) -> Result<Route, LightningError>
2586 where L::Target: Logger, GL::Target: Logger {
2587 let graph_lock = network_graph.read_only();
2588 let mut route = build_route_from_hops_internal(
2589 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
2590 route_params.final_value_msat, logger, random_seed_bytes)?;
2591 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2595 fn build_route_from_hops_internal<L: Deref>(
2596 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
2597 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, logger: L,
2598 random_seed_bytes: &[u8; 32]
2599 ) -> Result<Route, LightningError> where L::Target: Logger {
2602 our_node_id: NodeId,
2603 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2606 impl ScoreLookUp for HopScorer {
2607 type ScoreParams = ();
2608 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2609 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2611 let mut cur_id = self.our_node_id;
2612 for i in 0..self.hop_ids.len() {
2613 if let Some(next_id) = self.hop_ids[i] {
2614 if cur_id == *source && next_id == *target {
2626 impl<'a> Writeable for HopScorer {
2628 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2633 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2634 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2637 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2638 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2639 for i in 0..hops.len() {
2640 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2643 let scorer = HopScorer { our_node_id, hop_ids };
2645 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
2646 logger, &scorer, &(), random_seed_bytes)
2651 use crate::blinded_path::{BlindedHop, BlindedPath};
2652 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2653 use crate::routing::utxo::UtxoResult;
2654 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2655 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2656 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
2657 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2658 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2659 use crate::chain::transaction::OutPoint;
2660 use crate::sign::EntropySource;
2661 use crate::ln::ChannelId;
2662 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2663 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2664 use crate::ln::channelmanager;
2665 use crate::offers::invoice::BlindedPayInfo;
2666 use crate::util::config::UserConfig;
2667 use crate::util::test_utils as ln_test_utils;
2668 use crate::util::chacha20::ChaCha20;
2669 use crate::util::ser::{Readable, Writeable};
2671 use crate::util::ser::Writer;
2673 use bitcoin::hashes::Hash;
2674 use bitcoin::network::constants::Network;
2675 use bitcoin::blockdata::constants::genesis_block;
2676 use bitcoin::blockdata::script::Builder;
2677 use bitcoin::blockdata::opcodes;
2678 use bitcoin::blockdata::transaction::TxOut;
2682 use bitcoin::secp256k1::{PublicKey,SecretKey};
2683 use bitcoin::secp256k1::Secp256k1;
2685 use crate::io::Cursor;
2686 use crate::prelude::*;
2687 use crate::sync::Arc;
2689 use core::convert::TryInto;
2691 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2692 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2693 channelmanager::ChannelDetails {
2694 channel_id: ChannelId::new_zero(),
2695 counterparty: channelmanager::ChannelCounterparty {
2698 unspendable_punishment_reserve: 0,
2699 forwarding_info: None,
2700 outbound_htlc_minimum_msat: None,
2701 outbound_htlc_maximum_msat: None,
2703 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2706 outbound_scid_alias: None,
2707 inbound_scid_alias: None,
2708 channel_value_satoshis: 0,
2710 outbound_capacity_msat,
2711 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2712 next_outbound_htlc_minimum_msat: 0,
2713 inbound_capacity_msat: 42,
2714 unspendable_punishment_reserve: None,
2715 confirmations_required: None,
2716 confirmations: None,
2717 force_close_spend_delay: None,
2718 is_outbound: true, is_channel_ready: true,
2719 is_usable: true, is_public: true,
2720 inbound_htlc_minimum_msat: None,
2721 inbound_htlc_maximum_msat: None,
2723 feerate_sat_per_1000_weight: None,
2724 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
2729 fn simple_route_test() {
2730 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2731 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2732 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2733 let scorer = ln_test_utils::TestScorer::new();
2734 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2735 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2737 // Simple route to 2 via 1
2739 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 0, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2740 assert_eq!(err, "Cannot send a payment of 0 msat");
2741 } else { panic!(); }
2743 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2744 assert_eq!(route.paths[0].hops.len(), 2);
2746 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2747 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2748 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2749 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2750 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2751 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2753 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2754 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2755 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2756 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2757 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2758 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2762 fn invalid_first_hop_test() {
2763 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2764 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2765 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2766 let scorer = ln_test_utils::TestScorer::new();
2767 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2768 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2770 // Simple route to 2 via 1
2772 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2774 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2775 get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2776 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2777 } else { panic!(); }
2779 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2780 assert_eq!(route.paths[0].hops.len(), 2);
2784 fn htlc_minimum_test() {
2785 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2786 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2787 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2788 let scorer = ln_test_utils::TestScorer::new();
2789 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2790 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2792 // Simple route to 2 via 1
2794 // Disable other paths
2795 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2796 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2797 short_channel_id: 12,
2799 flags: 2, // to disable
2800 cltv_expiry_delta: 0,
2801 htlc_minimum_msat: 0,
2802 htlc_maximum_msat: MAX_VALUE_MSAT,
2804 fee_proportional_millionths: 0,
2805 excess_data: Vec::new()
2807 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2808 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2809 short_channel_id: 3,
2811 flags: 2, // to disable
2812 cltv_expiry_delta: 0,
2813 htlc_minimum_msat: 0,
2814 htlc_maximum_msat: MAX_VALUE_MSAT,
2816 fee_proportional_millionths: 0,
2817 excess_data: Vec::new()
2819 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2820 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2821 short_channel_id: 13,
2823 flags: 2, // to disable
2824 cltv_expiry_delta: 0,
2825 htlc_minimum_msat: 0,
2826 htlc_maximum_msat: MAX_VALUE_MSAT,
2828 fee_proportional_millionths: 0,
2829 excess_data: Vec::new()
2831 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2832 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2833 short_channel_id: 6,
2835 flags: 2, // to disable
2836 cltv_expiry_delta: 0,
2837 htlc_minimum_msat: 0,
2838 htlc_maximum_msat: MAX_VALUE_MSAT,
2840 fee_proportional_millionths: 0,
2841 excess_data: Vec::new()
2843 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2844 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2845 short_channel_id: 7,
2847 flags: 2, // to disable
2848 cltv_expiry_delta: 0,
2849 htlc_minimum_msat: 0,
2850 htlc_maximum_msat: MAX_VALUE_MSAT,
2852 fee_proportional_millionths: 0,
2853 excess_data: Vec::new()
2856 // Check against amount_to_transfer_over_msat.
2857 // Set minimal HTLC of 200_000_000 msat.
2858 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2859 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2860 short_channel_id: 2,
2863 cltv_expiry_delta: 0,
2864 htlc_minimum_msat: 200_000_000,
2865 htlc_maximum_msat: MAX_VALUE_MSAT,
2867 fee_proportional_millionths: 0,
2868 excess_data: Vec::new()
2871 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2873 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2874 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2875 short_channel_id: 4,
2878 cltv_expiry_delta: 0,
2879 htlc_minimum_msat: 0,
2880 htlc_maximum_msat: 199_999_999,
2882 fee_proportional_millionths: 0,
2883 excess_data: Vec::new()
2886 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2887 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 199_999_999, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2888 assert_eq!(err, "Failed to find a path to the given destination");
2889 } else { panic!(); }
2891 // Lift the restriction on the first hop.
2892 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2893 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2894 short_channel_id: 2,
2897 cltv_expiry_delta: 0,
2898 htlc_minimum_msat: 0,
2899 htlc_maximum_msat: MAX_VALUE_MSAT,
2901 fee_proportional_millionths: 0,
2902 excess_data: Vec::new()
2905 // A payment above the minimum should pass
2906 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 199_999_999, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2907 assert_eq!(route.paths[0].hops.len(), 2);
2911 fn htlc_minimum_overpay_test() {
2912 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2913 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2914 let config = UserConfig::default();
2915 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
2916 let scorer = ln_test_utils::TestScorer::new();
2917 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2918 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2920 // A route to node#2 via two paths.
2921 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2922 // Thus, they can't send 60 without overpaying.
2923 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2924 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2925 short_channel_id: 2,
2928 cltv_expiry_delta: 0,
2929 htlc_minimum_msat: 35_000,
2930 htlc_maximum_msat: 40_000,
2932 fee_proportional_millionths: 0,
2933 excess_data: Vec::new()
2935 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2936 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2937 short_channel_id: 12,
2940 cltv_expiry_delta: 0,
2941 htlc_minimum_msat: 35_000,
2942 htlc_maximum_msat: 40_000,
2944 fee_proportional_millionths: 0,
2945 excess_data: Vec::new()
2949 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2950 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2951 short_channel_id: 13,
2954 cltv_expiry_delta: 0,
2955 htlc_minimum_msat: 0,
2956 htlc_maximum_msat: MAX_VALUE_MSAT,
2958 fee_proportional_millionths: 0,
2959 excess_data: Vec::new()
2961 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2962 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2963 short_channel_id: 4,
2966 cltv_expiry_delta: 0,
2967 htlc_minimum_msat: 0,
2968 htlc_maximum_msat: MAX_VALUE_MSAT,
2970 fee_proportional_millionths: 0,
2971 excess_data: Vec::new()
2974 // Disable other paths
2975 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2976 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2977 short_channel_id: 1,
2979 flags: 2, // to disable
2980 cltv_expiry_delta: 0,
2981 htlc_minimum_msat: 0,
2982 htlc_maximum_msat: MAX_VALUE_MSAT,
2984 fee_proportional_millionths: 0,
2985 excess_data: Vec::new()
2988 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2989 // Overpay fees to hit htlc_minimum_msat.
2990 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
2991 // TODO: this could be better balanced to overpay 10k and not 15k.
2992 assert_eq!(overpaid_fees, 15_000);
2994 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2995 // while taking even more fee to match htlc_minimum_msat.
2996 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2997 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2998 short_channel_id: 12,
3001 cltv_expiry_delta: 0,
3002 htlc_minimum_msat: 65_000,
3003 htlc_maximum_msat: 80_000,
3005 fee_proportional_millionths: 0,
3006 excess_data: Vec::new()
3008 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3009 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3010 short_channel_id: 2,
3013 cltv_expiry_delta: 0,
3014 htlc_minimum_msat: 0,
3015 htlc_maximum_msat: MAX_VALUE_MSAT,
3017 fee_proportional_millionths: 0,
3018 excess_data: Vec::new()
3020 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3021 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3022 short_channel_id: 4,
3025 cltv_expiry_delta: 0,
3026 htlc_minimum_msat: 0,
3027 htlc_maximum_msat: MAX_VALUE_MSAT,
3029 fee_proportional_millionths: 100_000,
3030 excess_data: Vec::new()
3033 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3034 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3035 assert_eq!(route.paths.len(), 1);
3036 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3037 let fees = route.paths[0].hops[0].fee_msat;
3038 assert_eq!(fees, 5_000);
3040 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3041 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3042 // the other channel.
3043 assert_eq!(route.paths.len(), 1);
3044 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3045 let fees = route.paths[0].hops[0].fee_msat;
3046 assert_eq!(fees, 5_000);
3050 fn disable_channels_test() {
3051 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3052 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3053 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3054 let scorer = ln_test_utils::TestScorer::new();
3055 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3056 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3058 // // Disable channels 4 and 12 by flags=2
3059 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3060 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3061 short_channel_id: 4,
3063 flags: 2, // to disable
3064 cltv_expiry_delta: 0,
3065 htlc_minimum_msat: 0,
3066 htlc_maximum_msat: MAX_VALUE_MSAT,
3068 fee_proportional_millionths: 0,
3069 excess_data: Vec::new()
3071 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3072 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3073 short_channel_id: 12,
3075 flags: 2, // to disable
3076 cltv_expiry_delta: 0,
3077 htlc_minimum_msat: 0,
3078 htlc_maximum_msat: MAX_VALUE_MSAT,
3080 fee_proportional_millionths: 0,
3081 excess_data: Vec::new()
3084 // If all the channels require some features we don't understand, route should fail
3085 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3086 assert_eq!(err, "Failed to find a path to the given destination");
3087 } else { panic!(); }
3089 // If we specify a channel to node7, that overrides our local channel view and that gets used
3090 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3091 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3092 assert_eq!(route.paths[0].hops.len(), 2);
3094 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3095 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3096 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3097 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3098 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3099 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3101 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3102 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3103 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3104 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3105 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3106 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3110 fn disable_node_test() {
3111 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3112 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3113 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3114 let scorer = ln_test_utils::TestScorer::new();
3115 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3116 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3118 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3119 let mut unknown_features = NodeFeatures::empty();
3120 unknown_features.set_unknown_feature_required();
3121 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3122 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3123 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3125 // If all nodes require some features we don't understand, route should fail
3126 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3127 assert_eq!(err, "Failed to find a path to the given destination");
3128 } else { panic!(); }
3130 // If we specify a channel to node7, that overrides our local channel view and that gets used
3131 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3132 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3133 assert_eq!(route.paths[0].hops.len(), 2);
3135 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3136 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3137 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3138 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3139 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3140 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3142 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3143 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3144 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3145 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3146 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3147 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3149 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3150 // naively) assume that the user checked the feature bits on the invoice, which override
3151 // the node_announcement.
3155 fn our_chans_test() {
3156 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3157 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3158 let scorer = ln_test_utils::TestScorer::new();
3159 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3160 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3162 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3163 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3164 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3165 assert_eq!(route.paths[0].hops.len(), 3);
3167 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3168 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3169 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3170 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3171 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3172 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3174 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3175 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3176 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3177 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3178 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3179 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3181 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3182 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3183 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3184 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3185 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3186 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3188 // If we specify a channel to node7, that overrides our local channel view and that gets used
3189 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3190 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3191 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3192 assert_eq!(route.paths[0].hops.len(), 2);
3194 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3195 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3196 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3197 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3198 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3199 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3201 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3202 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3203 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3204 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3205 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3206 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3209 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3210 let zero_fees = RoutingFees {
3212 proportional_millionths: 0,
3214 vec![RouteHint(vec![RouteHintHop {
3215 src_node_id: nodes[3],
3216 short_channel_id: 8,
3218 cltv_expiry_delta: (8 << 4) | 1,
3219 htlc_minimum_msat: None,
3220 htlc_maximum_msat: None,
3222 ]), RouteHint(vec![RouteHintHop {
3223 src_node_id: nodes[4],
3224 short_channel_id: 9,
3227 proportional_millionths: 0,
3229 cltv_expiry_delta: (9 << 4) | 1,
3230 htlc_minimum_msat: None,
3231 htlc_maximum_msat: None,
3232 }]), RouteHint(vec![RouteHintHop {
3233 src_node_id: nodes[5],
3234 short_channel_id: 10,
3236 cltv_expiry_delta: (10 << 4) | 1,
3237 htlc_minimum_msat: None,
3238 htlc_maximum_msat: None,
3242 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3243 let zero_fees = RoutingFees {
3245 proportional_millionths: 0,
3247 vec![RouteHint(vec![RouteHintHop {
3248 src_node_id: nodes[2],
3249 short_channel_id: 5,
3252 proportional_millionths: 0,
3254 cltv_expiry_delta: (5 << 4) | 1,
3255 htlc_minimum_msat: None,
3256 htlc_maximum_msat: None,
3258 src_node_id: nodes[3],
3259 short_channel_id: 8,
3261 cltv_expiry_delta: (8 << 4) | 1,
3262 htlc_minimum_msat: None,
3263 htlc_maximum_msat: None,
3265 ]), RouteHint(vec![RouteHintHop {
3266 src_node_id: nodes[4],
3267 short_channel_id: 9,
3270 proportional_millionths: 0,
3272 cltv_expiry_delta: (9 << 4) | 1,
3273 htlc_minimum_msat: None,
3274 htlc_maximum_msat: None,
3275 }]), RouteHint(vec![RouteHintHop {
3276 src_node_id: nodes[5],
3277 short_channel_id: 10,
3279 cltv_expiry_delta: (10 << 4) | 1,
3280 htlc_minimum_msat: None,
3281 htlc_maximum_msat: None,
3286 fn partial_route_hint_test() {
3287 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3288 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3289 let scorer = ln_test_utils::TestScorer::new();
3290 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3291 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3293 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3294 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3295 // RouteHint may be partially used by the algo to build the best path.
3297 // First check that last hop can't have its source as the payee.
3298 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3299 src_node_id: nodes[6],
3300 short_channel_id: 8,
3303 proportional_millionths: 0,
3305 cltv_expiry_delta: (8 << 4) | 1,
3306 htlc_minimum_msat: None,
3307 htlc_maximum_msat: None,
3310 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3311 invalid_last_hops.push(invalid_last_hop);
3313 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(invalid_last_hops).unwrap();
3314 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3315 assert_eq!(err, "Route hint cannot have the payee as the source.");
3316 } else { panic!(); }
3319 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3320 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3321 assert_eq!(route.paths[0].hops.len(), 5);
3323 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3324 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3325 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3326 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3327 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3328 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3330 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3331 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3332 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3333 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3334 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3335 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3337 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3338 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3339 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3340 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3341 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3342 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3344 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3345 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3346 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3347 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3348 // If we have a peer in the node map, we'll use their features here since we don't have
3349 // a way of figuring out their features from the invoice:
3350 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3351 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3353 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3354 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3355 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3356 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3357 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3358 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3361 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3362 let zero_fees = RoutingFees {
3364 proportional_millionths: 0,
3366 vec![RouteHint(vec![RouteHintHop {
3367 src_node_id: nodes[3],
3368 short_channel_id: 8,
3370 cltv_expiry_delta: (8 << 4) | 1,
3371 htlc_minimum_msat: None,
3372 htlc_maximum_msat: None,
3373 }]), RouteHint(vec![
3375 ]), RouteHint(vec![RouteHintHop {
3376 src_node_id: nodes[5],
3377 short_channel_id: 10,
3379 cltv_expiry_delta: (10 << 4) | 1,
3380 htlc_minimum_msat: None,
3381 htlc_maximum_msat: None,
3386 fn ignores_empty_last_hops_test() {
3387 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3388 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3389 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3390 let scorer = ln_test_utils::TestScorer::new();
3391 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3392 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3394 // Test handling of an empty RouteHint passed in Invoice.
3396 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3397 assert_eq!(route.paths[0].hops.len(), 5);
3399 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3400 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3401 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3402 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3403 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3404 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3406 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3407 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3408 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3409 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3410 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3411 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3413 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3414 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3415 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3416 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3417 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3418 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3420 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3421 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3422 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3423 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3424 // If we have a peer in the node map, we'll use their features here since we don't have
3425 // a way of figuring out their features from the invoice:
3426 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3427 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3429 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3430 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3431 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3432 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3433 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3434 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3437 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3439 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3440 let zero_fees = RoutingFees {
3442 proportional_millionths: 0,
3444 vec![RouteHint(vec![RouteHintHop {
3445 src_node_id: hint_hops[0],
3446 short_channel_id: 0xff00,
3449 proportional_millionths: 0,
3451 cltv_expiry_delta: (5 << 4) | 1,
3452 htlc_minimum_msat: None,
3453 htlc_maximum_msat: None,
3455 src_node_id: hint_hops[1],
3456 short_channel_id: 0xff01,
3458 cltv_expiry_delta: (8 << 4) | 1,
3459 htlc_minimum_msat: None,
3460 htlc_maximum_msat: None,
3465 fn multi_hint_last_hops_test() {
3466 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3467 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3468 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3469 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3470 let scorer = ln_test_utils::TestScorer::new();
3471 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3472 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3473 // Test through channels 2, 3, 0xff00, 0xff01.
3474 // Test shows that multiple hop hints are considered.
3476 // Disabling channels 6 & 7 by flags=2
3477 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3478 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3479 short_channel_id: 6,
3481 flags: 2, // to disable
3482 cltv_expiry_delta: 0,
3483 htlc_minimum_msat: 0,
3484 htlc_maximum_msat: MAX_VALUE_MSAT,
3486 fee_proportional_millionths: 0,
3487 excess_data: Vec::new()
3489 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3490 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3491 short_channel_id: 7,
3493 flags: 2, // to disable
3494 cltv_expiry_delta: 0,
3495 htlc_minimum_msat: 0,
3496 htlc_maximum_msat: MAX_VALUE_MSAT,
3498 fee_proportional_millionths: 0,
3499 excess_data: Vec::new()
3502 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3503 assert_eq!(route.paths[0].hops.len(), 4);
3505 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3506 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3507 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3508 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3509 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3510 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3512 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3513 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3514 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3515 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3516 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3517 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3519 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3520 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3521 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3522 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3523 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3524 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3526 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3527 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3528 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3529 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3530 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3531 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3535 fn private_multi_hint_last_hops_test() {
3536 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3537 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3539 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3540 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3542 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3543 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3544 let scorer = ln_test_utils::TestScorer::new();
3545 // Test through channels 2, 3, 0xff00, 0xff01.
3546 // Test shows that multiple hop hints are considered.
3548 // Disabling channels 6 & 7 by flags=2
3549 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3550 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3551 short_channel_id: 6,
3553 flags: 2, // to disable
3554 cltv_expiry_delta: 0,
3555 htlc_minimum_msat: 0,
3556 htlc_maximum_msat: MAX_VALUE_MSAT,
3558 fee_proportional_millionths: 0,
3559 excess_data: Vec::new()
3561 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3562 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3563 short_channel_id: 7,
3565 flags: 2, // to disable
3566 cltv_expiry_delta: 0,
3567 htlc_minimum_msat: 0,
3568 htlc_maximum_msat: MAX_VALUE_MSAT,
3570 fee_proportional_millionths: 0,
3571 excess_data: Vec::new()
3574 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &[42u8; 32]).unwrap();
3575 assert_eq!(route.paths[0].hops.len(), 4);
3577 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3578 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3579 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3580 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3581 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3582 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3584 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3585 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3586 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3587 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3588 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3589 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3591 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3592 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3593 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3594 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3595 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3596 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3598 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3599 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3600 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3601 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3602 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3603 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3606 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3607 let zero_fees = RoutingFees {
3609 proportional_millionths: 0,
3611 vec![RouteHint(vec![RouteHintHop {
3612 src_node_id: nodes[4],
3613 short_channel_id: 11,
3615 cltv_expiry_delta: (11 << 4) | 1,
3616 htlc_minimum_msat: None,
3617 htlc_maximum_msat: None,
3619 src_node_id: nodes[3],
3620 short_channel_id: 8,
3622 cltv_expiry_delta: (8 << 4) | 1,
3623 htlc_minimum_msat: None,
3624 htlc_maximum_msat: None,
3625 }]), RouteHint(vec![RouteHintHop {
3626 src_node_id: nodes[4],
3627 short_channel_id: 9,
3630 proportional_millionths: 0,
3632 cltv_expiry_delta: (9 << 4) | 1,
3633 htlc_minimum_msat: None,
3634 htlc_maximum_msat: None,
3635 }]), RouteHint(vec![RouteHintHop {
3636 src_node_id: nodes[5],
3637 short_channel_id: 10,
3639 cltv_expiry_delta: (10 << 4) | 1,
3640 htlc_minimum_msat: None,
3641 htlc_maximum_msat: None,
3646 fn last_hops_with_public_channel_test() {
3647 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3648 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3649 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
3650 let scorer = ln_test_utils::TestScorer::new();
3651 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3652 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3653 // This test shows that public routes can be present in the invoice
3654 // which would be handled in the same manner.
3656 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3657 assert_eq!(route.paths[0].hops.len(), 5);
3659 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3660 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3661 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3662 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3663 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3664 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3666 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3667 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3668 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3669 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3670 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3671 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3673 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3674 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3675 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3676 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3677 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3678 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3680 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3681 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3682 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3683 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3684 // If we have a peer in the node map, we'll use their features here since we don't have
3685 // a way of figuring out their features from the invoice:
3686 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3687 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3689 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3690 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3691 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3692 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3693 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3694 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3698 fn our_chans_last_hop_connect_test() {
3699 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3700 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3701 let scorer = ln_test_utils::TestScorer::new();
3702 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3703 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3705 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3706 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3707 let mut last_hops = last_hops(&nodes);
3708 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3709 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3710 assert_eq!(route.paths[0].hops.len(), 2);
3712 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3713 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3714 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3715 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3716 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3717 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3719 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3720 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3721 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3722 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3723 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3724 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3726 last_hops[0].0[0].fees.base_msat = 1000;
3728 // Revert to via 6 as the fee on 8 goes up
3729 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops).unwrap();
3730 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3731 assert_eq!(route.paths[0].hops.len(), 4);
3733 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3734 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3735 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
3736 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3737 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3738 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3740 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3741 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3742 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3743 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
3744 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3745 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3747 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
3748 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3749 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3750 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3751 // If we have a peer in the node map, we'll use their features here since we don't have
3752 // a way of figuring out their features from the invoice:
3753 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3754 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3756 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3757 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3758 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3759 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3760 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3761 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3763 // ...but still use 8 for larger payments as 6 has a variable feerate
3764 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3765 assert_eq!(route.paths[0].hops.len(), 5);
3767 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3768 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3769 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3770 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3771 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3772 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3774 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3775 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3776 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3777 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3778 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3779 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3781 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3782 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3783 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3784 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3785 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3786 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3788 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3789 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3790 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
3791 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3792 // If we have a peer in the node map, we'll use their features here since we don't have
3793 // a way of figuring out their features from the invoice:
3794 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3795 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3797 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3798 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3799 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
3800 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3801 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3802 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3805 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> {
3806 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3807 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3808 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3810 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3811 let last_hops = RouteHint(vec![RouteHintHop {
3812 src_node_id: middle_node_id,
3813 short_channel_id: 8,
3816 proportional_millionths: last_hop_fee_prop,
3818 cltv_expiry_delta: (8 << 4) | 1,
3819 htlc_minimum_msat: None,
3820 htlc_maximum_msat: last_hop_htlc_max,
3822 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
3823 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3824 let scorer = ln_test_utils::TestScorer::new();
3825 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3826 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3827 let logger = ln_test_utils::TestLogger::new();
3828 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3829 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3830 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, &logger, &scorer, &(), &random_seed_bytes);
3835 fn unannounced_path_test() {
3836 // We should be able to send a payment to a destination without any help of a routing graph
3837 // if we have a channel with a common counterparty that appears in the first and last hop
3839 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3841 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3842 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3843 assert_eq!(route.paths[0].hops.len(), 2);
3845 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
3846 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3847 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
3848 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3849 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
3850 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3852 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
3853 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3854 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
3855 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3856 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3857 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3861 fn overflow_unannounced_path_test_liquidity_underflow() {
3862 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3863 // the last-hop had a fee which overflowed a u64, we'd panic.
3864 // This was due to us adding the first-hop from us unconditionally, causing us to think
3865 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3866 // In this test, we previously hit a subtraction underflow due to having less available
3867 // liquidity at the last hop than 0.
3868 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());
3872 fn overflow_unannounced_path_test_feerate_overflow() {
3873 // This tests for the same case as above, except instead of hitting a subtraction
3874 // underflow, we hit a case where the fee charged at a hop overflowed.
3875 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());
3879 fn available_amount_while_routing_test() {
3880 // Tests whether we choose the correct available channel amount while routing.
3882 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
3883 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3884 let scorer = ln_test_utils::TestScorer::new();
3885 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3886 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3887 let config = UserConfig::default();
3888 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3890 // We will use a simple single-path route from
3891 // our node to node2 via node0: channels {1, 3}.
3893 // First disable all other paths.
3894 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3895 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3896 short_channel_id: 2,
3899 cltv_expiry_delta: 0,
3900 htlc_minimum_msat: 0,
3901 htlc_maximum_msat: 100_000,
3903 fee_proportional_millionths: 0,
3904 excess_data: Vec::new()
3906 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3907 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3908 short_channel_id: 12,
3911 cltv_expiry_delta: 0,
3912 htlc_minimum_msat: 0,
3913 htlc_maximum_msat: 100_000,
3915 fee_proportional_millionths: 0,
3916 excess_data: Vec::new()
3919 // Make the first channel (#1) very permissive,
3920 // and we will be testing all limits on the second channel.
3921 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3922 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3923 short_channel_id: 1,
3926 cltv_expiry_delta: 0,
3927 htlc_minimum_msat: 0,
3928 htlc_maximum_msat: 1_000_000_000,
3930 fee_proportional_millionths: 0,
3931 excess_data: Vec::new()
3934 // First, let's see if routing works if we have absolutely no idea about the available amount.
3935 // In this case, it should be set to 250_000 sats.
3936 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3937 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3938 short_channel_id: 3,
3941 cltv_expiry_delta: 0,
3942 htlc_minimum_msat: 0,
3943 htlc_maximum_msat: 250_000_000,
3945 fee_proportional_millionths: 0,
3946 excess_data: Vec::new()
3950 // Attempt to route more than available results in a failure.
3951 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3952 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3953 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3954 } else { panic!(); }
3958 // Now, attempt to route an exact amount we have should be fine.
3959 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000_000, Arc::clone(&logger), &scorer, &(),&random_seed_bytes).unwrap();
3960 assert_eq!(route.paths.len(), 1);
3961 let path = route.paths.last().unwrap();
3962 assert_eq!(path.hops.len(), 2);
3963 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3964 assert_eq!(path.final_value_msat(), 250_000_000);
3967 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3968 // Disable channel #1 and use another first hop.
3969 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3970 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3971 short_channel_id: 1,
3974 cltv_expiry_delta: 0,
3975 htlc_minimum_msat: 0,
3976 htlc_maximum_msat: 1_000_000_000,
3978 fee_proportional_millionths: 0,
3979 excess_data: Vec::new()
3982 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3983 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3986 // Attempt to route more than available results in a failure.
3987 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3988 &our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3989 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3990 } else { panic!(); }
3994 // Now, attempt to route an exact amount we have should be fine.
3995 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3996 assert_eq!(route.paths.len(), 1);
3997 let path = route.paths.last().unwrap();
3998 assert_eq!(path.hops.len(), 2);
3999 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4000 assert_eq!(path.final_value_msat(), 200_000_000);
4003 // Enable channel #1 back.
4004 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4005 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4006 short_channel_id: 1,
4009 cltv_expiry_delta: 0,
4010 htlc_minimum_msat: 0,
4011 htlc_maximum_msat: 1_000_000_000,
4013 fee_proportional_millionths: 0,
4014 excess_data: Vec::new()
4018 // Now let's see if routing works if we know only htlc_maximum_msat.
4019 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4020 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4021 short_channel_id: 3,
4024 cltv_expiry_delta: 0,
4025 htlc_minimum_msat: 0,
4026 htlc_maximum_msat: 15_000,
4028 fee_proportional_millionths: 0,
4029 excess_data: Vec::new()
4033 // Attempt to route more than available results in a failure.
4034 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4035 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4036 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4037 } else { panic!(); }
4041 // Now, attempt to route an exact amount we have should be fine.
4042 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4043 assert_eq!(route.paths.len(), 1);
4044 let path = route.paths.last().unwrap();
4045 assert_eq!(path.hops.len(), 2);
4046 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4047 assert_eq!(path.final_value_msat(), 15_000);
4050 // Now let's see if routing works if we know only capacity from the UTXO.
4052 // We can't change UTXO capacity on the fly, so we'll disable
4053 // the existing channel and add another one with the capacity we need.
4054 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4055 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4056 short_channel_id: 3,
4059 cltv_expiry_delta: 0,
4060 htlc_minimum_msat: 0,
4061 htlc_maximum_msat: MAX_VALUE_MSAT,
4063 fee_proportional_millionths: 0,
4064 excess_data: Vec::new()
4067 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4068 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4069 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4070 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4071 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4073 *chain_monitor.utxo_ret.lock().unwrap() =
4074 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4075 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4077 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4078 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4079 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4080 short_channel_id: 333,
4083 cltv_expiry_delta: (3 << 4) | 1,
4084 htlc_minimum_msat: 0,
4085 htlc_maximum_msat: 15_000,
4087 fee_proportional_millionths: 0,
4088 excess_data: Vec::new()
4090 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4091 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4092 short_channel_id: 333,
4095 cltv_expiry_delta: (3 << 4) | 2,
4096 htlc_minimum_msat: 0,
4097 htlc_maximum_msat: 15_000,
4099 fee_proportional_millionths: 0,
4100 excess_data: Vec::new()
4104 // Attempt to route more than available results in a failure.
4105 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4106 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4107 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4108 } else { panic!(); }
4112 // Now, attempt to route an exact amount we have should be fine.
4113 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4114 assert_eq!(route.paths.len(), 1);
4115 let path = route.paths.last().unwrap();
4116 assert_eq!(path.hops.len(), 2);
4117 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4118 assert_eq!(path.final_value_msat(), 15_000);
4121 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4122 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4123 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4124 short_channel_id: 333,
4127 cltv_expiry_delta: 0,
4128 htlc_minimum_msat: 0,
4129 htlc_maximum_msat: 10_000,
4131 fee_proportional_millionths: 0,
4132 excess_data: Vec::new()
4136 // Attempt to route more than available results in a failure.
4137 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4138 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4139 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4140 } else { panic!(); }
4144 // Now, attempt to route an exact amount we have should be fine.
4145 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4146 assert_eq!(route.paths.len(), 1);
4147 let path = route.paths.last().unwrap();
4148 assert_eq!(path.hops.len(), 2);
4149 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4150 assert_eq!(path.final_value_msat(), 10_000);
4155 fn available_liquidity_last_hop_test() {
4156 // Check that available liquidity properly limits the path even when only
4157 // one of the latter hops is limited.
4158 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4159 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4160 let scorer = ln_test_utils::TestScorer::new();
4161 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4162 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4163 let config = UserConfig::default();
4164 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4166 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4167 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4168 // Total capacity: 50 sats.
4170 // Disable other potential paths.
4171 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4172 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4173 short_channel_id: 2,
4176 cltv_expiry_delta: 0,
4177 htlc_minimum_msat: 0,
4178 htlc_maximum_msat: 100_000,
4180 fee_proportional_millionths: 0,
4181 excess_data: Vec::new()
4183 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4184 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4185 short_channel_id: 7,
4188 cltv_expiry_delta: 0,
4189 htlc_minimum_msat: 0,
4190 htlc_maximum_msat: 100_000,
4192 fee_proportional_millionths: 0,
4193 excess_data: Vec::new()
4198 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4199 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4200 short_channel_id: 12,
4203 cltv_expiry_delta: 0,
4204 htlc_minimum_msat: 0,
4205 htlc_maximum_msat: 100_000,
4207 fee_proportional_millionths: 0,
4208 excess_data: Vec::new()
4210 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4211 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4212 short_channel_id: 13,
4215 cltv_expiry_delta: 0,
4216 htlc_minimum_msat: 0,
4217 htlc_maximum_msat: 100_000,
4219 fee_proportional_millionths: 0,
4220 excess_data: Vec::new()
4223 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4224 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4225 short_channel_id: 6,
4228 cltv_expiry_delta: 0,
4229 htlc_minimum_msat: 0,
4230 htlc_maximum_msat: 50_000,
4232 fee_proportional_millionths: 0,
4233 excess_data: Vec::new()
4235 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4236 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4237 short_channel_id: 11,
4240 cltv_expiry_delta: 0,
4241 htlc_minimum_msat: 0,
4242 htlc_maximum_msat: 100_000,
4244 fee_proportional_millionths: 0,
4245 excess_data: Vec::new()
4248 // Attempt to route more than available results in a failure.
4249 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4250 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4251 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4252 } else { panic!(); }
4256 // Now, attempt to route 49 sats (just a bit below the capacity).
4257 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4258 assert_eq!(route.paths.len(), 1);
4259 let mut total_amount_paid_msat = 0;
4260 for path in &route.paths {
4261 assert_eq!(path.hops.len(), 4);
4262 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4263 total_amount_paid_msat += path.final_value_msat();
4265 assert_eq!(total_amount_paid_msat, 49_000);
4269 // Attempt to route an exact amount is also fine
4270 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4271 assert_eq!(route.paths.len(), 1);
4272 let mut total_amount_paid_msat = 0;
4273 for path in &route.paths {
4274 assert_eq!(path.hops.len(), 4);
4275 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4276 total_amount_paid_msat += path.final_value_msat();
4278 assert_eq!(total_amount_paid_msat, 50_000);
4283 fn ignore_fee_first_hop_test() {
4284 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4285 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4286 let scorer = ln_test_utils::TestScorer::new();
4287 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4288 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4289 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4291 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4292 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4293 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4294 short_channel_id: 1,
4297 cltv_expiry_delta: 0,
4298 htlc_minimum_msat: 0,
4299 htlc_maximum_msat: 100_000,
4300 fee_base_msat: 1_000_000,
4301 fee_proportional_millionths: 0,
4302 excess_data: Vec::new()
4304 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4305 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4306 short_channel_id: 3,
4309 cltv_expiry_delta: 0,
4310 htlc_minimum_msat: 0,
4311 htlc_maximum_msat: 50_000,
4313 fee_proportional_millionths: 0,
4314 excess_data: Vec::new()
4318 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4319 assert_eq!(route.paths.len(), 1);
4320 let mut total_amount_paid_msat = 0;
4321 for path in &route.paths {
4322 assert_eq!(path.hops.len(), 2);
4323 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4324 total_amount_paid_msat += path.final_value_msat();
4326 assert_eq!(total_amount_paid_msat, 50_000);
4331 fn simple_mpp_route_test() {
4332 let (secp_ctx, _, _, _, _) = build_graph();
4333 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4334 let config = UserConfig::default();
4335 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4336 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4337 do_simple_mpp_route_test(clear_payment_params);
4339 // MPP to a 1-hop blinded path for nodes[2]
4340 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
4341 let blinded_path = BlindedPath {
4342 introduction_node_id: nodes[2],
4343 blinding_point: ln_test_utils::pubkey(42),
4344 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4346 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4348 fee_proportional_millionths: 0,
4349 htlc_minimum_msat: 0,
4350 htlc_maximum_msat: 0,
4351 cltv_expiry_delta: 0,
4352 features: BlindedHopFeatures::empty(),
4354 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4355 .with_bolt12_features(bolt12_features.clone()).unwrap();
4356 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4358 // MPP to 3 2-hop blinded paths
4359 let mut blinded_path_node_0 = blinded_path.clone();
4360 blinded_path_node_0.introduction_node_id = nodes[0];
4361 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4362 let mut node_0_payinfo = blinded_payinfo.clone();
4363 node_0_payinfo.htlc_maximum_msat = 50_000;
4365 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4366 blinded_path_node_7.introduction_node_id = nodes[7];
4367 let mut node_7_payinfo = blinded_payinfo.clone();
4368 node_7_payinfo.htlc_maximum_msat = 60_000;
4370 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4371 blinded_path_node_1.introduction_node_id = nodes[1];
4372 let mut node_1_payinfo = blinded_payinfo.clone();
4373 node_1_payinfo.htlc_maximum_msat = 180_000;
4375 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4377 (node_0_payinfo, blinded_path_node_0),
4378 (node_7_payinfo, blinded_path_node_7),
4379 (node_1_payinfo, blinded_path_node_1)
4381 .with_bolt12_features(bolt12_features).unwrap();
4382 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4386 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4387 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4388 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4389 let scorer = ln_test_utils::TestScorer::new();
4390 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4391 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4393 // We need a route consisting of 3 paths:
4394 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4395 // To achieve this, the amount being transferred should be around
4396 // the total capacity of these 3 paths.
4398 // First, we set limits on these (previously unlimited) channels.
4399 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4401 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4402 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4403 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4404 short_channel_id: 1,
4407 cltv_expiry_delta: 0,
4408 htlc_minimum_msat: 0,
4409 htlc_maximum_msat: 100_000,
4411 fee_proportional_millionths: 0,
4412 excess_data: Vec::new()
4414 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4415 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4416 short_channel_id: 3,
4419 cltv_expiry_delta: 0,
4420 htlc_minimum_msat: 0,
4421 htlc_maximum_msat: 50_000,
4423 fee_proportional_millionths: 0,
4424 excess_data: Vec::new()
4427 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4428 // (total limit 60).
4429 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4430 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4431 short_channel_id: 12,
4434 cltv_expiry_delta: 0,
4435 htlc_minimum_msat: 0,
4436 htlc_maximum_msat: 60_000,
4438 fee_proportional_millionths: 0,
4439 excess_data: Vec::new()
4441 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4442 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4443 short_channel_id: 13,
4446 cltv_expiry_delta: 0,
4447 htlc_minimum_msat: 0,
4448 htlc_maximum_msat: 60_000,
4450 fee_proportional_millionths: 0,
4451 excess_data: Vec::new()
4454 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4455 // (total capacity 180 sats).
4456 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4457 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4458 short_channel_id: 2,
4461 cltv_expiry_delta: 0,
4462 htlc_minimum_msat: 0,
4463 htlc_maximum_msat: 200_000,
4465 fee_proportional_millionths: 0,
4466 excess_data: Vec::new()
4468 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4469 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4470 short_channel_id: 4,
4473 cltv_expiry_delta: 0,
4474 htlc_minimum_msat: 0,
4475 htlc_maximum_msat: 180_000,
4477 fee_proportional_millionths: 0,
4478 excess_data: Vec::new()
4482 // Attempt to route more than available results in a failure.
4483 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4484 &our_id, &payment_params, &network_graph.read_only(), None, 300_000,
4485 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4486 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4487 } else { panic!(); }
4491 // Attempt to route while setting max_path_count to 0 results in a failure.
4492 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4493 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4494 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100,
4495 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4496 assert_eq!(err, "Can't find a route with no paths allowed.");
4497 } else { panic!(); }
4501 // Attempt to route while setting max_path_count to 3 results in a failure.
4502 // This is the case because the minimal_value_contribution_msat would require each path
4503 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4504 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4505 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4506 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000,
4507 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4508 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4509 } else { panic!(); }
4513 // Now, attempt to route 250 sats (just a bit below the capacity).
4514 // Our algorithm should provide us with these 3 paths.
4515 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4516 250_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4517 assert_eq!(route.paths.len(), 3);
4518 let mut total_amount_paid_msat = 0;
4519 for path in &route.paths {
4520 if let Some(bt) = &path.blinded_tail {
4521 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4523 assert_eq!(path.hops.len(), 2);
4524 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4526 total_amount_paid_msat += path.final_value_msat();
4528 assert_eq!(total_amount_paid_msat, 250_000);
4532 // Attempt to route an exact amount is also fine
4533 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4534 290_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4535 assert_eq!(route.paths.len(), 3);
4536 let mut total_amount_paid_msat = 0;
4537 for path in &route.paths {
4538 if payment_params.payee.blinded_route_hints().len() != 0 {
4539 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
4540 if let Some(bt) = &path.blinded_tail {
4541 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4542 if bt.hops.len() > 1 {
4543 assert_eq!(path.hops.last().unwrap().pubkey,
4544 payment_params.payee.blinded_route_hints().iter()
4545 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
4546 .map(|(_, p)| p.introduction_node_id).unwrap());
4548 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4551 assert_eq!(path.hops.len(), 2);
4552 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4554 total_amount_paid_msat += path.final_value_msat();
4556 assert_eq!(total_amount_paid_msat, 290_000);
4561 fn long_mpp_route_test() {
4562 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4563 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4564 let scorer = ln_test_utils::TestScorer::new();
4565 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4566 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4567 let config = UserConfig::default();
4568 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4570 // We need a route consisting of 3 paths:
4571 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4572 // Note that these paths overlap (channels 5, 12, 13).
4573 // We will route 300 sats.
4574 // Each path will have 100 sats capacity, those channels which
4575 // are used twice will have 200 sats capacity.
4577 // Disable other potential paths.
4578 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4579 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4580 short_channel_id: 2,
4583 cltv_expiry_delta: 0,
4584 htlc_minimum_msat: 0,
4585 htlc_maximum_msat: 100_000,
4587 fee_proportional_millionths: 0,
4588 excess_data: Vec::new()
4590 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4591 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4592 short_channel_id: 7,
4595 cltv_expiry_delta: 0,
4596 htlc_minimum_msat: 0,
4597 htlc_maximum_msat: 100_000,
4599 fee_proportional_millionths: 0,
4600 excess_data: Vec::new()
4603 // Path via {node0, node2} is channels {1, 3, 5}.
4604 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4605 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4606 short_channel_id: 1,
4609 cltv_expiry_delta: 0,
4610 htlc_minimum_msat: 0,
4611 htlc_maximum_msat: 100_000,
4613 fee_proportional_millionths: 0,
4614 excess_data: Vec::new()
4616 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4617 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4618 short_channel_id: 3,
4621 cltv_expiry_delta: 0,
4622 htlc_minimum_msat: 0,
4623 htlc_maximum_msat: 100_000,
4625 fee_proportional_millionths: 0,
4626 excess_data: Vec::new()
4629 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4630 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4631 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4632 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4633 short_channel_id: 5,
4636 cltv_expiry_delta: 0,
4637 htlc_minimum_msat: 0,
4638 htlc_maximum_msat: 200_000,
4640 fee_proportional_millionths: 0,
4641 excess_data: Vec::new()
4644 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4645 // Add 100 sats to the capacities of {12, 13}, because these channels
4646 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4647 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4648 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4649 short_channel_id: 12,
4652 cltv_expiry_delta: 0,
4653 htlc_minimum_msat: 0,
4654 htlc_maximum_msat: 200_000,
4656 fee_proportional_millionths: 0,
4657 excess_data: Vec::new()
4659 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4660 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4661 short_channel_id: 13,
4664 cltv_expiry_delta: 0,
4665 htlc_minimum_msat: 0,
4666 htlc_maximum_msat: 200_000,
4668 fee_proportional_millionths: 0,
4669 excess_data: Vec::new()
4672 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4673 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4674 short_channel_id: 6,
4677 cltv_expiry_delta: 0,
4678 htlc_minimum_msat: 0,
4679 htlc_maximum_msat: 100_000,
4681 fee_proportional_millionths: 0,
4682 excess_data: Vec::new()
4684 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4685 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4686 short_channel_id: 11,
4689 cltv_expiry_delta: 0,
4690 htlc_minimum_msat: 0,
4691 htlc_maximum_msat: 100_000,
4693 fee_proportional_millionths: 0,
4694 excess_data: Vec::new()
4697 // Path via {node7, node2} is channels {12, 13, 5}.
4698 // We already limited them to 200 sats (they are used twice for 100 sats).
4699 // Nothing to do here.
4702 // Attempt to route more than available results in a failure.
4703 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4704 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4705 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4706 } else { panic!(); }
4710 // Now, attempt to route 300 sats (exact amount we can route).
4711 // Our algorithm should provide us with these 3 paths, 100 sats each.
4712 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4713 assert_eq!(route.paths.len(), 3);
4715 let mut total_amount_paid_msat = 0;
4716 for path in &route.paths {
4717 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4718 total_amount_paid_msat += path.final_value_msat();
4720 assert_eq!(total_amount_paid_msat, 300_000);
4726 fn mpp_cheaper_route_test() {
4727 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4728 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4729 let scorer = ln_test_utils::TestScorer::new();
4730 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4731 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4732 let config = UserConfig::default();
4733 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4735 // This test checks that if we have two cheaper paths and one more expensive path,
4736 // so that liquidity-wise any 2 of 3 combination is sufficient,
4737 // two cheaper paths will be taken.
4738 // These paths have equal available liquidity.
4740 // We need a combination of 3 paths:
4741 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4742 // Note that these paths overlap (channels 5, 12, 13).
4743 // Each path will have 100 sats capacity, those channels which
4744 // are used twice will have 200 sats capacity.
4746 // Disable other potential paths.
4747 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4748 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4749 short_channel_id: 2,
4752 cltv_expiry_delta: 0,
4753 htlc_minimum_msat: 0,
4754 htlc_maximum_msat: 100_000,
4756 fee_proportional_millionths: 0,
4757 excess_data: Vec::new()
4759 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4760 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4761 short_channel_id: 7,
4764 cltv_expiry_delta: 0,
4765 htlc_minimum_msat: 0,
4766 htlc_maximum_msat: 100_000,
4768 fee_proportional_millionths: 0,
4769 excess_data: Vec::new()
4772 // Path via {node0, node2} is channels {1, 3, 5}.
4773 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4774 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4775 short_channel_id: 1,
4778 cltv_expiry_delta: 0,
4779 htlc_minimum_msat: 0,
4780 htlc_maximum_msat: 100_000,
4782 fee_proportional_millionths: 0,
4783 excess_data: Vec::new()
4785 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4786 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4787 short_channel_id: 3,
4790 cltv_expiry_delta: 0,
4791 htlc_minimum_msat: 0,
4792 htlc_maximum_msat: 100_000,
4794 fee_proportional_millionths: 0,
4795 excess_data: Vec::new()
4798 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4799 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4800 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4801 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4802 short_channel_id: 5,
4805 cltv_expiry_delta: 0,
4806 htlc_minimum_msat: 0,
4807 htlc_maximum_msat: 200_000,
4809 fee_proportional_millionths: 0,
4810 excess_data: Vec::new()
4813 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4814 // Add 100 sats to the capacities of {12, 13}, because these channels
4815 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4816 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4817 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4818 short_channel_id: 12,
4821 cltv_expiry_delta: 0,
4822 htlc_minimum_msat: 0,
4823 htlc_maximum_msat: 200_000,
4825 fee_proportional_millionths: 0,
4826 excess_data: Vec::new()
4828 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4829 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4830 short_channel_id: 13,
4833 cltv_expiry_delta: 0,
4834 htlc_minimum_msat: 0,
4835 htlc_maximum_msat: 200_000,
4837 fee_proportional_millionths: 0,
4838 excess_data: Vec::new()
4841 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4842 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4843 short_channel_id: 6,
4846 cltv_expiry_delta: 0,
4847 htlc_minimum_msat: 0,
4848 htlc_maximum_msat: 100_000,
4849 fee_base_msat: 1_000,
4850 fee_proportional_millionths: 0,
4851 excess_data: Vec::new()
4853 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4854 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4855 short_channel_id: 11,
4858 cltv_expiry_delta: 0,
4859 htlc_minimum_msat: 0,
4860 htlc_maximum_msat: 100_000,
4862 fee_proportional_millionths: 0,
4863 excess_data: Vec::new()
4866 // Path via {node7, node2} is channels {12, 13, 5}.
4867 // We already limited them to 200 sats (they are used twice for 100 sats).
4868 // Nothing to do here.
4871 // Now, attempt to route 180 sats.
4872 // Our algorithm should provide us with these 2 paths.
4873 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4874 assert_eq!(route.paths.len(), 2);
4876 let mut total_value_transferred_msat = 0;
4877 let mut total_paid_msat = 0;
4878 for path in &route.paths {
4879 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4880 total_value_transferred_msat += path.final_value_msat();
4881 for hop in &path.hops {
4882 total_paid_msat += hop.fee_msat;
4885 // If we paid fee, this would be higher.
4886 assert_eq!(total_value_transferred_msat, 180_000);
4887 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4888 assert_eq!(total_fees_paid, 0);
4893 fn fees_on_mpp_route_test() {
4894 // This test makes sure that MPP algorithm properly takes into account
4895 // fees charged on the channels, by making the fees impactful:
4896 // if the fee is not properly accounted for, the behavior is different.
4897 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4898 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4899 let scorer = ln_test_utils::TestScorer::new();
4900 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4901 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4902 let config = UserConfig::default();
4903 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4905 // We need a route consisting of 2 paths:
4906 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4907 // We will route 200 sats, Each path will have 100 sats capacity.
4909 // This test is not particularly stable: e.g.,
4910 // there's a way to route via {node0, node2, node4}.
4911 // It works while pathfinding is deterministic, but can be broken otherwise.
4912 // It's fine to ignore this concern for now.
4914 // Disable other potential paths.
4915 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4916 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4917 short_channel_id: 2,
4920 cltv_expiry_delta: 0,
4921 htlc_minimum_msat: 0,
4922 htlc_maximum_msat: 100_000,
4924 fee_proportional_millionths: 0,
4925 excess_data: Vec::new()
4928 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4929 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4930 short_channel_id: 7,
4933 cltv_expiry_delta: 0,
4934 htlc_minimum_msat: 0,
4935 htlc_maximum_msat: 100_000,
4937 fee_proportional_millionths: 0,
4938 excess_data: Vec::new()
4941 // Path via {node0, node2} is channels {1, 3, 5}.
4942 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4943 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4944 short_channel_id: 1,
4947 cltv_expiry_delta: 0,
4948 htlc_minimum_msat: 0,
4949 htlc_maximum_msat: 100_000,
4951 fee_proportional_millionths: 0,
4952 excess_data: Vec::new()
4954 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4955 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4956 short_channel_id: 3,
4959 cltv_expiry_delta: 0,
4960 htlc_minimum_msat: 0,
4961 htlc_maximum_msat: 100_000,
4963 fee_proportional_millionths: 0,
4964 excess_data: Vec::new()
4967 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4968 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4969 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4970 short_channel_id: 5,
4973 cltv_expiry_delta: 0,
4974 htlc_minimum_msat: 0,
4975 htlc_maximum_msat: 100_000,
4977 fee_proportional_millionths: 0,
4978 excess_data: Vec::new()
4981 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4982 // All channels should be 100 sats capacity. But for the fee experiment,
4983 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4984 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4985 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4986 // so no matter how large are other channels,
4987 // the whole path will be limited by 100 sats with just these 2 conditions:
4988 // - channel 12 capacity is 250 sats
4989 // - fee for channel 6 is 150 sats
4990 // Let's test this by enforcing these 2 conditions and removing other limits.
4991 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4992 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4993 short_channel_id: 12,
4996 cltv_expiry_delta: 0,
4997 htlc_minimum_msat: 0,
4998 htlc_maximum_msat: 250_000,
5000 fee_proportional_millionths: 0,
5001 excess_data: Vec::new()
5003 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5004 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5005 short_channel_id: 13,
5008 cltv_expiry_delta: 0,
5009 htlc_minimum_msat: 0,
5010 htlc_maximum_msat: MAX_VALUE_MSAT,
5012 fee_proportional_millionths: 0,
5013 excess_data: Vec::new()
5016 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5017 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5018 short_channel_id: 6,
5021 cltv_expiry_delta: 0,
5022 htlc_minimum_msat: 0,
5023 htlc_maximum_msat: MAX_VALUE_MSAT,
5024 fee_base_msat: 150_000,
5025 fee_proportional_millionths: 0,
5026 excess_data: Vec::new()
5028 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5029 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5030 short_channel_id: 11,
5033 cltv_expiry_delta: 0,
5034 htlc_minimum_msat: 0,
5035 htlc_maximum_msat: MAX_VALUE_MSAT,
5037 fee_proportional_millionths: 0,
5038 excess_data: Vec::new()
5042 // Attempt to route more than available results in a failure.
5043 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5044 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5045 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5046 } else { panic!(); }
5050 // Now, attempt to route 200 sats (exact amount we can route).
5051 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5052 assert_eq!(route.paths.len(), 2);
5054 let mut total_amount_paid_msat = 0;
5055 for path in &route.paths {
5056 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5057 total_amount_paid_msat += path.final_value_msat();
5059 assert_eq!(total_amount_paid_msat, 200_000);
5060 assert_eq!(route.get_total_fees(), 150_000);
5065 fn mpp_with_last_hops() {
5066 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5067 // via a single last-hop route hint, we'd fail to route if we first collected routes
5068 // totaling close but not quite enough to fund the full payment.
5070 // This was because we considered last-hop hints to have exactly the sought payment amount
5071 // instead of the amount we were trying to collect, needlessly limiting our path searching
5072 // at the very first hop.
5074 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5075 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5076 // to only have the remaining to-collect amount in available liquidity.
5078 // This bug appeared in production in some specific channel configurations.
5079 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5080 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5081 let scorer = ln_test_utils::TestScorer::new();
5082 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5083 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5084 let config = UserConfig::default();
5085 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5086 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5087 src_node_id: nodes[2],
5088 short_channel_id: 42,
5089 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5090 cltv_expiry_delta: 42,
5091 htlc_minimum_msat: None,
5092 htlc_maximum_msat: None,
5093 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5095 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5096 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5097 // would first use the no-fee route and then fail to find a path along the second route as
5098 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5099 // under 5% of our payment amount.
5100 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5101 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5102 short_channel_id: 1,
5105 cltv_expiry_delta: (5 << 4) | 5,
5106 htlc_minimum_msat: 0,
5107 htlc_maximum_msat: 99_000,
5108 fee_base_msat: u32::max_value(),
5109 fee_proportional_millionths: u32::max_value(),
5110 excess_data: Vec::new()
5112 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5113 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5114 short_channel_id: 2,
5117 cltv_expiry_delta: (5 << 4) | 3,
5118 htlc_minimum_msat: 0,
5119 htlc_maximum_msat: 99_000,
5120 fee_base_msat: u32::max_value(),
5121 fee_proportional_millionths: u32::max_value(),
5122 excess_data: Vec::new()
5124 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5125 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5126 short_channel_id: 4,
5129 cltv_expiry_delta: (4 << 4) | 1,
5130 htlc_minimum_msat: 0,
5131 htlc_maximum_msat: MAX_VALUE_MSAT,
5133 fee_proportional_millionths: 0,
5134 excess_data: Vec::new()
5136 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5137 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5138 short_channel_id: 13,
5140 flags: 0|2, // Channel disabled
5141 cltv_expiry_delta: (13 << 4) | 1,
5142 htlc_minimum_msat: 0,
5143 htlc_maximum_msat: MAX_VALUE_MSAT,
5145 fee_proportional_millionths: 2000000,
5146 excess_data: Vec::new()
5149 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5151 let mut route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5152 assert_eq!(route.paths.len(), 2);
5153 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5154 // Paths are manually ordered ordered by SCID, so:
5155 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5156 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5157 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5158 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5159 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5160 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5161 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5162 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5163 assert_eq!(route.get_total_fees(), 1);
5164 assert_eq!(route.get_total_amount(), 100_000);
5168 fn drop_lowest_channel_mpp_route_test() {
5169 // This test checks that low-capacity channel is dropped when after
5170 // path finding we realize that we found more capacity than we need.
5171 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5172 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5173 let scorer = ln_test_utils::TestScorer::new();
5174 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5175 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5176 let config = UserConfig::default();
5177 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5178 .with_max_channel_saturation_power_of_half(0);
5180 // We need a route consisting of 3 paths:
5181 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5183 // The first and the second paths should be sufficient, but the third should be
5184 // cheaper, so that we select it but drop later.
5186 // First, we set limits on these (previously unlimited) channels.
5187 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5189 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5190 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5191 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5192 short_channel_id: 1,
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()
5202 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5203 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5204 short_channel_id: 3,
5207 cltv_expiry_delta: 0,
5208 htlc_minimum_msat: 0,
5209 htlc_maximum_msat: 50_000,
5211 fee_proportional_millionths: 0,
5212 excess_data: Vec::new()
5215 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5216 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5217 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5218 short_channel_id: 12,
5221 cltv_expiry_delta: 0,
5222 htlc_minimum_msat: 0,
5223 htlc_maximum_msat: 60_000,
5225 fee_proportional_millionths: 0,
5226 excess_data: Vec::new()
5228 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5229 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5230 short_channel_id: 13,
5233 cltv_expiry_delta: 0,
5234 htlc_minimum_msat: 0,
5235 htlc_maximum_msat: 60_000,
5237 fee_proportional_millionths: 0,
5238 excess_data: Vec::new()
5241 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5242 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5243 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5244 short_channel_id: 2,
5247 cltv_expiry_delta: 0,
5248 htlc_minimum_msat: 0,
5249 htlc_maximum_msat: 20_000,
5251 fee_proportional_millionths: 0,
5252 excess_data: Vec::new()
5254 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5255 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5256 short_channel_id: 4,
5259 cltv_expiry_delta: 0,
5260 htlc_minimum_msat: 0,
5261 htlc_maximum_msat: 20_000,
5263 fee_proportional_millionths: 0,
5264 excess_data: Vec::new()
5268 // Attempt to route more than available results in a failure.
5269 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5270 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5271 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5272 } else { panic!(); }
5276 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5277 // Our algorithm should provide us with these 3 paths.
5278 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5279 assert_eq!(route.paths.len(), 3);
5280 let mut total_amount_paid_msat = 0;
5281 for path in &route.paths {
5282 assert_eq!(path.hops.len(), 2);
5283 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5284 total_amount_paid_msat += path.final_value_msat();
5286 assert_eq!(total_amount_paid_msat, 125_000);
5290 // Attempt to route without the last small cheap channel
5291 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5292 assert_eq!(route.paths.len(), 2);
5293 let mut total_amount_paid_msat = 0;
5294 for path in &route.paths {
5295 assert_eq!(path.hops.len(), 2);
5296 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5297 total_amount_paid_msat += path.final_value_msat();
5299 assert_eq!(total_amount_paid_msat, 90_000);
5304 fn min_criteria_consistency() {
5305 // Test that we don't use an inconsistent metric between updating and walking nodes during
5306 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5307 // was updated with a different criterion from the heap sorting, resulting in loops in
5308 // calculated paths. We test for that specific case here.
5310 // We construct a network that looks like this:
5312 // node2 -1(3)2- node3
5316 // node1 -1(5)2- node4 -1(1)2- node6
5322 // We create a loop on the side of our real path - our destination is node 6, with a
5323 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5324 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5325 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5326 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5327 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5328 // "previous hop" being set to node 3, creating a loop in the path.
5329 let secp_ctx = Secp256k1::new();
5330 let logger = Arc::new(ln_test_utils::TestLogger::new());
5331 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5332 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5333 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5334 let scorer = ln_test_utils::TestScorer::new();
5335 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5336 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5337 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5339 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5340 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5341 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5342 short_channel_id: 6,
5345 cltv_expiry_delta: (6 << 4) | 0,
5346 htlc_minimum_msat: 0,
5347 htlc_maximum_msat: MAX_VALUE_MSAT,
5349 fee_proportional_millionths: 0,
5350 excess_data: Vec::new()
5352 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5354 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5355 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5356 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5357 short_channel_id: 5,
5360 cltv_expiry_delta: (5 << 4) | 0,
5361 htlc_minimum_msat: 0,
5362 htlc_maximum_msat: MAX_VALUE_MSAT,
5364 fee_proportional_millionths: 0,
5365 excess_data: Vec::new()
5367 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5369 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5370 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5371 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5372 short_channel_id: 4,
5375 cltv_expiry_delta: (4 << 4) | 0,
5376 htlc_minimum_msat: 0,
5377 htlc_maximum_msat: MAX_VALUE_MSAT,
5379 fee_proportional_millionths: 0,
5380 excess_data: Vec::new()
5382 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5384 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5385 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5386 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5387 short_channel_id: 3,
5390 cltv_expiry_delta: (3 << 4) | 0,
5391 htlc_minimum_msat: 0,
5392 htlc_maximum_msat: MAX_VALUE_MSAT,
5394 fee_proportional_millionths: 0,
5395 excess_data: Vec::new()
5397 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5399 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5400 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5401 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5402 short_channel_id: 2,
5405 cltv_expiry_delta: (2 << 4) | 0,
5406 htlc_minimum_msat: 0,
5407 htlc_maximum_msat: MAX_VALUE_MSAT,
5409 fee_proportional_millionths: 0,
5410 excess_data: Vec::new()
5413 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5414 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5415 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5416 short_channel_id: 1,
5419 cltv_expiry_delta: (1 << 4) | 0,
5420 htlc_minimum_msat: 100,
5421 htlc_maximum_msat: MAX_VALUE_MSAT,
5423 fee_proportional_millionths: 0,
5424 excess_data: Vec::new()
5426 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5429 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5430 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5431 assert_eq!(route.paths.len(), 1);
5432 assert_eq!(route.paths[0].hops.len(), 3);
5434 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5435 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5436 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5437 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5438 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5439 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5441 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5442 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5443 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5444 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5445 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5446 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5448 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5449 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5450 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5451 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5452 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5453 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5459 fn exact_fee_liquidity_limit() {
5460 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5461 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5462 // we calculated fees on a higher value, resulting in us ignoring such paths.
5463 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5464 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5465 let scorer = ln_test_utils::TestScorer::new();
5466 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5467 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5468 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5470 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5472 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5473 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5474 short_channel_id: 2,
5477 cltv_expiry_delta: 0,
5478 htlc_minimum_msat: 0,
5479 htlc_maximum_msat: 85_000,
5481 fee_proportional_millionths: 0,
5482 excess_data: Vec::new()
5485 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5486 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5487 short_channel_id: 12,
5490 cltv_expiry_delta: (4 << 4) | 1,
5491 htlc_minimum_msat: 0,
5492 htlc_maximum_msat: 270_000,
5494 fee_proportional_millionths: 1000000,
5495 excess_data: Vec::new()
5499 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5500 // 200% fee charged channel 13 in the 1-to-2 direction.
5501 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5502 assert_eq!(route.paths.len(), 1);
5503 assert_eq!(route.paths[0].hops.len(), 2);
5505 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5506 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5507 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5508 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5509 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5510 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5512 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5513 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5514 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5515 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5516 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5517 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5522 fn htlc_max_reduction_below_min() {
5523 // Test that if, while walking the graph, we reduce the value being sent to meet an
5524 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5525 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5526 // resulting in us thinking there is no possible path, even if other paths exist.
5527 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5528 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5529 let scorer = ln_test_utils::TestScorer::new();
5530 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5531 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5532 let config = UserConfig::default();
5533 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5535 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5536 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5537 // then try to send 90_000.
5538 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5539 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5540 short_channel_id: 2,
5543 cltv_expiry_delta: 0,
5544 htlc_minimum_msat: 0,
5545 htlc_maximum_msat: 80_000,
5547 fee_proportional_millionths: 0,
5548 excess_data: Vec::new()
5550 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5551 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5552 short_channel_id: 4,
5555 cltv_expiry_delta: (4 << 4) | 1,
5556 htlc_minimum_msat: 90_000,
5557 htlc_maximum_msat: MAX_VALUE_MSAT,
5559 fee_proportional_millionths: 0,
5560 excess_data: Vec::new()
5564 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5565 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5566 // expensive) channels 12-13 path.
5567 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5568 assert_eq!(route.paths.len(), 1);
5569 assert_eq!(route.paths[0].hops.len(), 2);
5571 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5572 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5573 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5574 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5575 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5576 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5578 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5579 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5580 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5581 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5582 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5583 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5588 fn multiple_direct_first_hops() {
5589 // Previously we'd only ever considered one first hop path per counterparty.
5590 // However, as we don't restrict users to one channel per peer, we really need to support
5591 // looking at all first hop paths.
5592 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5593 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5594 // route over multiple channels with the same first hop.
5595 let secp_ctx = Secp256k1::new();
5596 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5597 let logger = Arc::new(ln_test_utils::TestLogger::new());
5598 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5599 let scorer = ln_test_utils::TestScorer::new();
5600 let config = UserConfig::default();
5601 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5602 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5603 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5606 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5607 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5608 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5609 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5610 assert_eq!(route.paths.len(), 1);
5611 assert_eq!(route.paths[0].hops.len(), 1);
5613 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5614 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5615 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5618 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5619 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5620 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5621 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5622 assert_eq!(route.paths.len(), 2);
5623 assert_eq!(route.paths[0].hops.len(), 1);
5624 assert_eq!(route.paths[1].hops.len(), 1);
5626 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5627 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5629 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5630 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5632 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5633 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5637 // If we have a bunch of outbound channels to the same node, where most are not
5638 // sufficient to pay the full payment, but one is, we should default to just using the
5639 // one single channel that has sufficient balance, avoiding MPP.
5641 // If we have several options above the 3xpayment value threshold, we should pick the
5642 // smallest of them, avoiding further fragmenting our available outbound balance to
5644 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5645 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5646 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5647 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5648 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5649 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5650 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5651 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5652 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5653 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5654 assert_eq!(route.paths.len(), 1);
5655 assert_eq!(route.paths[0].hops.len(), 1);
5657 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5658 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5659 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5664 fn prefers_shorter_route_with_higher_fees() {
5665 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5666 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5667 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5669 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5670 let scorer = ln_test_utils::TestScorer::new();
5671 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5672 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5673 let route = get_route(
5674 &our_id, &payment_params, &network_graph.read_only(), None, 100,
5675 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5677 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5679 assert_eq!(route.get_total_fees(), 100);
5680 assert_eq!(route.get_total_amount(), 100);
5681 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5683 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5684 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5685 let scorer = FixedPenaltyScorer::with_penalty(100);
5686 let route = get_route(
5687 &our_id, &payment_params, &network_graph.read_only(), None, 100,
5688 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5690 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5692 assert_eq!(route.get_total_fees(), 300);
5693 assert_eq!(route.get_total_amount(), 100);
5694 assert_eq!(path, vec![2, 4, 7, 10]);
5697 struct BadChannelScorer {
5698 short_channel_id: u64,
5702 impl Writeable for BadChannelScorer {
5703 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5705 impl ScoreLookUp for BadChannelScorer {
5706 type ScoreParams = ();
5707 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5708 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5712 struct BadNodeScorer {
5717 impl Writeable for BadNodeScorer {
5718 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5721 impl ScoreLookUp for BadNodeScorer {
5722 type ScoreParams = ();
5723 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5724 if *target == self.node_id { u64::max_value() } else { 0 }
5729 fn avoids_routing_through_bad_channels_and_nodes() {
5730 let (secp_ctx, network, _, _, logger) = build_graph();
5731 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5732 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5733 let network_graph = network.read_only();
5735 // A path to nodes[6] exists when no penalties are applied to any channel.
5736 let scorer = ln_test_utils::TestScorer::new();
5737 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5738 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5739 let route = get_route(
5740 &our_id, &payment_params, &network_graph, None, 100,
5741 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5743 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5745 assert_eq!(route.get_total_fees(), 100);
5746 assert_eq!(route.get_total_amount(), 100);
5747 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5749 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5750 let scorer = BadChannelScorer { short_channel_id: 6 };
5751 let route = get_route(
5752 &our_id, &payment_params, &network_graph, None, 100,
5753 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5755 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5757 assert_eq!(route.get_total_fees(), 300);
5758 assert_eq!(route.get_total_amount(), 100);
5759 assert_eq!(path, vec![2, 4, 7, 10]);
5761 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5762 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5764 &our_id, &payment_params, &network_graph, None, 100,
5765 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5767 Err(LightningError { err, .. } ) => {
5768 assert_eq!(err, "Failed to find a path to the given destination");
5770 Ok(_) => panic!("Expected error"),
5775 fn total_fees_single_path() {
5777 paths: vec![Path { hops: vec![
5779 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5780 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5781 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5784 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5785 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5786 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5789 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5790 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5791 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5793 ], blinded_tail: None }],
5794 payment_params: None,
5797 assert_eq!(route.get_total_fees(), 250);
5798 assert_eq!(route.get_total_amount(), 225);
5802 fn total_fees_multi_path() {
5804 paths: vec![Path { hops: vec![
5806 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5807 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5808 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5811 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5812 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5813 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5815 ], blinded_tail: None }, Path { hops: vec![
5817 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5818 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5819 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5822 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5823 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5824 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5826 ], blinded_tail: None }],
5827 payment_params: None,
5830 assert_eq!(route.get_total_fees(), 200);
5831 assert_eq!(route.get_total_amount(), 300);
5835 fn total_empty_route_no_panic() {
5836 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5837 // would both panic if the route was completely empty. We test to ensure they return 0
5838 // here, even though its somewhat nonsensical as a route.
5839 let route = Route { paths: Vec::new(), payment_params: None };
5841 assert_eq!(route.get_total_fees(), 0);
5842 assert_eq!(route.get_total_amount(), 0);
5846 fn limits_total_cltv_delta() {
5847 let (secp_ctx, network, _, _, logger) = build_graph();
5848 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5849 let network_graph = network.read_only();
5851 let scorer = ln_test_utils::TestScorer::new();
5853 // Make sure that generally there is at least one route available
5854 let feasible_max_total_cltv_delta = 1008;
5855 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5856 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5857 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5858 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5859 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5860 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5861 assert_ne!(path.len(), 0);
5863 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5864 let fail_max_total_cltv_delta = 23;
5865 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5866 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5867 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5869 Err(LightningError { err, .. } ) => {
5870 assert_eq!(err, "Failed to find a path to the given destination");
5872 Ok(_) => panic!("Expected error"),
5877 fn avoids_recently_failed_paths() {
5878 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5879 // randomly inserting channels into it until we can't find a route anymore.
5880 let (secp_ctx, network, _, _, logger) = build_graph();
5881 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5882 let network_graph = network.read_only();
5884 let scorer = ln_test_utils::TestScorer::new();
5885 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5886 .with_max_path_count(1);
5887 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5888 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5890 // We should be able to find a route initially, and then after we fail a few random
5891 // channels eventually we won't be able to any longer.
5892 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).is_ok());
5894 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5895 for chan in route.paths[0].hops.iter() {
5896 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5898 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5899 % route.paths[0].hops.len();
5900 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
5906 fn limits_path_length() {
5907 let (secp_ctx, network, _, _, logger) = build_line_graph();
5908 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5909 let network_graph = network.read_only();
5911 let scorer = ln_test_utils::TestScorer::new();
5912 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5913 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5915 // First check we can actually create a long route on this graph.
5916 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
5917 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100,
5918 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5919 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5920 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5922 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5923 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
5924 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100,
5925 Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5927 Err(LightningError { err, .. } ) => {
5928 assert_eq!(err, "Failed to find a path to the given destination");
5930 Ok(_) => panic!("Expected error"),
5935 fn adds_and_limits_cltv_offset() {
5936 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5937 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5939 let scorer = ln_test_utils::TestScorer::new();
5941 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5942 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5943 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5944 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5945 assert_eq!(route.paths.len(), 1);
5947 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5949 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5950 let mut route_default = route.clone();
5951 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5952 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5953 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5954 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5955 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5957 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5958 let mut route_limited = route.clone();
5959 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5960 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5961 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5962 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5963 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5967 fn adds_plausible_cltv_offset() {
5968 let (secp_ctx, network, _, _, logger) = build_graph();
5969 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5970 let network_graph = network.read_only();
5971 let network_nodes = network_graph.nodes();
5972 let network_channels = network_graph.channels();
5973 let scorer = ln_test_utils::TestScorer::new();
5974 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5975 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5976 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5978 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100,
5979 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5980 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5982 let mut path_plausibility = vec![];
5984 for p in route.paths {
5985 // 1. Select random observation point
5986 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5987 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5989 prng.process_in_place(&mut random_bytes);
5990 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
5991 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
5993 // 2. Calculate what CLTV expiry delta we would observe there
5994 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5996 // 3. Starting from the observation point, find candidate paths
5997 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5998 candidates.push_back((observation_point, vec![]));
6000 let mut found_plausible_candidate = false;
6002 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6003 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6004 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6005 found_plausible_candidate = true;
6006 break 'candidate_loop;
6010 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6011 for channel_id in &cur_node.channels {
6012 if let Some(channel_info) = network_channels.get(&channel_id) {
6013 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6014 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6015 if cur_path_cltv_deltas.iter().sum::<u32>()
6016 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6017 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6018 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6019 candidates.push_back((*next_id, new_path_cltv_deltas));
6027 path_plausibility.push(found_plausible_candidate);
6029 assert!(path_plausibility.iter().all(|x| *x));
6033 fn builds_correct_path_from_hops() {
6034 let (secp_ctx, network, _, _, logger) = build_graph();
6035 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6036 let network_graph = network.read_only();
6038 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6039 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6041 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6042 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6043 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
6044 &network_graph, 100, Arc::clone(&logger), &random_seed_bytes).unwrap();
6045 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6046 assert_eq!(hops.len(), route.paths[0].hops.len());
6047 for (idx, hop_pubkey) in hops.iter().enumerate() {
6048 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6053 fn avoids_saturating_channels() {
6054 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6055 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6056 let decay_params = ProbabilisticScoringDecayParameters::default();
6057 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6059 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6060 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6061 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6062 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6063 short_channel_id: 4,
6066 cltv_expiry_delta: (4 << 4) | 1,
6067 htlc_minimum_msat: 0,
6068 htlc_maximum_msat: 250_000_000,
6070 fee_proportional_millionths: 0,
6071 excess_data: Vec::new()
6073 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6074 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6075 short_channel_id: 13,
6078 cltv_expiry_delta: (13 << 4) | 1,
6079 htlc_minimum_msat: 0,
6080 htlc_maximum_msat: 250_000_000,
6082 fee_proportional_millionths: 0,
6083 excess_data: Vec::new()
6086 let config = UserConfig::default();
6087 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6088 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6089 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6090 // 100,000 sats is less than the available liquidity on each channel, set above.
6091 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000_000, Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6092 assert_eq!(route.paths.len(), 2);
6093 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6094 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6097 #[cfg(not(feature = "no-std"))]
6098 pub(super) fn random_init_seed() -> u64 {
6099 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6100 use core::hash::{BuildHasher, Hasher};
6101 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6102 println!("Using seed of {}", seed);
6107 #[cfg(not(feature = "no-std"))]
6108 fn generate_routes() {
6109 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6111 let logger = ln_test_utils::TestLogger::new();
6112 let graph = match super::bench_utils::read_network_graph(&logger) {
6120 let params = ProbabilisticScoringFeeParameters::default();
6121 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6122 let features = super::Bolt11InvoiceFeatures::empty();
6124 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6128 #[cfg(not(feature = "no-std"))]
6129 fn generate_routes_mpp() {
6130 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6132 let logger = ln_test_utils::TestLogger::new();
6133 let graph = match super::bench_utils::read_network_graph(&logger) {
6141 let params = ProbabilisticScoringFeeParameters::default();
6142 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6143 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6145 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6149 #[cfg(not(feature = "no-std"))]
6150 fn generate_large_mpp_routes() {
6151 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6153 let logger = ln_test_utils::TestLogger::new();
6154 let graph = match super::bench_utils::read_network_graph(&logger) {
6162 let params = ProbabilisticScoringFeeParameters::default();
6163 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6164 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6166 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6170 fn honors_manual_penalties() {
6171 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6172 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6174 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6175 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6177 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6178 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6180 // First check set manual penalties are returned by the scorer.
6181 let usage = ChannelUsage {
6183 inflight_htlc_msat: 0,
6184 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6186 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6187 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6188 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
6190 // Then check we can get a normal route
6191 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6192 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6193 assert!(route.is_ok());
6195 // Then check that we can't get a route if we ban an intermediate node.
6196 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6197 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6198 assert!(route.is_err());
6200 // Finally make sure we can route again, when we remove the ban.
6201 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6202 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6203 assert!(route.is_ok());
6207 fn abide_by_route_hint_max_htlc() {
6208 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6209 // params in the final route.
6210 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6211 let netgraph = network_graph.read_only();
6212 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6213 let scorer = ln_test_utils::TestScorer::new();
6214 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6215 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6216 let config = UserConfig::default();
6218 let max_htlc_msat = 50_000;
6219 let route_hint_1 = RouteHint(vec![RouteHintHop {
6220 src_node_id: nodes[2],
6221 short_channel_id: 42,
6224 proportional_millionths: 0,
6226 cltv_expiry_delta: 10,
6227 htlc_minimum_msat: None,
6228 htlc_maximum_msat: Some(max_htlc_msat),
6230 let dest_node_id = ln_test_utils::pubkey(42);
6231 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6232 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6233 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6235 // Make sure we'll error if our route hints don't have enough liquidity according to their
6236 // htlc_maximum_msat.
6237 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6238 &payment_params, &netgraph, None, max_htlc_msat + 1, Arc::clone(&logger), &scorer, &(),
6241 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6242 } else { panic!(); }
6244 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6245 let mut route_hint_2 = route_hint_1.clone();
6246 route_hint_2.0[0].short_channel_id = 43;
6247 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6248 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6249 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6250 let route = get_route(&our_id, &payment_params, &netgraph, None, max_htlc_msat + 1,
6251 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6252 assert_eq!(route.paths.len(), 2);
6253 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6254 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6258 fn direct_channel_to_hints_with_max_htlc() {
6259 // Check that if we have a first hop channel peer that's connected to multiple provided route
6260 // hints, that we properly split the payment between the route hints if needed.
6261 let logger = Arc::new(ln_test_utils::TestLogger::new());
6262 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6263 let scorer = ln_test_utils::TestScorer::new();
6264 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6265 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6266 let config = UserConfig::default();
6268 let our_node_id = ln_test_utils::pubkey(42);
6269 let intermed_node_id = ln_test_utils::pubkey(43);
6270 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6272 let amt_msat = 900_000;
6273 let max_htlc_msat = 500_000;
6274 let route_hint_1 = RouteHint(vec![RouteHintHop {
6275 src_node_id: intermed_node_id,
6276 short_channel_id: 44,
6279 proportional_millionths: 0,
6281 cltv_expiry_delta: 10,
6282 htlc_minimum_msat: None,
6283 htlc_maximum_msat: Some(max_htlc_msat),
6285 src_node_id: intermed_node_id,
6286 short_channel_id: 45,
6289 proportional_millionths: 0,
6291 cltv_expiry_delta: 10,
6292 htlc_minimum_msat: None,
6293 // Check that later route hint max htlcs don't override earlier ones
6294 htlc_maximum_msat: Some(max_htlc_msat - 50),
6296 let mut route_hint_2 = route_hint_1.clone();
6297 route_hint_2.0[0].short_channel_id = 46;
6298 route_hint_2.0[1].short_channel_id = 47;
6299 let dest_node_id = ln_test_utils::pubkey(44);
6300 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6301 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6302 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6304 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6305 Some(&first_hop.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6306 &random_seed_bytes).unwrap();
6307 assert_eq!(route.paths.len(), 2);
6308 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6309 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6310 assert_eq!(route.get_total_amount(), amt_msat);
6312 // Re-run but with two first hop channels connected to the same route hint peers that must be
6314 let first_hops = vec![
6315 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6316 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6318 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6319 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6320 &random_seed_bytes).unwrap();
6321 assert_eq!(route.paths.len(), 2);
6322 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6323 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6324 assert_eq!(route.get_total_amount(), amt_msat);
6326 // Make sure this works for blinded route hints.
6327 let blinded_path = BlindedPath {
6328 introduction_node_id: intermed_node_id,
6329 blinding_point: ln_test_utils::pubkey(42),
6331 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6332 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6335 let blinded_payinfo = BlindedPayInfo {
6337 fee_proportional_millionths: 0,
6338 htlc_minimum_msat: 1,
6339 htlc_maximum_msat: max_htlc_msat,
6340 cltv_expiry_delta: 10,
6341 features: BlindedHopFeatures::empty(),
6343 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6344 let payment_params = PaymentParameters::blinded(vec![
6345 (blinded_payinfo.clone(), blinded_path.clone()),
6346 (blinded_payinfo.clone(), blinded_path.clone())])
6347 .with_bolt12_features(bolt12_features).unwrap();
6348 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6349 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6350 &random_seed_bytes).unwrap();
6351 assert_eq!(route.paths.len(), 2);
6352 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6353 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6354 assert_eq!(route.get_total_amount(), amt_msat);
6358 fn blinded_route_ser() {
6359 let blinded_path_1 = BlindedPath {
6360 introduction_node_id: ln_test_utils::pubkey(42),
6361 blinding_point: ln_test_utils::pubkey(43),
6363 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6364 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6367 let blinded_path_2 = BlindedPath {
6368 introduction_node_id: ln_test_utils::pubkey(46),
6369 blinding_point: ln_test_utils::pubkey(47),
6371 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6372 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6375 // (De)serialize a Route with 1 blinded path out of two total paths.
6376 let mut route = Route { paths: vec![Path {
6377 hops: vec![RouteHop {
6378 pubkey: ln_test_utils::pubkey(50),
6379 node_features: NodeFeatures::empty(),
6380 short_channel_id: 42,
6381 channel_features: ChannelFeatures::empty(),
6383 cltv_expiry_delta: 0,
6385 blinded_tail: Some(BlindedTail {
6386 hops: blinded_path_1.blinded_hops,
6387 blinding_point: blinded_path_1.blinding_point,
6388 excess_final_cltv_expiry_delta: 40,
6389 final_value_msat: 100,
6391 hops: vec![RouteHop {
6392 pubkey: ln_test_utils::pubkey(51),
6393 node_features: NodeFeatures::empty(),
6394 short_channel_id: 43,
6395 channel_features: ChannelFeatures::empty(),
6397 cltv_expiry_delta: 0,
6398 }], blinded_tail: None }],
6399 payment_params: None,
6401 let encoded_route = route.encode();
6402 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6403 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6404 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6406 // (De)serialize a Route with two paths, each containing a blinded tail.
6407 route.paths[1].blinded_tail = Some(BlindedTail {
6408 hops: blinded_path_2.blinded_hops,
6409 blinding_point: blinded_path_2.blinding_point,
6410 excess_final_cltv_expiry_delta: 41,
6411 final_value_msat: 101,
6413 let encoded_route = route.encode();
6414 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6415 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6416 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6420 fn blinded_path_inflight_processing() {
6421 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6422 // account for the blinded tail's final amount_msat.
6423 let mut inflight_htlcs = InFlightHtlcs::new();
6424 let blinded_path = BlindedPath {
6425 introduction_node_id: ln_test_utils::pubkey(43),
6426 blinding_point: ln_test_utils::pubkey(48),
6427 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
6430 hops: vec![RouteHop {
6431 pubkey: ln_test_utils::pubkey(42),
6432 node_features: NodeFeatures::empty(),
6433 short_channel_id: 42,
6434 channel_features: ChannelFeatures::empty(),
6436 cltv_expiry_delta: 0,
6439 pubkey: blinded_path.introduction_node_id,
6440 node_features: NodeFeatures::empty(),
6441 short_channel_id: 43,
6442 channel_features: ChannelFeatures::empty(),
6444 cltv_expiry_delta: 0,
6446 blinded_tail: Some(BlindedTail {
6447 hops: blinded_path.blinded_hops,
6448 blinding_point: blinded_path.blinding_point,
6449 excess_final_cltv_expiry_delta: 0,
6450 final_value_msat: 200,
6453 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
6454 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
6455 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
6459 fn blinded_path_cltv_shadow_offset() {
6460 // Make sure we add a shadow offset when sending to blinded paths.
6461 let blinded_path = BlindedPath {
6462 introduction_node_id: ln_test_utils::pubkey(43),
6463 blinding_point: ln_test_utils::pubkey(44),
6465 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
6466 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
6469 let mut route = Route { paths: vec![Path {
6470 hops: vec![RouteHop {
6471 pubkey: ln_test_utils::pubkey(42),
6472 node_features: NodeFeatures::empty(),
6473 short_channel_id: 42,
6474 channel_features: ChannelFeatures::empty(),
6476 cltv_expiry_delta: 0,
6479 pubkey: blinded_path.introduction_node_id,
6480 node_features: NodeFeatures::empty(),
6481 short_channel_id: 43,
6482 channel_features: ChannelFeatures::empty(),
6484 cltv_expiry_delta: 0,
6487 blinded_tail: Some(BlindedTail {
6488 hops: blinded_path.blinded_hops,
6489 blinding_point: blinded_path.blinding_point,
6490 excess_final_cltv_expiry_delta: 0,
6491 final_value_msat: 200,
6493 }], payment_params: None};
6495 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
6496 let (_, network_graph, _, _, _) = build_line_graph();
6497 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
6498 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
6499 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
6503 fn simple_blinded_route_hints() {
6504 do_simple_blinded_route_hints(1);
6505 do_simple_blinded_route_hints(2);
6506 do_simple_blinded_route_hints(3);
6509 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
6510 // Check that we can generate a route to a blinded path with the expected hops.
6511 let (secp_ctx, network, _, _, logger) = build_graph();
6512 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6513 let network_graph = network.read_only();
6515 let scorer = ln_test_utils::TestScorer::new();
6516 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6517 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6519 let mut blinded_path = BlindedPath {
6520 introduction_node_id: nodes[2],
6521 blinding_point: ln_test_utils::pubkey(42),
6522 blinded_hops: Vec::with_capacity(num_blinded_hops),
6524 for i in 0..num_blinded_hops {
6525 blinded_path.blinded_hops.push(
6526 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
6529 let blinded_payinfo = BlindedPayInfo {
6531 fee_proportional_millionths: 500,
6532 htlc_minimum_msat: 1000,
6533 htlc_maximum_msat: 100_000_000,
6534 cltv_expiry_delta: 15,
6535 features: BlindedHopFeatures::empty(),
6538 let final_amt_msat = 1001;
6539 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
6540 let route = get_route(&our_id, &payment_params, &network_graph, None, final_amt_msat , Arc::clone(&logger),
6541 &scorer, &(), &random_seed_bytes).unwrap();
6542 assert_eq!(route.paths.len(), 1);
6543 assert_eq!(route.paths[0].hops.len(), 2);
6545 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
6546 assert_eq!(tail.hops, blinded_path.blinded_hops);
6547 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
6548 assert_eq!(tail.final_value_msat, 1001);
6550 let final_hop = route.paths[0].hops.last().unwrap();
6551 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
6552 if tail.hops.len() > 1 {
6553 assert_eq!(final_hop.fee_msat,
6554 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
6555 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
6557 assert_eq!(final_hop.fee_msat, 0);
6558 assert_eq!(final_hop.cltv_expiry_delta, 0);
6563 fn blinded_path_routing_errors() {
6564 // Check that we can generate a route to a blinded path with the expected hops.
6565 let (secp_ctx, network, _, _, logger) = build_graph();
6566 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6567 let network_graph = network.read_only();
6569 let scorer = ln_test_utils::TestScorer::new();
6570 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6571 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6573 let mut invalid_blinded_path = BlindedPath {
6574 introduction_node_id: nodes[2],
6575 blinding_point: ln_test_utils::pubkey(42),
6577 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
6580 let blinded_payinfo = BlindedPayInfo {
6582 fee_proportional_millionths: 500,
6583 htlc_minimum_msat: 1000,
6584 htlc_maximum_msat: 100_000_000,
6585 cltv_expiry_delta: 15,
6586 features: BlindedHopFeatures::empty(),
6589 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
6590 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
6591 let payment_params = PaymentParameters::blinded(vec![
6592 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
6593 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
6594 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6595 &scorer, &(), &random_seed_bytes)
6597 Err(LightningError { err, .. }) => {
6598 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
6600 _ => panic!("Expected error")
6603 invalid_blinded_path.introduction_node_id = our_id;
6604 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
6605 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6606 &scorer, &(), &random_seed_bytes)
6608 Err(LightningError { err, .. }) => {
6609 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
6611 _ => panic!("Expected error")
6614 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
6615 invalid_blinded_path.blinded_hops.clear();
6616 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
6617 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6618 &scorer, &(), &random_seed_bytes)
6620 Err(LightningError { err, .. }) => {
6621 assert_eq!(err, "0-hop blinded path provided");
6623 _ => panic!("Expected error")
6628 fn matching_intro_node_paths_provided() {
6629 // Check that if multiple blinded paths with the same intro node are provided in payment
6630 // parameters, we'll return the correct paths in the resulting MPP route.
6631 let (secp_ctx, network, _, _, logger) = build_graph();
6632 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6633 let network_graph = network.read_only();
6635 let scorer = ln_test_utils::TestScorer::new();
6636 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6637 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6638 let config = UserConfig::default();
6640 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6641 let blinded_path_1 = BlindedPath {
6642 introduction_node_id: nodes[2],
6643 blinding_point: ln_test_utils::pubkey(42),
6645 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6646 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6649 let blinded_payinfo_1 = BlindedPayInfo {
6651 fee_proportional_millionths: 0,
6652 htlc_minimum_msat: 0,
6653 htlc_maximum_msat: 30_000,
6654 cltv_expiry_delta: 0,
6655 features: BlindedHopFeatures::empty(),
6658 let mut blinded_path_2 = blinded_path_1.clone();
6659 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
6660 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
6661 blinded_payinfo_2.htlc_maximum_msat = 70_000;
6663 let blinded_hints = vec![
6664 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
6665 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
6667 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
6668 .with_bolt12_features(bolt12_features.clone()).unwrap();
6670 let route = get_route(&our_id, &payment_params, &network_graph, None,
6671 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6672 assert_eq!(route.paths.len(), 2);
6673 let mut total_amount_paid_msat = 0;
6674 for path in route.paths.into_iter() {
6675 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6676 if let Some(bt) = &path.blinded_tail {
6677 assert_eq!(bt.blinding_point,
6678 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
6679 .map(|(_, bp)| bp.blinding_point).unwrap());
6680 } else { panic!(); }
6681 total_amount_paid_msat += path.final_value_msat();
6683 assert_eq!(total_amount_paid_msat, 100_000);
6687 fn direct_to_intro_node() {
6688 // This previously caused a debug panic in the router when asserting
6689 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
6690 // direct channels we failed to account for the fee charged for use of the blinded path.
6693 // node0 -1(1)2 - node1
6694 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
6695 // doesn't account for the blinded path fee.
6697 let secp_ctx = Secp256k1::new();
6698 let logger = Arc::new(ln_test_utils::TestLogger::new());
6699 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6700 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
6701 let scorer = ln_test_utils::TestScorer::new();
6702 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6703 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6705 let amt_msat = 10_000_000;
6706 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
6707 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
6708 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6709 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6710 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6711 short_channel_id: 1,
6714 cltv_expiry_delta: 42,
6715 htlc_minimum_msat: 1_000,
6716 htlc_maximum_msat: 10_000_000,
6718 fee_proportional_millionths: 0,
6719 excess_data: Vec::new()
6721 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6722 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6723 short_channel_id: 1,
6726 cltv_expiry_delta: 42,
6727 htlc_minimum_msat: 1_000,
6728 htlc_maximum_msat: 10_000_000,
6730 fee_proportional_millionths: 0,
6731 excess_data: Vec::new()
6733 let first_hops = vec![
6734 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6736 let blinded_path = BlindedPath {
6737 introduction_node_id: nodes[1],
6738 blinding_point: ln_test_utils::pubkey(42),
6740 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6741 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6744 let blinded_payinfo = BlindedPayInfo {
6745 fee_base_msat: 1000,
6746 fee_proportional_millionths: 0,
6747 htlc_minimum_msat: 1000,
6748 htlc_maximum_msat: MAX_VALUE_MSAT,
6749 cltv_expiry_delta: 0,
6750 features: BlindedHopFeatures::empty(),
6752 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
6754 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
6756 let netgraph = network_graph.read_only();
6757 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &payment_params, &netgraph,
6758 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6759 &random_seed_bytes) {
6760 assert_eq!(err, "Failed to find a path to the given destination");
6761 } else { panic!("Expected error") }
6763 // Sending an exact amount accounting for the blinded path fee works.
6764 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
6765 let route = get_route(&nodes[0], &payment_params, &netgraph,
6766 Some(&first_hops.iter().collect::<Vec<_>>()), amt_minus_blinded_path_fee,
6767 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6768 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
6769 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
6773 fn direct_to_matching_intro_nodes() {
6774 // This previously caused us to enter `unreachable` code in the following situation:
6775 // 1. We add a route candidate for intro_node contributing a high amount
6776 // 2. We add a first_hop<>intro_node route candidate for the same high amount
6777 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
6778 // amount, and update our route candidate for intro_node for the lower amount
6779 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
6780 // lower contribution amount, but fail (this was previously caused by failure to account for
6781 // blinded path fees when adding first_hop<>intro_node candidates)
6782 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
6783 // candidate still thinks its path is contributing the original higher amount. This caused us
6784 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
6786 let secp_ctx = Secp256k1::new();
6787 let logger = Arc::new(ln_test_utils::TestLogger::new());
6788 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6789 let scorer = ln_test_utils::TestScorer::new();
6790 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6791 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6792 let config = UserConfig::default();
6794 // Values are taken from the fuzz input that uncovered this panic.
6795 let amt_msat = 21_7020_5185_1403_2640;
6796 let (_, _, _, nodes) = get_nodes(&secp_ctx);
6797 let first_hops = vec![
6798 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
6799 18446744073709551615)];
6801 let blinded_path = BlindedPath {
6802 introduction_node_id: nodes[1],
6803 blinding_point: ln_test_utils::pubkey(42),
6805 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6806 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6809 let blinded_payinfo = BlindedPayInfo {
6810 fee_base_msat: 5046_2720,
6811 fee_proportional_millionths: 0,
6812 htlc_minimum_msat: 4503_5996_2737_0496,
6813 htlc_maximum_msat: 45_0359_9627_3704_9600,
6814 cltv_expiry_delta: 0,
6815 features: BlindedHopFeatures::empty(),
6817 let mut blinded_hints = vec![
6818 (blinded_payinfo.clone(), blinded_path.clone()),
6819 (blinded_payinfo.clone(), blinded_path.clone()),
6821 blinded_hints[1].0.fee_base_msat = 419_4304;
6822 blinded_hints[1].0.fee_proportional_millionths = 257;
6823 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
6824 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
6825 blinded_hints[1].0.cltv_expiry_delta = 0;
6827 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6828 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
6829 .with_bolt12_features(bolt12_features.clone()).unwrap();
6831 let netgraph = network_graph.read_only();
6832 let route = get_route(&nodes[0], &payment_params, &netgraph,
6833 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat,
6834 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6835 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
6836 assert_eq!(route.get_total_amount(), amt_msat);
6840 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
6841 pub(crate) mod bench_utils {
6845 use bitcoin::hashes::Hash;
6846 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
6848 use crate::chain::transaction::OutPoint;
6849 use crate::routing::scoring::ScoreUpdate;
6850 use crate::sign::{EntropySource, KeysManager};
6851 use crate::ln::ChannelId;
6852 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
6853 use crate::ln::features::Bolt11InvoiceFeatures;
6854 use crate::routing::gossip::NetworkGraph;
6855 use crate::util::config::UserConfig;
6856 use crate::util::ser::ReadableArgs;
6857 use crate::util::test_utils::TestLogger;
6859 /// Tries to open a network graph file, or panics with a URL to fetch it.
6860 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
6861 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
6862 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
6863 .or_else(|_| { // Fall back to guessing based on the binary location
6864 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
6865 let mut path = std::env::current_exe().unwrap();
6866 path.pop(); // lightning-...
6868 path.pop(); // debug
6869 path.pop(); // target
6870 path.push("lightning");
6871 path.push("net_graph-2023-01-18.bin");
6874 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
6875 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
6876 let mut path = std::env::current_exe().unwrap();
6877 path.pop(); // bench...
6879 path.pop(); // debug
6880 path.pop(); // target
6881 path.pop(); // bench
6882 path.push("lightning");
6883 path.push("net_graph-2023-01-18.bin");
6886 .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");
6887 #[cfg(require_route_graph_test)]
6888 return Ok(res.unwrap());
6889 #[cfg(not(require_route_graph_test))]
6893 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
6894 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
6897 pub(crate) fn payer_pubkey() -> PublicKey {
6898 let secp_ctx = Secp256k1::new();
6899 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
6903 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
6905 channel_id: ChannelId::new_zero(),
6906 counterparty: ChannelCounterparty {
6907 features: channelmanager::provided_init_features(&UserConfig::default()),
6909 unspendable_punishment_reserve: 0,
6910 forwarding_info: None,
6911 outbound_htlc_minimum_msat: None,
6912 outbound_htlc_maximum_msat: None,
6914 funding_txo: Some(OutPoint {
6915 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
6918 short_channel_id: Some(1),
6919 inbound_scid_alias: None,
6920 outbound_scid_alias: None,
6921 channel_value_satoshis: 10_000_000_000,
6923 outbound_capacity_msat: 10_000_000_000,
6924 next_outbound_htlc_minimum_msat: 0,
6925 next_outbound_htlc_limit_msat: 10_000_000_000,
6926 inbound_capacity_msat: 0,
6927 unspendable_punishment_reserve: None,
6928 confirmations_required: None,
6929 confirmations: None,
6930 force_close_spend_delay: None,
6932 is_channel_ready: true,
6935 inbound_htlc_minimum_msat: None,
6936 inbound_htlc_maximum_msat: None,
6938 feerate_sat_per_1000_weight: None,
6939 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
6943 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
6944 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
6945 starting_amount: u64, route_count: usize,
6946 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
6947 let payer = payer_pubkey();
6948 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
6949 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6951 let nodes = graph.read_only().nodes().clone();
6952 let mut route_endpoints = Vec::new();
6953 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
6954 // with some routes we picked being un-routable.
6955 for _ in 0..route_count * 3 / 2 {
6957 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6958 let src = PublicKey::from_slice(nodes.unordered_keys()
6959 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6960 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6961 let dst = PublicKey::from_slice(nodes.unordered_keys()
6962 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6963 let params = PaymentParameters::from_node_id(dst, 42)
6964 .with_bolt11_features(features.clone()).unwrap();
6965 let first_hop = first_hop(src);
6966 let amt = starting_amount + seed % 1_000_000;
6968 get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]),
6969 amt, &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
6971 // ...and seed the scorer with success and failure data...
6972 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6973 let mut score_amt = seed % 1_000_000_000;
6975 // Generate fail/success paths for a wider range of potential amounts with
6976 // MPP enabled to give us a chance to apply penalties for more potential
6978 let mpp_features = channelmanager::provided_invoice_features(&UserConfig::default());
6979 let params = PaymentParameters::from_node_id(dst, 42)
6980 .with_bolt11_features(mpp_features).unwrap();
6982 let route_res = get_route(&payer, ¶ms, &graph.read_only(),
6983 Some(&[&first_hop]), score_amt, &TestLogger::new(), scorer,
6984 score_params, &random_seed_bytes);
6985 if let Ok(route) = route_res {
6986 for path in route.paths {
6987 if seed & 0x80 == 0 {
6988 scorer.payment_path_successful(&path);
6990 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
6991 scorer.payment_path_failed(&path, short_channel_id);
6993 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6997 // If we couldn't find a path with a higer amount, reduce and try again.
7001 route_endpoints.push((first_hop, params, amt));
7007 // Because we've changed channel scores, it's possible we'll take different routes to the
7008 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
7009 // requires a too-high CLTV delta.
7010 route_endpoints.retain(|(first_hop, params, amt)| {
7011 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
7012 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
7014 route_endpoints.truncate(route_count);
7015 assert_eq!(route_endpoints.len(), route_count);
7023 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
7024 use crate::sign::{EntropySource, KeysManager};
7025 use crate::ln::channelmanager;
7026 use crate::ln::features::Bolt11InvoiceFeatures;
7027 use crate::routing::gossip::NetworkGraph;
7028 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
7029 use crate::util::config::UserConfig;
7030 use crate::util::logger::{Logger, Record};
7031 use crate::util::test_utils::TestLogger;
7033 use criterion::Criterion;
7035 struct DummyLogger {}
7036 impl Logger for DummyLogger {
7037 fn log(&self, _record: &Record) {}
7040 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7041 let logger = TestLogger::new();
7042 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7043 let scorer = FixedPenaltyScorer::with_penalty(0);
7044 generate_routes(bench, &network_graph, scorer, &(), Bolt11InvoiceFeatures::empty(), 0,
7045 "generate_routes_with_zero_penalty_scorer");
7048 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7049 let logger = TestLogger::new();
7050 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7051 let scorer = FixedPenaltyScorer::with_penalty(0);
7052 generate_routes(bench, &network_graph, scorer, &(),
7053 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7054 "generate_mpp_routes_with_zero_penalty_scorer");
7057 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7058 let logger = TestLogger::new();
7059 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7060 let params = ProbabilisticScoringFeeParameters::default();
7061 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7062 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
7063 "generate_routes_with_probabilistic_scorer");
7066 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7067 let logger = TestLogger::new();
7068 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7069 let params = ProbabilisticScoringFeeParameters::default();
7070 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7071 generate_routes(bench, &network_graph, scorer, ¶ms,
7072 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7073 "generate_mpp_routes_with_probabilistic_scorer");
7076 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7077 let logger = TestLogger::new();
7078 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7079 let params = ProbabilisticScoringFeeParameters::default();
7080 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7081 generate_routes(bench, &network_graph, scorer, ¶ms,
7082 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
7083 "generate_large_mpp_routes_with_probabilistic_scorer");
7086 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
7087 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
7088 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
7089 bench_name: &'static str,
7091 let payer = bench_utils::payer_pubkey();
7092 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7093 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7095 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
7096 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
7098 // ...then benchmark finding paths between the nodes we learned.
7100 bench.bench_function(bench_name, |b| b.iter(|| {
7101 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
7102 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
7103 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());