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::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2662 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2663 use crate::ln::channelmanager;
2664 use crate::offers::invoice::BlindedPayInfo;
2665 use crate::util::config::UserConfig;
2666 use crate::util::test_utils as ln_test_utils;
2667 use crate::util::chacha20::ChaCha20;
2668 use crate::util::ser::{Readable, Writeable};
2670 use crate::util::ser::Writer;
2672 use bitcoin::hashes::Hash;
2673 use bitcoin::network::constants::Network;
2674 use bitcoin::blockdata::constants::genesis_block;
2675 use bitcoin::blockdata::script::Builder;
2676 use bitcoin::blockdata::opcodes;
2677 use bitcoin::blockdata::transaction::TxOut;
2681 use bitcoin::secp256k1::{PublicKey,SecretKey};
2682 use bitcoin::secp256k1::Secp256k1;
2684 use crate::io::Cursor;
2685 use crate::prelude::*;
2686 use crate::sync::Arc;
2688 use core::convert::TryInto;
2690 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2691 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2692 channelmanager::ChannelDetails {
2693 channel_id: [0; 32],
2694 counterparty: channelmanager::ChannelCounterparty {
2697 unspendable_punishment_reserve: 0,
2698 forwarding_info: None,
2699 outbound_htlc_minimum_msat: None,
2700 outbound_htlc_maximum_msat: None,
2702 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2705 outbound_scid_alias: None,
2706 inbound_scid_alias: None,
2707 channel_value_satoshis: 0,
2709 outbound_capacity_msat,
2710 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2711 next_outbound_htlc_minimum_msat: 0,
2712 inbound_capacity_msat: 42,
2713 unspendable_punishment_reserve: None,
2714 confirmations_required: None,
2715 confirmations: None,
2716 force_close_spend_delay: None,
2717 is_outbound: true, is_channel_ready: true,
2718 is_usable: true, is_public: true,
2719 inbound_htlc_minimum_msat: None,
2720 inbound_htlc_maximum_msat: None,
2722 feerate_sat_per_1000_weight: None,
2723 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
2728 fn simple_route_test() {
2729 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2730 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2731 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2732 let scorer = ln_test_utils::TestScorer::new();
2733 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2734 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2736 // Simple route to 2 via 1
2738 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) {
2739 assert_eq!(err, "Cannot send a payment of 0 msat");
2740 } else { panic!(); }
2742 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2743 assert_eq!(route.paths[0].hops.len(), 2);
2745 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2746 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2747 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2748 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2749 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2750 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2752 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2753 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2754 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2755 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2756 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2757 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2761 fn invalid_first_hop_test() {
2762 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2763 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2764 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2765 let scorer = ln_test_utils::TestScorer::new();
2766 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2767 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2769 // Simple route to 2 via 1
2771 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2773 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2774 get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2775 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2776 } else { panic!(); }
2778 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2779 assert_eq!(route.paths[0].hops.len(), 2);
2783 fn htlc_minimum_test() {
2784 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2785 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2786 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2787 let scorer = ln_test_utils::TestScorer::new();
2788 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2789 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2791 // Simple route to 2 via 1
2793 // Disable other paths
2794 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2795 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2796 short_channel_id: 12,
2798 flags: 2, // to disable
2799 cltv_expiry_delta: 0,
2800 htlc_minimum_msat: 0,
2801 htlc_maximum_msat: MAX_VALUE_MSAT,
2803 fee_proportional_millionths: 0,
2804 excess_data: Vec::new()
2806 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2807 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2808 short_channel_id: 3,
2810 flags: 2, // to disable
2811 cltv_expiry_delta: 0,
2812 htlc_minimum_msat: 0,
2813 htlc_maximum_msat: MAX_VALUE_MSAT,
2815 fee_proportional_millionths: 0,
2816 excess_data: Vec::new()
2818 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2819 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2820 short_channel_id: 13,
2822 flags: 2, // to disable
2823 cltv_expiry_delta: 0,
2824 htlc_minimum_msat: 0,
2825 htlc_maximum_msat: MAX_VALUE_MSAT,
2827 fee_proportional_millionths: 0,
2828 excess_data: Vec::new()
2830 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2831 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2832 short_channel_id: 6,
2834 flags: 2, // to disable
2835 cltv_expiry_delta: 0,
2836 htlc_minimum_msat: 0,
2837 htlc_maximum_msat: MAX_VALUE_MSAT,
2839 fee_proportional_millionths: 0,
2840 excess_data: Vec::new()
2842 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2843 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2844 short_channel_id: 7,
2846 flags: 2, // to disable
2847 cltv_expiry_delta: 0,
2848 htlc_minimum_msat: 0,
2849 htlc_maximum_msat: MAX_VALUE_MSAT,
2851 fee_proportional_millionths: 0,
2852 excess_data: Vec::new()
2855 // Check against amount_to_transfer_over_msat.
2856 // Set minimal HTLC of 200_000_000 msat.
2857 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2858 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2859 short_channel_id: 2,
2862 cltv_expiry_delta: 0,
2863 htlc_minimum_msat: 200_000_000,
2864 htlc_maximum_msat: MAX_VALUE_MSAT,
2866 fee_proportional_millionths: 0,
2867 excess_data: Vec::new()
2870 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2872 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2873 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2874 short_channel_id: 4,
2877 cltv_expiry_delta: 0,
2878 htlc_minimum_msat: 0,
2879 htlc_maximum_msat: 199_999_999,
2881 fee_proportional_millionths: 0,
2882 excess_data: Vec::new()
2885 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2886 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) {
2887 assert_eq!(err, "Failed to find a path to the given destination");
2888 } else { panic!(); }
2890 // Lift the restriction on the first hop.
2891 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2892 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2893 short_channel_id: 2,
2896 cltv_expiry_delta: 0,
2897 htlc_minimum_msat: 0,
2898 htlc_maximum_msat: MAX_VALUE_MSAT,
2900 fee_proportional_millionths: 0,
2901 excess_data: Vec::new()
2904 // A payment above the minimum should pass
2905 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 199_999_999, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2906 assert_eq!(route.paths[0].hops.len(), 2);
2910 fn htlc_minimum_overpay_test() {
2911 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2912 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2913 let config = UserConfig::default();
2914 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
2915 let scorer = ln_test_utils::TestScorer::new();
2916 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2917 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2919 // A route to node#2 via two paths.
2920 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2921 // Thus, they can't send 60 without overpaying.
2922 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2923 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2924 short_channel_id: 2,
2927 cltv_expiry_delta: 0,
2928 htlc_minimum_msat: 35_000,
2929 htlc_maximum_msat: 40_000,
2931 fee_proportional_millionths: 0,
2932 excess_data: Vec::new()
2934 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2935 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2936 short_channel_id: 12,
2939 cltv_expiry_delta: 0,
2940 htlc_minimum_msat: 35_000,
2941 htlc_maximum_msat: 40_000,
2943 fee_proportional_millionths: 0,
2944 excess_data: Vec::new()
2948 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2949 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2950 short_channel_id: 13,
2953 cltv_expiry_delta: 0,
2954 htlc_minimum_msat: 0,
2955 htlc_maximum_msat: MAX_VALUE_MSAT,
2957 fee_proportional_millionths: 0,
2958 excess_data: Vec::new()
2960 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2961 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2962 short_channel_id: 4,
2965 cltv_expiry_delta: 0,
2966 htlc_minimum_msat: 0,
2967 htlc_maximum_msat: MAX_VALUE_MSAT,
2969 fee_proportional_millionths: 0,
2970 excess_data: Vec::new()
2973 // Disable other paths
2974 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2975 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2976 short_channel_id: 1,
2978 flags: 2, // to disable
2979 cltv_expiry_delta: 0,
2980 htlc_minimum_msat: 0,
2981 htlc_maximum_msat: MAX_VALUE_MSAT,
2983 fee_proportional_millionths: 0,
2984 excess_data: Vec::new()
2987 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2988 // Overpay fees to hit htlc_minimum_msat.
2989 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
2990 // TODO: this could be better balanced to overpay 10k and not 15k.
2991 assert_eq!(overpaid_fees, 15_000);
2993 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2994 // while taking even more fee to match htlc_minimum_msat.
2995 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2996 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2997 short_channel_id: 12,
3000 cltv_expiry_delta: 0,
3001 htlc_minimum_msat: 65_000,
3002 htlc_maximum_msat: 80_000,
3004 fee_proportional_millionths: 0,
3005 excess_data: Vec::new()
3007 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3008 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3009 short_channel_id: 2,
3012 cltv_expiry_delta: 0,
3013 htlc_minimum_msat: 0,
3014 htlc_maximum_msat: MAX_VALUE_MSAT,
3016 fee_proportional_millionths: 0,
3017 excess_data: Vec::new()
3019 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3020 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3021 short_channel_id: 4,
3024 cltv_expiry_delta: 0,
3025 htlc_minimum_msat: 0,
3026 htlc_maximum_msat: MAX_VALUE_MSAT,
3028 fee_proportional_millionths: 100_000,
3029 excess_data: Vec::new()
3032 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3033 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3034 assert_eq!(route.paths.len(), 1);
3035 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3036 let fees = route.paths[0].hops[0].fee_msat;
3037 assert_eq!(fees, 5_000);
3039 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3040 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3041 // the other channel.
3042 assert_eq!(route.paths.len(), 1);
3043 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3044 let fees = route.paths[0].hops[0].fee_msat;
3045 assert_eq!(fees, 5_000);
3049 fn disable_channels_test() {
3050 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3051 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3052 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3053 let scorer = ln_test_utils::TestScorer::new();
3054 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3055 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3057 // // Disable channels 4 and 12 by flags=2
3058 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3059 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3060 short_channel_id: 4,
3062 flags: 2, // to disable
3063 cltv_expiry_delta: 0,
3064 htlc_minimum_msat: 0,
3065 htlc_maximum_msat: MAX_VALUE_MSAT,
3067 fee_proportional_millionths: 0,
3068 excess_data: Vec::new()
3070 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3071 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3072 short_channel_id: 12,
3074 flags: 2, // to disable
3075 cltv_expiry_delta: 0,
3076 htlc_minimum_msat: 0,
3077 htlc_maximum_msat: MAX_VALUE_MSAT,
3079 fee_proportional_millionths: 0,
3080 excess_data: Vec::new()
3083 // If all the channels require some features we don't understand, route should fail
3084 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) {
3085 assert_eq!(err, "Failed to find a path to the given destination");
3086 } else { panic!(); }
3088 // If we specify a channel to node7, that overrides our local channel view and that gets used
3089 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3090 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();
3091 assert_eq!(route.paths[0].hops.len(), 2);
3093 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3094 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3095 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3096 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3097 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3098 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3100 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3101 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3102 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3103 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3104 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3105 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3109 fn disable_node_test() {
3110 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3111 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3112 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3113 let scorer = ln_test_utils::TestScorer::new();
3114 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3115 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3117 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3118 let mut unknown_features = NodeFeatures::empty();
3119 unknown_features.set_unknown_feature_required();
3120 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3121 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3122 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3124 // If all nodes require some features we don't understand, route should fail
3125 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) {
3126 assert_eq!(err, "Failed to find a path to the given destination");
3127 } else { panic!(); }
3129 // If we specify a channel to node7, that overrides our local channel view and that gets used
3130 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3131 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();
3132 assert_eq!(route.paths[0].hops.len(), 2);
3134 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3135 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3136 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3137 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3138 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3139 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3141 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3142 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3143 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3144 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3145 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3146 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3148 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3149 // naively) assume that the user checked the feature bits on the invoice, which override
3150 // the node_announcement.
3154 fn our_chans_test() {
3155 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3156 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3157 let scorer = ln_test_utils::TestScorer::new();
3158 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3159 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3161 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3162 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3163 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3164 assert_eq!(route.paths[0].hops.len(), 3);
3166 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3167 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3168 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3169 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3170 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3171 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3173 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3174 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3175 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3176 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3177 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3178 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3180 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3181 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3182 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3183 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3184 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3185 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3187 // If we specify a channel to node7, that overrides our local channel view and that gets used
3188 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3189 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3190 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();
3191 assert_eq!(route.paths[0].hops.len(), 2);
3193 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3194 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3195 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3196 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3197 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3198 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3200 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3201 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3202 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3203 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3204 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3205 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3208 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3209 let zero_fees = RoutingFees {
3211 proportional_millionths: 0,
3213 vec![RouteHint(vec![RouteHintHop {
3214 src_node_id: nodes[3],
3215 short_channel_id: 8,
3217 cltv_expiry_delta: (8 << 4) | 1,
3218 htlc_minimum_msat: None,
3219 htlc_maximum_msat: None,
3221 ]), RouteHint(vec![RouteHintHop {
3222 src_node_id: nodes[4],
3223 short_channel_id: 9,
3226 proportional_millionths: 0,
3228 cltv_expiry_delta: (9 << 4) | 1,
3229 htlc_minimum_msat: None,
3230 htlc_maximum_msat: None,
3231 }]), RouteHint(vec![RouteHintHop {
3232 src_node_id: nodes[5],
3233 short_channel_id: 10,
3235 cltv_expiry_delta: (10 << 4) | 1,
3236 htlc_minimum_msat: None,
3237 htlc_maximum_msat: None,
3241 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3242 let zero_fees = RoutingFees {
3244 proportional_millionths: 0,
3246 vec![RouteHint(vec![RouteHintHop {
3247 src_node_id: nodes[2],
3248 short_channel_id: 5,
3251 proportional_millionths: 0,
3253 cltv_expiry_delta: (5 << 4) | 1,
3254 htlc_minimum_msat: None,
3255 htlc_maximum_msat: None,
3257 src_node_id: nodes[3],
3258 short_channel_id: 8,
3260 cltv_expiry_delta: (8 << 4) | 1,
3261 htlc_minimum_msat: None,
3262 htlc_maximum_msat: None,
3264 ]), RouteHint(vec![RouteHintHop {
3265 src_node_id: nodes[4],
3266 short_channel_id: 9,
3269 proportional_millionths: 0,
3271 cltv_expiry_delta: (9 << 4) | 1,
3272 htlc_minimum_msat: None,
3273 htlc_maximum_msat: None,
3274 }]), RouteHint(vec![RouteHintHop {
3275 src_node_id: nodes[5],
3276 short_channel_id: 10,
3278 cltv_expiry_delta: (10 << 4) | 1,
3279 htlc_minimum_msat: None,
3280 htlc_maximum_msat: None,
3285 fn partial_route_hint_test() {
3286 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3287 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3288 let scorer = ln_test_utils::TestScorer::new();
3289 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3290 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3292 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3293 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3294 // RouteHint may be partially used by the algo to build the best path.
3296 // First check that last hop can't have its source as the payee.
3297 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3298 src_node_id: nodes[6],
3299 short_channel_id: 8,
3302 proportional_millionths: 0,
3304 cltv_expiry_delta: (8 << 4) | 1,
3305 htlc_minimum_msat: None,
3306 htlc_maximum_msat: None,
3309 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3310 invalid_last_hops.push(invalid_last_hop);
3312 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(invalid_last_hops).unwrap();
3313 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) {
3314 assert_eq!(err, "Route hint cannot have the payee as the source.");
3315 } else { panic!(); }
3318 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3319 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3320 assert_eq!(route.paths[0].hops.len(), 5);
3322 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3323 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3324 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3325 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3326 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3327 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3329 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3330 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3331 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3332 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3333 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3334 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3336 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3337 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3338 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3339 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3340 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3341 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3343 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3344 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3345 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3346 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3347 // If we have a peer in the node map, we'll use their features here since we don't have
3348 // a way of figuring out their features from the invoice:
3349 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3350 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3352 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3353 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3354 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3355 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3356 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3357 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3360 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3361 let zero_fees = RoutingFees {
3363 proportional_millionths: 0,
3365 vec![RouteHint(vec![RouteHintHop {
3366 src_node_id: nodes[3],
3367 short_channel_id: 8,
3369 cltv_expiry_delta: (8 << 4) | 1,
3370 htlc_minimum_msat: None,
3371 htlc_maximum_msat: None,
3372 }]), RouteHint(vec![
3374 ]), RouteHint(vec![RouteHintHop {
3375 src_node_id: nodes[5],
3376 short_channel_id: 10,
3378 cltv_expiry_delta: (10 << 4) | 1,
3379 htlc_minimum_msat: None,
3380 htlc_maximum_msat: None,
3385 fn ignores_empty_last_hops_test() {
3386 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3387 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3388 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3389 let scorer = ln_test_utils::TestScorer::new();
3390 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3391 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3393 // Test handling of an empty RouteHint passed in Invoice.
3395 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3396 assert_eq!(route.paths[0].hops.len(), 5);
3398 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3399 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3400 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3401 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3402 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3403 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3405 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3406 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3407 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3408 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3409 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3410 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3412 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3413 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3414 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3415 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3416 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3417 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3419 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3420 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3421 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3422 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3423 // If we have a peer in the node map, we'll use their features here since we don't have
3424 // a way of figuring out their features from the invoice:
3425 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3426 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3428 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3429 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3430 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3431 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3432 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3433 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3436 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3438 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3439 let zero_fees = RoutingFees {
3441 proportional_millionths: 0,
3443 vec![RouteHint(vec![RouteHintHop {
3444 src_node_id: hint_hops[0],
3445 short_channel_id: 0xff00,
3448 proportional_millionths: 0,
3450 cltv_expiry_delta: (5 << 4) | 1,
3451 htlc_minimum_msat: None,
3452 htlc_maximum_msat: None,
3454 src_node_id: hint_hops[1],
3455 short_channel_id: 0xff01,
3457 cltv_expiry_delta: (8 << 4) | 1,
3458 htlc_minimum_msat: None,
3459 htlc_maximum_msat: None,
3464 fn multi_hint_last_hops_test() {
3465 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3466 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3467 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3468 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3469 let scorer = ln_test_utils::TestScorer::new();
3470 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3471 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3472 // Test through channels 2, 3, 0xff00, 0xff01.
3473 // Test shows that multiple hop hints are considered.
3475 // Disabling channels 6 & 7 by flags=2
3476 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3477 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3478 short_channel_id: 6,
3480 flags: 2, // to disable
3481 cltv_expiry_delta: 0,
3482 htlc_minimum_msat: 0,
3483 htlc_maximum_msat: MAX_VALUE_MSAT,
3485 fee_proportional_millionths: 0,
3486 excess_data: Vec::new()
3488 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3489 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3490 short_channel_id: 7,
3492 flags: 2, // to disable
3493 cltv_expiry_delta: 0,
3494 htlc_minimum_msat: 0,
3495 htlc_maximum_msat: MAX_VALUE_MSAT,
3497 fee_proportional_millionths: 0,
3498 excess_data: Vec::new()
3501 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3502 assert_eq!(route.paths[0].hops.len(), 4);
3504 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3505 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3506 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3507 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3508 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3509 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3511 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3512 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3513 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3514 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3515 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3516 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3518 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3519 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3520 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3521 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3522 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3523 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3525 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3526 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3527 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3528 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3529 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3530 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3534 fn private_multi_hint_last_hops_test() {
3535 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3536 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3538 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3539 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3541 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3542 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3543 let scorer = ln_test_utils::TestScorer::new();
3544 // Test through channels 2, 3, 0xff00, 0xff01.
3545 // Test shows that multiple hop hints are considered.
3547 // Disabling channels 6 & 7 by flags=2
3548 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3549 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3550 short_channel_id: 6,
3552 flags: 2, // to disable
3553 cltv_expiry_delta: 0,
3554 htlc_minimum_msat: 0,
3555 htlc_maximum_msat: MAX_VALUE_MSAT,
3557 fee_proportional_millionths: 0,
3558 excess_data: Vec::new()
3560 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3561 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3562 short_channel_id: 7,
3564 flags: 2, // to disable
3565 cltv_expiry_delta: 0,
3566 htlc_minimum_msat: 0,
3567 htlc_maximum_msat: MAX_VALUE_MSAT,
3569 fee_proportional_millionths: 0,
3570 excess_data: Vec::new()
3573 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &[42u8; 32]).unwrap();
3574 assert_eq!(route.paths[0].hops.len(), 4);
3576 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3577 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3578 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3579 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3580 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3581 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3583 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3584 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3585 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3586 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3587 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3588 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3590 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3591 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3592 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3593 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3594 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3595 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3597 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3598 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3599 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3600 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3601 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3602 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3605 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3606 let zero_fees = RoutingFees {
3608 proportional_millionths: 0,
3610 vec![RouteHint(vec![RouteHintHop {
3611 src_node_id: nodes[4],
3612 short_channel_id: 11,
3614 cltv_expiry_delta: (11 << 4) | 1,
3615 htlc_minimum_msat: None,
3616 htlc_maximum_msat: None,
3618 src_node_id: nodes[3],
3619 short_channel_id: 8,
3621 cltv_expiry_delta: (8 << 4) | 1,
3622 htlc_minimum_msat: None,
3623 htlc_maximum_msat: None,
3624 }]), RouteHint(vec![RouteHintHop {
3625 src_node_id: nodes[4],
3626 short_channel_id: 9,
3629 proportional_millionths: 0,
3631 cltv_expiry_delta: (9 << 4) | 1,
3632 htlc_minimum_msat: None,
3633 htlc_maximum_msat: None,
3634 }]), RouteHint(vec![RouteHintHop {
3635 src_node_id: nodes[5],
3636 short_channel_id: 10,
3638 cltv_expiry_delta: (10 << 4) | 1,
3639 htlc_minimum_msat: None,
3640 htlc_maximum_msat: None,
3645 fn last_hops_with_public_channel_test() {
3646 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3647 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3648 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
3649 let scorer = ln_test_utils::TestScorer::new();
3650 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3651 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3652 // This test shows that public routes can be present in the invoice
3653 // which would be handled in the same manner.
3655 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3656 assert_eq!(route.paths[0].hops.len(), 5);
3658 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3659 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3660 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3661 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3662 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3663 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3665 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3666 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3667 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3668 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3669 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3670 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3672 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3673 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3674 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3675 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3676 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3677 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3679 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3680 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3681 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3682 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3683 // If we have a peer in the node map, we'll use their features here since we don't have
3684 // a way of figuring out their features from the invoice:
3685 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3686 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3688 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3689 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3690 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3691 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3692 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3693 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3697 fn our_chans_last_hop_connect_test() {
3698 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3699 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3700 let scorer = ln_test_utils::TestScorer::new();
3701 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3702 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3704 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3705 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3706 let mut last_hops = last_hops(&nodes);
3707 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3708 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();
3709 assert_eq!(route.paths[0].hops.len(), 2);
3711 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3712 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3713 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3714 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3715 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3716 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3718 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3719 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3720 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3721 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3722 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3723 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3725 last_hops[0].0[0].fees.base_msat = 1000;
3727 // Revert to via 6 as the fee on 8 goes up
3728 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops).unwrap();
3729 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3730 assert_eq!(route.paths[0].hops.len(), 4);
3732 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3733 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3734 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
3735 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3736 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3737 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3739 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3740 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3741 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3742 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
3743 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3744 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3746 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
3747 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3748 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3749 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3750 // If we have a peer in the node map, we'll use their features here since we don't have
3751 // a way of figuring out their features from the invoice:
3752 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3753 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3755 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3756 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3757 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3758 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3759 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3760 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3762 // ...but still use 8 for larger payments as 6 has a variable feerate
3763 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3764 assert_eq!(route.paths[0].hops.len(), 5);
3766 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3767 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3768 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3769 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3770 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3771 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3773 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3774 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3775 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3776 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3777 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3778 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3780 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3781 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3782 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3783 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3784 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3785 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3787 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3788 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3789 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
3790 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3791 // If we have a peer in the node map, we'll use their features here since we don't have
3792 // a way of figuring out their features from the invoice:
3793 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3794 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3796 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3797 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3798 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
3799 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3800 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3801 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3804 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> {
3805 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3806 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3807 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3809 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3810 let last_hops = RouteHint(vec![RouteHintHop {
3811 src_node_id: middle_node_id,
3812 short_channel_id: 8,
3815 proportional_millionths: last_hop_fee_prop,
3817 cltv_expiry_delta: (8 << 4) | 1,
3818 htlc_minimum_msat: None,
3819 htlc_maximum_msat: last_hop_htlc_max,
3821 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
3822 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3823 let scorer = ln_test_utils::TestScorer::new();
3824 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3825 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3826 let logger = ln_test_utils::TestLogger::new();
3827 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3828 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3829 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, &logger, &scorer, &(), &random_seed_bytes);
3834 fn unannounced_path_test() {
3835 // We should be able to send a payment to a destination without any help of a routing graph
3836 // if we have a channel with a common counterparty that appears in the first and last hop
3838 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3840 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3841 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3842 assert_eq!(route.paths[0].hops.len(), 2);
3844 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
3845 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3846 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
3847 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3848 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
3849 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3851 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
3852 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3853 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
3854 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3855 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3856 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3860 fn overflow_unannounced_path_test_liquidity_underflow() {
3861 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3862 // the last-hop had a fee which overflowed a u64, we'd panic.
3863 // This was due to us adding the first-hop from us unconditionally, causing us to think
3864 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3865 // In this test, we previously hit a subtraction underflow due to having less available
3866 // liquidity at the last hop than 0.
3867 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());
3871 fn overflow_unannounced_path_test_feerate_overflow() {
3872 // This tests for the same case as above, except instead of hitting a subtraction
3873 // underflow, we hit a case where the fee charged at a hop overflowed.
3874 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());
3878 fn available_amount_while_routing_test() {
3879 // Tests whether we choose the correct available channel amount while routing.
3881 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
3882 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3883 let scorer = ln_test_utils::TestScorer::new();
3884 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3885 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3886 let config = UserConfig::default();
3887 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3889 // We will use a simple single-path route from
3890 // our node to node2 via node0: channels {1, 3}.
3892 // First disable all other paths.
3893 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3894 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3895 short_channel_id: 2,
3898 cltv_expiry_delta: 0,
3899 htlc_minimum_msat: 0,
3900 htlc_maximum_msat: 100_000,
3902 fee_proportional_millionths: 0,
3903 excess_data: Vec::new()
3905 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3906 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3907 short_channel_id: 12,
3910 cltv_expiry_delta: 0,
3911 htlc_minimum_msat: 0,
3912 htlc_maximum_msat: 100_000,
3914 fee_proportional_millionths: 0,
3915 excess_data: Vec::new()
3918 // Make the first channel (#1) very permissive,
3919 // and we will be testing all limits on the second channel.
3920 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3921 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3922 short_channel_id: 1,
3925 cltv_expiry_delta: 0,
3926 htlc_minimum_msat: 0,
3927 htlc_maximum_msat: 1_000_000_000,
3929 fee_proportional_millionths: 0,
3930 excess_data: Vec::new()
3933 // First, let's see if routing works if we have absolutely no idea about the available amount.
3934 // In this case, it should be set to 250_000 sats.
3935 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3936 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3937 short_channel_id: 3,
3940 cltv_expiry_delta: 0,
3941 htlc_minimum_msat: 0,
3942 htlc_maximum_msat: 250_000_000,
3944 fee_proportional_millionths: 0,
3945 excess_data: Vec::new()
3949 // Attempt to route more than available results in a failure.
3950 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3951 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3952 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3953 } else { panic!(); }
3957 // Now, attempt to route an exact amount we have should be fine.
3958 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000_000, Arc::clone(&logger), &scorer, &(),&random_seed_bytes).unwrap();
3959 assert_eq!(route.paths.len(), 1);
3960 let path = route.paths.last().unwrap();
3961 assert_eq!(path.hops.len(), 2);
3962 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3963 assert_eq!(path.final_value_msat(), 250_000_000);
3966 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3967 // Disable channel #1 and use another first hop.
3968 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3969 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3970 short_channel_id: 1,
3973 cltv_expiry_delta: 0,
3974 htlc_minimum_msat: 0,
3975 htlc_maximum_msat: 1_000_000_000,
3977 fee_proportional_millionths: 0,
3978 excess_data: Vec::new()
3981 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3982 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3985 // Attempt to route more than available results in a failure.
3986 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3987 &our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3988 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3989 } else { panic!(); }
3993 // Now, attempt to route an exact amount we have should be fine.
3994 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();
3995 assert_eq!(route.paths.len(), 1);
3996 let path = route.paths.last().unwrap();
3997 assert_eq!(path.hops.len(), 2);
3998 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3999 assert_eq!(path.final_value_msat(), 200_000_000);
4002 // Enable channel #1 back.
4003 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4004 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4005 short_channel_id: 1,
4008 cltv_expiry_delta: 0,
4009 htlc_minimum_msat: 0,
4010 htlc_maximum_msat: 1_000_000_000,
4012 fee_proportional_millionths: 0,
4013 excess_data: Vec::new()
4017 // Now let's see if routing works if we know only htlc_maximum_msat.
4018 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4019 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4020 short_channel_id: 3,
4023 cltv_expiry_delta: 0,
4024 htlc_minimum_msat: 0,
4025 htlc_maximum_msat: 15_000,
4027 fee_proportional_millionths: 0,
4028 excess_data: Vec::new()
4032 // Attempt to route more than available results in a failure.
4033 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4034 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4035 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4036 } else { panic!(); }
4040 // Now, attempt to route an exact amount we have should be fine.
4041 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4042 assert_eq!(route.paths.len(), 1);
4043 let path = route.paths.last().unwrap();
4044 assert_eq!(path.hops.len(), 2);
4045 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4046 assert_eq!(path.final_value_msat(), 15_000);
4049 // Now let's see if routing works if we know only capacity from the UTXO.
4051 // We can't change UTXO capacity on the fly, so we'll disable
4052 // the existing channel and add another one with the capacity we need.
4053 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4054 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4055 short_channel_id: 3,
4058 cltv_expiry_delta: 0,
4059 htlc_minimum_msat: 0,
4060 htlc_maximum_msat: MAX_VALUE_MSAT,
4062 fee_proportional_millionths: 0,
4063 excess_data: Vec::new()
4066 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4067 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4068 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4069 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4070 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4072 *chain_monitor.utxo_ret.lock().unwrap() =
4073 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4074 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4076 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4077 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4078 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4079 short_channel_id: 333,
4082 cltv_expiry_delta: (3 << 4) | 1,
4083 htlc_minimum_msat: 0,
4084 htlc_maximum_msat: 15_000,
4086 fee_proportional_millionths: 0,
4087 excess_data: Vec::new()
4089 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4090 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4091 short_channel_id: 333,
4094 cltv_expiry_delta: (3 << 4) | 2,
4095 htlc_minimum_msat: 0,
4096 htlc_maximum_msat: 15_000,
4098 fee_proportional_millionths: 0,
4099 excess_data: Vec::new()
4103 // Attempt to route more than available results in a failure.
4104 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4105 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4106 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4107 } else { panic!(); }
4111 // Now, attempt to route an exact amount we have should be fine.
4112 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4113 assert_eq!(route.paths.len(), 1);
4114 let path = route.paths.last().unwrap();
4115 assert_eq!(path.hops.len(), 2);
4116 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4117 assert_eq!(path.final_value_msat(), 15_000);
4120 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4121 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4122 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4123 short_channel_id: 333,
4126 cltv_expiry_delta: 0,
4127 htlc_minimum_msat: 0,
4128 htlc_maximum_msat: 10_000,
4130 fee_proportional_millionths: 0,
4131 excess_data: Vec::new()
4135 // Attempt to route more than available results in a failure.
4136 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4137 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4138 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4139 } else { panic!(); }
4143 // Now, attempt to route an exact amount we have should be fine.
4144 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4145 assert_eq!(route.paths.len(), 1);
4146 let path = route.paths.last().unwrap();
4147 assert_eq!(path.hops.len(), 2);
4148 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4149 assert_eq!(path.final_value_msat(), 10_000);
4154 fn available_liquidity_last_hop_test() {
4155 // Check that available liquidity properly limits the path even when only
4156 // one of the latter hops is limited.
4157 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4158 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4159 let scorer = ln_test_utils::TestScorer::new();
4160 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4161 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4162 let config = UserConfig::default();
4163 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4165 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4166 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4167 // Total capacity: 50 sats.
4169 // Disable other potential paths.
4170 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4171 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4172 short_channel_id: 2,
4175 cltv_expiry_delta: 0,
4176 htlc_minimum_msat: 0,
4177 htlc_maximum_msat: 100_000,
4179 fee_proportional_millionths: 0,
4180 excess_data: Vec::new()
4182 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4183 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4184 short_channel_id: 7,
4187 cltv_expiry_delta: 0,
4188 htlc_minimum_msat: 0,
4189 htlc_maximum_msat: 100_000,
4191 fee_proportional_millionths: 0,
4192 excess_data: Vec::new()
4197 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4198 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4199 short_channel_id: 12,
4202 cltv_expiry_delta: 0,
4203 htlc_minimum_msat: 0,
4204 htlc_maximum_msat: 100_000,
4206 fee_proportional_millionths: 0,
4207 excess_data: Vec::new()
4209 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4210 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4211 short_channel_id: 13,
4214 cltv_expiry_delta: 0,
4215 htlc_minimum_msat: 0,
4216 htlc_maximum_msat: 100_000,
4218 fee_proportional_millionths: 0,
4219 excess_data: Vec::new()
4222 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4223 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4224 short_channel_id: 6,
4227 cltv_expiry_delta: 0,
4228 htlc_minimum_msat: 0,
4229 htlc_maximum_msat: 50_000,
4231 fee_proportional_millionths: 0,
4232 excess_data: Vec::new()
4234 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4235 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4236 short_channel_id: 11,
4239 cltv_expiry_delta: 0,
4240 htlc_minimum_msat: 0,
4241 htlc_maximum_msat: 100_000,
4243 fee_proportional_millionths: 0,
4244 excess_data: Vec::new()
4247 // Attempt to route more than available results in a failure.
4248 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4249 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4250 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4251 } else { panic!(); }
4255 // Now, attempt to route 49 sats (just a bit below the capacity).
4256 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4257 assert_eq!(route.paths.len(), 1);
4258 let mut total_amount_paid_msat = 0;
4259 for path in &route.paths {
4260 assert_eq!(path.hops.len(), 4);
4261 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4262 total_amount_paid_msat += path.final_value_msat();
4264 assert_eq!(total_amount_paid_msat, 49_000);
4268 // Attempt to route an exact amount is also fine
4269 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4270 assert_eq!(route.paths.len(), 1);
4271 let mut total_amount_paid_msat = 0;
4272 for path in &route.paths {
4273 assert_eq!(path.hops.len(), 4);
4274 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4275 total_amount_paid_msat += path.final_value_msat();
4277 assert_eq!(total_amount_paid_msat, 50_000);
4282 fn ignore_fee_first_hop_test() {
4283 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4284 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4285 let scorer = ln_test_utils::TestScorer::new();
4286 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4287 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4288 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4290 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4291 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4292 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4293 short_channel_id: 1,
4296 cltv_expiry_delta: 0,
4297 htlc_minimum_msat: 0,
4298 htlc_maximum_msat: 100_000,
4299 fee_base_msat: 1_000_000,
4300 fee_proportional_millionths: 0,
4301 excess_data: Vec::new()
4303 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4304 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4305 short_channel_id: 3,
4308 cltv_expiry_delta: 0,
4309 htlc_minimum_msat: 0,
4310 htlc_maximum_msat: 50_000,
4312 fee_proportional_millionths: 0,
4313 excess_data: Vec::new()
4317 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4318 assert_eq!(route.paths.len(), 1);
4319 let mut total_amount_paid_msat = 0;
4320 for path in &route.paths {
4321 assert_eq!(path.hops.len(), 2);
4322 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4323 total_amount_paid_msat += path.final_value_msat();
4325 assert_eq!(total_amount_paid_msat, 50_000);
4330 fn simple_mpp_route_test() {
4331 let (secp_ctx, _, _, _, _) = build_graph();
4332 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4333 let config = UserConfig::default();
4334 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4335 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4336 do_simple_mpp_route_test(clear_payment_params);
4338 // MPP to a 1-hop blinded path for nodes[2]
4339 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
4340 let blinded_path = BlindedPath {
4341 introduction_node_id: nodes[2],
4342 blinding_point: ln_test_utils::pubkey(42),
4343 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4345 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4347 fee_proportional_millionths: 0,
4348 htlc_minimum_msat: 0,
4349 htlc_maximum_msat: 0,
4350 cltv_expiry_delta: 0,
4351 features: BlindedHopFeatures::empty(),
4353 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4354 .with_bolt12_features(bolt12_features.clone()).unwrap();
4355 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4357 // MPP to 3 2-hop blinded paths
4358 let mut blinded_path_node_0 = blinded_path.clone();
4359 blinded_path_node_0.introduction_node_id = nodes[0];
4360 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4361 let mut node_0_payinfo = blinded_payinfo.clone();
4362 node_0_payinfo.htlc_maximum_msat = 50_000;
4364 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4365 blinded_path_node_7.introduction_node_id = nodes[7];
4366 let mut node_7_payinfo = blinded_payinfo.clone();
4367 node_7_payinfo.htlc_maximum_msat = 60_000;
4369 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4370 blinded_path_node_1.introduction_node_id = nodes[1];
4371 let mut node_1_payinfo = blinded_payinfo.clone();
4372 node_1_payinfo.htlc_maximum_msat = 180_000;
4374 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4376 (node_0_payinfo, blinded_path_node_0),
4377 (node_7_payinfo, blinded_path_node_7),
4378 (node_1_payinfo, blinded_path_node_1)
4380 .with_bolt12_features(bolt12_features).unwrap();
4381 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4385 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4386 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4387 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4388 let scorer = ln_test_utils::TestScorer::new();
4389 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4390 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4392 // We need a route consisting of 3 paths:
4393 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4394 // To achieve this, the amount being transferred should be around
4395 // the total capacity of these 3 paths.
4397 // First, we set limits on these (previously unlimited) channels.
4398 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4400 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4401 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4402 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4403 short_channel_id: 1,
4406 cltv_expiry_delta: 0,
4407 htlc_minimum_msat: 0,
4408 htlc_maximum_msat: 100_000,
4410 fee_proportional_millionths: 0,
4411 excess_data: Vec::new()
4413 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4414 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4415 short_channel_id: 3,
4418 cltv_expiry_delta: 0,
4419 htlc_minimum_msat: 0,
4420 htlc_maximum_msat: 50_000,
4422 fee_proportional_millionths: 0,
4423 excess_data: Vec::new()
4426 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4427 // (total limit 60).
4428 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4429 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4430 short_channel_id: 12,
4433 cltv_expiry_delta: 0,
4434 htlc_minimum_msat: 0,
4435 htlc_maximum_msat: 60_000,
4437 fee_proportional_millionths: 0,
4438 excess_data: Vec::new()
4440 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4441 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4442 short_channel_id: 13,
4445 cltv_expiry_delta: 0,
4446 htlc_minimum_msat: 0,
4447 htlc_maximum_msat: 60_000,
4449 fee_proportional_millionths: 0,
4450 excess_data: Vec::new()
4453 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4454 // (total capacity 180 sats).
4455 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4456 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4457 short_channel_id: 2,
4460 cltv_expiry_delta: 0,
4461 htlc_minimum_msat: 0,
4462 htlc_maximum_msat: 200_000,
4464 fee_proportional_millionths: 0,
4465 excess_data: Vec::new()
4467 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4468 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4469 short_channel_id: 4,
4472 cltv_expiry_delta: 0,
4473 htlc_minimum_msat: 0,
4474 htlc_maximum_msat: 180_000,
4476 fee_proportional_millionths: 0,
4477 excess_data: Vec::new()
4481 // Attempt to route more than available results in a failure.
4482 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4483 &our_id, &payment_params, &network_graph.read_only(), None, 300_000,
4484 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4485 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4486 } else { panic!(); }
4490 // Attempt to route while setting max_path_count to 0 results in a failure.
4491 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4492 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4493 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100,
4494 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4495 assert_eq!(err, "Can't find a route with no paths allowed.");
4496 } else { panic!(); }
4500 // Attempt to route while setting max_path_count to 3 results in a failure.
4501 // This is the case because the minimal_value_contribution_msat would require each path
4502 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4503 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4504 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4505 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000,
4506 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4507 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4508 } else { panic!(); }
4512 // Now, attempt to route 250 sats (just a bit below the capacity).
4513 // Our algorithm should provide us with these 3 paths.
4514 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4515 250_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4516 assert_eq!(route.paths.len(), 3);
4517 let mut total_amount_paid_msat = 0;
4518 for path in &route.paths {
4519 if let Some(bt) = &path.blinded_tail {
4520 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4522 assert_eq!(path.hops.len(), 2);
4523 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4525 total_amount_paid_msat += path.final_value_msat();
4527 assert_eq!(total_amount_paid_msat, 250_000);
4531 // Attempt to route an exact amount is also fine
4532 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4533 290_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4534 assert_eq!(route.paths.len(), 3);
4535 let mut total_amount_paid_msat = 0;
4536 for path in &route.paths {
4537 if payment_params.payee.blinded_route_hints().len() != 0 {
4538 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
4539 if let Some(bt) = &path.blinded_tail {
4540 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4541 if bt.hops.len() > 1 {
4542 assert_eq!(path.hops.last().unwrap().pubkey,
4543 payment_params.payee.blinded_route_hints().iter()
4544 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
4545 .map(|(_, p)| p.introduction_node_id).unwrap());
4547 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4550 assert_eq!(path.hops.len(), 2);
4551 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4553 total_amount_paid_msat += path.final_value_msat();
4555 assert_eq!(total_amount_paid_msat, 290_000);
4560 fn long_mpp_route_test() {
4561 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4562 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4563 let scorer = ln_test_utils::TestScorer::new();
4564 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4565 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4566 let config = UserConfig::default();
4567 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4569 // We need a route consisting of 3 paths:
4570 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4571 // Note that these paths overlap (channels 5, 12, 13).
4572 // We will route 300 sats.
4573 // Each path will have 100 sats capacity, those channels which
4574 // are used twice will have 200 sats capacity.
4576 // Disable other potential paths.
4577 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4578 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4579 short_channel_id: 2,
4582 cltv_expiry_delta: 0,
4583 htlc_minimum_msat: 0,
4584 htlc_maximum_msat: 100_000,
4586 fee_proportional_millionths: 0,
4587 excess_data: Vec::new()
4589 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4590 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4591 short_channel_id: 7,
4594 cltv_expiry_delta: 0,
4595 htlc_minimum_msat: 0,
4596 htlc_maximum_msat: 100_000,
4598 fee_proportional_millionths: 0,
4599 excess_data: Vec::new()
4602 // Path via {node0, node2} is channels {1, 3, 5}.
4603 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4604 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4605 short_channel_id: 1,
4608 cltv_expiry_delta: 0,
4609 htlc_minimum_msat: 0,
4610 htlc_maximum_msat: 100_000,
4612 fee_proportional_millionths: 0,
4613 excess_data: Vec::new()
4615 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4616 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4617 short_channel_id: 3,
4620 cltv_expiry_delta: 0,
4621 htlc_minimum_msat: 0,
4622 htlc_maximum_msat: 100_000,
4624 fee_proportional_millionths: 0,
4625 excess_data: Vec::new()
4628 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4629 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4630 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4631 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4632 short_channel_id: 5,
4635 cltv_expiry_delta: 0,
4636 htlc_minimum_msat: 0,
4637 htlc_maximum_msat: 200_000,
4639 fee_proportional_millionths: 0,
4640 excess_data: Vec::new()
4643 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4644 // Add 100 sats to the capacities of {12, 13}, because these channels
4645 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4646 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4647 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4648 short_channel_id: 12,
4651 cltv_expiry_delta: 0,
4652 htlc_minimum_msat: 0,
4653 htlc_maximum_msat: 200_000,
4655 fee_proportional_millionths: 0,
4656 excess_data: Vec::new()
4658 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4659 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4660 short_channel_id: 13,
4663 cltv_expiry_delta: 0,
4664 htlc_minimum_msat: 0,
4665 htlc_maximum_msat: 200_000,
4667 fee_proportional_millionths: 0,
4668 excess_data: Vec::new()
4671 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4672 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4673 short_channel_id: 6,
4676 cltv_expiry_delta: 0,
4677 htlc_minimum_msat: 0,
4678 htlc_maximum_msat: 100_000,
4680 fee_proportional_millionths: 0,
4681 excess_data: Vec::new()
4683 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4684 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4685 short_channel_id: 11,
4688 cltv_expiry_delta: 0,
4689 htlc_minimum_msat: 0,
4690 htlc_maximum_msat: 100_000,
4692 fee_proportional_millionths: 0,
4693 excess_data: Vec::new()
4696 // Path via {node7, node2} is channels {12, 13, 5}.
4697 // We already limited them to 200 sats (they are used twice for 100 sats).
4698 // Nothing to do here.
4701 // Attempt to route more than available results in a failure.
4702 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4703 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4704 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4705 } else { panic!(); }
4709 // Now, attempt to route 300 sats (exact amount we can route).
4710 // Our algorithm should provide us with these 3 paths, 100 sats each.
4711 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4712 assert_eq!(route.paths.len(), 3);
4714 let mut total_amount_paid_msat = 0;
4715 for path in &route.paths {
4716 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4717 total_amount_paid_msat += path.final_value_msat();
4719 assert_eq!(total_amount_paid_msat, 300_000);
4725 fn mpp_cheaper_route_test() {
4726 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4727 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4728 let scorer = ln_test_utils::TestScorer::new();
4729 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4730 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4731 let config = UserConfig::default();
4732 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4734 // This test checks that if we have two cheaper paths and one more expensive path,
4735 // so that liquidity-wise any 2 of 3 combination is sufficient,
4736 // two cheaper paths will be taken.
4737 // These paths have equal available liquidity.
4739 // We need a combination of 3 paths:
4740 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4741 // Note that these paths overlap (channels 5, 12, 13).
4742 // Each path will have 100 sats capacity, those channels which
4743 // are used twice will have 200 sats capacity.
4745 // Disable other potential paths.
4746 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4747 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4748 short_channel_id: 2,
4751 cltv_expiry_delta: 0,
4752 htlc_minimum_msat: 0,
4753 htlc_maximum_msat: 100_000,
4755 fee_proportional_millionths: 0,
4756 excess_data: Vec::new()
4758 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4759 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4760 short_channel_id: 7,
4763 cltv_expiry_delta: 0,
4764 htlc_minimum_msat: 0,
4765 htlc_maximum_msat: 100_000,
4767 fee_proportional_millionths: 0,
4768 excess_data: Vec::new()
4771 // Path via {node0, node2} is channels {1, 3, 5}.
4772 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4773 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4774 short_channel_id: 1,
4777 cltv_expiry_delta: 0,
4778 htlc_minimum_msat: 0,
4779 htlc_maximum_msat: 100_000,
4781 fee_proportional_millionths: 0,
4782 excess_data: Vec::new()
4784 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4785 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4786 short_channel_id: 3,
4789 cltv_expiry_delta: 0,
4790 htlc_minimum_msat: 0,
4791 htlc_maximum_msat: 100_000,
4793 fee_proportional_millionths: 0,
4794 excess_data: Vec::new()
4797 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4798 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4799 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4800 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4801 short_channel_id: 5,
4804 cltv_expiry_delta: 0,
4805 htlc_minimum_msat: 0,
4806 htlc_maximum_msat: 200_000,
4808 fee_proportional_millionths: 0,
4809 excess_data: Vec::new()
4812 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4813 // Add 100 sats to the capacities of {12, 13}, because these channels
4814 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4815 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4816 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4817 short_channel_id: 12,
4820 cltv_expiry_delta: 0,
4821 htlc_minimum_msat: 0,
4822 htlc_maximum_msat: 200_000,
4824 fee_proportional_millionths: 0,
4825 excess_data: Vec::new()
4827 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4828 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4829 short_channel_id: 13,
4832 cltv_expiry_delta: 0,
4833 htlc_minimum_msat: 0,
4834 htlc_maximum_msat: 200_000,
4836 fee_proportional_millionths: 0,
4837 excess_data: Vec::new()
4840 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4841 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4842 short_channel_id: 6,
4845 cltv_expiry_delta: 0,
4846 htlc_minimum_msat: 0,
4847 htlc_maximum_msat: 100_000,
4848 fee_base_msat: 1_000,
4849 fee_proportional_millionths: 0,
4850 excess_data: Vec::new()
4852 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4853 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4854 short_channel_id: 11,
4857 cltv_expiry_delta: 0,
4858 htlc_minimum_msat: 0,
4859 htlc_maximum_msat: 100_000,
4861 fee_proportional_millionths: 0,
4862 excess_data: Vec::new()
4865 // Path via {node7, node2} is channels {12, 13, 5}.
4866 // We already limited them to 200 sats (they are used twice for 100 sats).
4867 // Nothing to do here.
4870 // Now, attempt to route 180 sats.
4871 // Our algorithm should provide us with these 2 paths.
4872 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4873 assert_eq!(route.paths.len(), 2);
4875 let mut total_value_transferred_msat = 0;
4876 let mut total_paid_msat = 0;
4877 for path in &route.paths {
4878 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4879 total_value_transferred_msat += path.final_value_msat();
4880 for hop in &path.hops {
4881 total_paid_msat += hop.fee_msat;
4884 // If we paid fee, this would be higher.
4885 assert_eq!(total_value_transferred_msat, 180_000);
4886 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4887 assert_eq!(total_fees_paid, 0);
4892 fn fees_on_mpp_route_test() {
4893 // This test makes sure that MPP algorithm properly takes into account
4894 // fees charged on the channels, by making the fees impactful:
4895 // if the fee is not properly accounted for, the behavior is different.
4896 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4897 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4898 let scorer = ln_test_utils::TestScorer::new();
4899 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4900 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4901 let config = UserConfig::default();
4902 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4904 // We need a route consisting of 2 paths:
4905 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4906 // We will route 200 sats, Each path will have 100 sats capacity.
4908 // This test is not particularly stable: e.g.,
4909 // there's a way to route via {node0, node2, node4}.
4910 // It works while pathfinding is deterministic, but can be broken otherwise.
4911 // It's fine to ignore this concern for now.
4913 // Disable other potential paths.
4914 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4915 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4916 short_channel_id: 2,
4919 cltv_expiry_delta: 0,
4920 htlc_minimum_msat: 0,
4921 htlc_maximum_msat: 100_000,
4923 fee_proportional_millionths: 0,
4924 excess_data: Vec::new()
4927 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4928 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4929 short_channel_id: 7,
4932 cltv_expiry_delta: 0,
4933 htlc_minimum_msat: 0,
4934 htlc_maximum_msat: 100_000,
4936 fee_proportional_millionths: 0,
4937 excess_data: Vec::new()
4940 // Path via {node0, node2} is channels {1, 3, 5}.
4941 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4942 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4943 short_channel_id: 1,
4946 cltv_expiry_delta: 0,
4947 htlc_minimum_msat: 0,
4948 htlc_maximum_msat: 100_000,
4950 fee_proportional_millionths: 0,
4951 excess_data: Vec::new()
4953 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4954 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4955 short_channel_id: 3,
4958 cltv_expiry_delta: 0,
4959 htlc_minimum_msat: 0,
4960 htlc_maximum_msat: 100_000,
4962 fee_proportional_millionths: 0,
4963 excess_data: Vec::new()
4966 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4967 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4968 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4969 short_channel_id: 5,
4972 cltv_expiry_delta: 0,
4973 htlc_minimum_msat: 0,
4974 htlc_maximum_msat: 100_000,
4976 fee_proportional_millionths: 0,
4977 excess_data: Vec::new()
4980 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4981 // All channels should be 100 sats capacity. But for the fee experiment,
4982 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4983 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4984 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4985 // so no matter how large are other channels,
4986 // the whole path will be limited by 100 sats with just these 2 conditions:
4987 // - channel 12 capacity is 250 sats
4988 // - fee for channel 6 is 150 sats
4989 // Let's test this by enforcing these 2 conditions and removing other limits.
4990 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4991 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4992 short_channel_id: 12,
4995 cltv_expiry_delta: 0,
4996 htlc_minimum_msat: 0,
4997 htlc_maximum_msat: 250_000,
4999 fee_proportional_millionths: 0,
5000 excess_data: Vec::new()
5002 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5003 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5004 short_channel_id: 13,
5007 cltv_expiry_delta: 0,
5008 htlc_minimum_msat: 0,
5009 htlc_maximum_msat: MAX_VALUE_MSAT,
5011 fee_proportional_millionths: 0,
5012 excess_data: Vec::new()
5015 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5016 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5017 short_channel_id: 6,
5020 cltv_expiry_delta: 0,
5021 htlc_minimum_msat: 0,
5022 htlc_maximum_msat: MAX_VALUE_MSAT,
5023 fee_base_msat: 150_000,
5024 fee_proportional_millionths: 0,
5025 excess_data: Vec::new()
5027 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5028 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5029 short_channel_id: 11,
5032 cltv_expiry_delta: 0,
5033 htlc_minimum_msat: 0,
5034 htlc_maximum_msat: MAX_VALUE_MSAT,
5036 fee_proportional_millionths: 0,
5037 excess_data: Vec::new()
5041 // Attempt to route more than available results in a failure.
5042 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5043 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5044 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5045 } else { panic!(); }
5049 // Now, attempt to route 200 sats (exact amount we can route).
5050 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5051 assert_eq!(route.paths.len(), 2);
5053 let mut total_amount_paid_msat = 0;
5054 for path in &route.paths {
5055 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5056 total_amount_paid_msat += path.final_value_msat();
5058 assert_eq!(total_amount_paid_msat, 200_000);
5059 assert_eq!(route.get_total_fees(), 150_000);
5064 fn mpp_with_last_hops() {
5065 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5066 // via a single last-hop route hint, we'd fail to route if we first collected routes
5067 // totaling close but not quite enough to fund the full payment.
5069 // This was because we considered last-hop hints to have exactly the sought payment amount
5070 // instead of the amount we were trying to collect, needlessly limiting our path searching
5071 // at the very first hop.
5073 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5074 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5075 // to only have the remaining to-collect amount in available liquidity.
5077 // This bug appeared in production in some specific channel configurations.
5078 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5079 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5080 let scorer = ln_test_utils::TestScorer::new();
5081 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5082 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5083 let config = UserConfig::default();
5084 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5085 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5086 src_node_id: nodes[2],
5087 short_channel_id: 42,
5088 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5089 cltv_expiry_delta: 42,
5090 htlc_minimum_msat: None,
5091 htlc_maximum_msat: None,
5092 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5094 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5095 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5096 // would first use the no-fee route and then fail to find a path along the second route as
5097 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5098 // under 5% of our payment amount.
5099 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5100 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5101 short_channel_id: 1,
5104 cltv_expiry_delta: (5 << 4) | 5,
5105 htlc_minimum_msat: 0,
5106 htlc_maximum_msat: 99_000,
5107 fee_base_msat: u32::max_value(),
5108 fee_proportional_millionths: u32::max_value(),
5109 excess_data: Vec::new()
5111 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5112 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5113 short_channel_id: 2,
5116 cltv_expiry_delta: (5 << 4) | 3,
5117 htlc_minimum_msat: 0,
5118 htlc_maximum_msat: 99_000,
5119 fee_base_msat: u32::max_value(),
5120 fee_proportional_millionths: u32::max_value(),
5121 excess_data: Vec::new()
5123 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5124 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5125 short_channel_id: 4,
5128 cltv_expiry_delta: (4 << 4) | 1,
5129 htlc_minimum_msat: 0,
5130 htlc_maximum_msat: MAX_VALUE_MSAT,
5132 fee_proportional_millionths: 0,
5133 excess_data: Vec::new()
5135 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5136 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5137 short_channel_id: 13,
5139 flags: 0|2, // Channel disabled
5140 cltv_expiry_delta: (13 << 4) | 1,
5141 htlc_minimum_msat: 0,
5142 htlc_maximum_msat: MAX_VALUE_MSAT,
5144 fee_proportional_millionths: 2000000,
5145 excess_data: Vec::new()
5148 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5150 let mut route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5151 assert_eq!(route.paths.len(), 2);
5152 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5153 // Paths are manually ordered ordered by SCID, so:
5154 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5155 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5156 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5157 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5158 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5159 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5160 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5161 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5162 assert_eq!(route.get_total_fees(), 1);
5163 assert_eq!(route.get_total_amount(), 100_000);
5167 fn drop_lowest_channel_mpp_route_test() {
5168 // This test checks that low-capacity channel is dropped when after
5169 // path finding we realize that we found more capacity than we need.
5170 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5171 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5172 let scorer = ln_test_utils::TestScorer::new();
5173 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5174 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5175 let config = UserConfig::default();
5176 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5177 .with_max_channel_saturation_power_of_half(0);
5179 // We need a route consisting of 3 paths:
5180 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5182 // The first and the second paths should be sufficient, but the third should be
5183 // cheaper, so that we select it but drop later.
5185 // First, we set limits on these (previously unlimited) channels.
5186 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5188 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5189 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5190 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5191 short_channel_id: 1,
5194 cltv_expiry_delta: 0,
5195 htlc_minimum_msat: 0,
5196 htlc_maximum_msat: 100_000,
5198 fee_proportional_millionths: 0,
5199 excess_data: Vec::new()
5201 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5202 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5203 short_channel_id: 3,
5206 cltv_expiry_delta: 0,
5207 htlc_minimum_msat: 0,
5208 htlc_maximum_msat: 50_000,
5210 fee_proportional_millionths: 0,
5211 excess_data: Vec::new()
5214 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5215 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5216 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5217 short_channel_id: 12,
5220 cltv_expiry_delta: 0,
5221 htlc_minimum_msat: 0,
5222 htlc_maximum_msat: 60_000,
5224 fee_proportional_millionths: 0,
5225 excess_data: Vec::new()
5227 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5228 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5229 short_channel_id: 13,
5232 cltv_expiry_delta: 0,
5233 htlc_minimum_msat: 0,
5234 htlc_maximum_msat: 60_000,
5236 fee_proportional_millionths: 0,
5237 excess_data: Vec::new()
5240 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5241 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5242 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5243 short_channel_id: 2,
5246 cltv_expiry_delta: 0,
5247 htlc_minimum_msat: 0,
5248 htlc_maximum_msat: 20_000,
5250 fee_proportional_millionths: 0,
5251 excess_data: Vec::new()
5253 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5254 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5255 short_channel_id: 4,
5258 cltv_expiry_delta: 0,
5259 htlc_minimum_msat: 0,
5260 htlc_maximum_msat: 20_000,
5262 fee_proportional_millionths: 0,
5263 excess_data: Vec::new()
5267 // Attempt to route more than available results in a failure.
5268 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5269 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5270 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5271 } else { panic!(); }
5275 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5276 // Our algorithm should provide us with these 3 paths.
5277 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5278 assert_eq!(route.paths.len(), 3);
5279 let mut total_amount_paid_msat = 0;
5280 for path in &route.paths {
5281 assert_eq!(path.hops.len(), 2);
5282 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5283 total_amount_paid_msat += path.final_value_msat();
5285 assert_eq!(total_amount_paid_msat, 125_000);
5289 // Attempt to route without the last small cheap channel
5290 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5291 assert_eq!(route.paths.len(), 2);
5292 let mut total_amount_paid_msat = 0;
5293 for path in &route.paths {
5294 assert_eq!(path.hops.len(), 2);
5295 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5296 total_amount_paid_msat += path.final_value_msat();
5298 assert_eq!(total_amount_paid_msat, 90_000);
5303 fn min_criteria_consistency() {
5304 // Test that we don't use an inconsistent metric between updating and walking nodes during
5305 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5306 // was updated with a different criterion from the heap sorting, resulting in loops in
5307 // calculated paths. We test for that specific case here.
5309 // We construct a network that looks like this:
5311 // node2 -1(3)2- node3
5315 // node1 -1(5)2- node4 -1(1)2- node6
5321 // We create a loop on the side of our real path - our destination is node 6, with a
5322 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5323 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5324 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5325 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5326 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5327 // "previous hop" being set to node 3, creating a loop in the path.
5328 let secp_ctx = Secp256k1::new();
5329 let logger = Arc::new(ln_test_utils::TestLogger::new());
5330 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5331 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5332 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5333 let scorer = ln_test_utils::TestScorer::new();
5334 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5335 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5336 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5338 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5339 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5340 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5341 short_channel_id: 6,
5344 cltv_expiry_delta: (6 << 4) | 0,
5345 htlc_minimum_msat: 0,
5346 htlc_maximum_msat: MAX_VALUE_MSAT,
5348 fee_proportional_millionths: 0,
5349 excess_data: Vec::new()
5351 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5353 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5354 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5355 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5356 short_channel_id: 5,
5359 cltv_expiry_delta: (5 << 4) | 0,
5360 htlc_minimum_msat: 0,
5361 htlc_maximum_msat: MAX_VALUE_MSAT,
5363 fee_proportional_millionths: 0,
5364 excess_data: Vec::new()
5366 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5368 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5369 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5370 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5371 short_channel_id: 4,
5374 cltv_expiry_delta: (4 << 4) | 0,
5375 htlc_minimum_msat: 0,
5376 htlc_maximum_msat: MAX_VALUE_MSAT,
5378 fee_proportional_millionths: 0,
5379 excess_data: Vec::new()
5381 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5383 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5384 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5385 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5386 short_channel_id: 3,
5389 cltv_expiry_delta: (3 << 4) | 0,
5390 htlc_minimum_msat: 0,
5391 htlc_maximum_msat: MAX_VALUE_MSAT,
5393 fee_proportional_millionths: 0,
5394 excess_data: Vec::new()
5396 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5398 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5399 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5400 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5401 short_channel_id: 2,
5404 cltv_expiry_delta: (2 << 4) | 0,
5405 htlc_minimum_msat: 0,
5406 htlc_maximum_msat: MAX_VALUE_MSAT,
5408 fee_proportional_millionths: 0,
5409 excess_data: Vec::new()
5412 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5413 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5414 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5415 short_channel_id: 1,
5418 cltv_expiry_delta: (1 << 4) | 0,
5419 htlc_minimum_msat: 100,
5420 htlc_maximum_msat: MAX_VALUE_MSAT,
5422 fee_proportional_millionths: 0,
5423 excess_data: Vec::new()
5425 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5428 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5429 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5430 assert_eq!(route.paths.len(), 1);
5431 assert_eq!(route.paths[0].hops.len(), 3);
5433 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5434 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5435 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5436 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5437 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5438 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5440 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5441 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5442 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5443 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5444 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5445 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5447 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5448 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5449 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5450 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5451 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5452 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5458 fn exact_fee_liquidity_limit() {
5459 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5460 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5461 // we calculated fees on a higher value, resulting in us ignoring such paths.
5462 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5463 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5464 let scorer = ln_test_utils::TestScorer::new();
5465 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5466 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5467 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5469 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5471 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5472 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5473 short_channel_id: 2,
5476 cltv_expiry_delta: 0,
5477 htlc_minimum_msat: 0,
5478 htlc_maximum_msat: 85_000,
5480 fee_proportional_millionths: 0,
5481 excess_data: Vec::new()
5484 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5485 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5486 short_channel_id: 12,
5489 cltv_expiry_delta: (4 << 4) | 1,
5490 htlc_minimum_msat: 0,
5491 htlc_maximum_msat: 270_000,
5493 fee_proportional_millionths: 1000000,
5494 excess_data: Vec::new()
5498 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5499 // 200% fee charged channel 13 in the 1-to-2 direction.
5500 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5501 assert_eq!(route.paths.len(), 1);
5502 assert_eq!(route.paths[0].hops.len(), 2);
5504 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5505 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5506 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5507 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5508 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5509 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5511 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5512 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5513 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5514 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5515 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5516 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5521 fn htlc_max_reduction_below_min() {
5522 // Test that if, while walking the graph, we reduce the value being sent to meet an
5523 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5524 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5525 // resulting in us thinking there is no possible path, even if other paths exist.
5526 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5527 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5528 let scorer = ln_test_utils::TestScorer::new();
5529 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5530 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5531 let config = UserConfig::default();
5532 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5534 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5535 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5536 // then try to send 90_000.
5537 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5538 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5539 short_channel_id: 2,
5542 cltv_expiry_delta: 0,
5543 htlc_minimum_msat: 0,
5544 htlc_maximum_msat: 80_000,
5546 fee_proportional_millionths: 0,
5547 excess_data: Vec::new()
5549 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5550 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5551 short_channel_id: 4,
5554 cltv_expiry_delta: (4 << 4) | 1,
5555 htlc_minimum_msat: 90_000,
5556 htlc_maximum_msat: MAX_VALUE_MSAT,
5558 fee_proportional_millionths: 0,
5559 excess_data: Vec::new()
5563 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5564 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5565 // expensive) channels 12-13 path.
5566 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5567 assert_eq!(route.paths.len(), 1);
5568 assert_eq!(route.paths[0].hops.len(), 2);
5570 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5571 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5572 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5573 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5574 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5575 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5577 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5578 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5579 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5580 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5581 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5582 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5587 fn multiple_direct_first_hops() {
5588 // Previously we'd only ever considered one first hop path per counterparty.
5589 // However, as we don't restrict users to one channel per peer, we really need to support
5590 // looking at all first hop paths.
5591 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5592 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5593 // route over multiple channels with the same first hop.
5594 let secp_ctx = Secp256k1::new();
5595 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5596 let logger = Arc::new(ln_test_utils::TestLogger::new());
5597 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5598 let scorer = ln_test_utils::TestScorer::new();
5599 let config = UserConfig::default();
5600 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5601 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5602 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5605 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5606 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5607 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5608 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5609 assert_eq!(route.paths.len(), 1);
5610 assert_eq!(route.paths[0].hops.len(), 1);
5612 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5613 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5614 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5617 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5618 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5619 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5620 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5621 assert_eq!(route.paths.len(), 2);
5622 assert_eq!(route.paths[0].hops.len(), 1);
5623 assert_eq!(route.paths[1].hops.len(), 1);
5625 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5626 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5628 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5629 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5631 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5632 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5636 // If we have a bunch of outbound channels to the same node, where most are not
5637 // sufficient to pay the full payment, but one is, we should default to just using the
5638 // one single channel that has sufficient balance, avoiding MPP.
5640 // If we have several options above the 3xpayment value threshold, we should pick the
5641 // smallest of them, avoiding further fragmenting our available outbound balance to
5643 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5644 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5645 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5646 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5647 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5648 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5649 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5650 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5651 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5652 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5653 assert_eq!(route.paths.len(), 1);
5654 assert_eq!(route.paths[0].hops.len(), 1);
5656 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5657 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5658 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5663 fn prefers_shorter_route_with_higher_fees() {
5664 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5665 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5666 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5668 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5669 let scorer = ln_test_utils::TestScorer::new();
5670 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5671 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5672 let route = get_route(
5673 &our_id, &payment_params, &network_graph.read_only(), None, 100,
5674 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5676 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5678 assert_eq!(route.get_total_fees(), 100);
5679 assert_eq!(route.get_total_amount(), 100);
5680 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5682 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5683 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5684 let scorer = FixedPenaltyScorer::with_penalty(100);
5685 let route = get_route(
5686 &our_id, &payment_params, &network_graph.read_only(), None, 100,
5687 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5689 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5691 assert_eq!(route.get_total_fees(), 300);
5692 assert_eq!(route.get_total_amount(), 100);
5693 assert_eq!(path, vec![2, 4, 7, 10]);
5696 struct BadChannelScorer {
5697 short_channel_id: u64,
5701 impl Writeable for BadChannelScorer {
5702 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5704 impl ScoreLookUp for BadChannelScorer {
5705 type ScoreParams = ();
5706 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5707 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5711 struct BadNodeScorer {
5716 impl Writeable for BadNodeScorer {
5717 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5720 impl ScoreLookUp for BadNodeScorer {
5721 type ScoreParams = ();
5722 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5723 if *target == self.node_id { u64::max_value() } else { 0 }
5728 fn avoids_routing_through_bad_channels_and_nodes() {
5729 let (secp_ctx, network, _, _, logger) = build_graph();
5730 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5731 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5732 let network_graph = network.read_only();
5734 // A path to nodes[6] exists when no penalties are applied to any channel.
5735 let scorer = ln_test_utils::TestScorer::new();
5736 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5737 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5738 let route = get_route(
5739 &our_id, &payment_params, &network_graph, None, 100,
5740 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5742 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5744 assert_eq!(route.get_total_fees(), 100);
5745 assert_eq!(route.get_total_amount(), 100);
5746 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5748 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5749 let scorer = BadChannelScorer { short_channel_id: 6 };
5750 let route = get_route(
5751 &our_id, &payment_params, &network_graph, None, 100,
5752 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5754 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5756 assert_eq!(route.get_total_fees(), 300);
5757 assert_eq!(route.get_total_amount(), 100);
5758 assert_eq!(path, vec![2, 4, 7, 10]);
5760 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5761 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5763 &our_id, &payment_params, &network_graph, None, 100,
5764 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5766 Err(LightningError { err, .. } ) => {
5767 assert_eq!(err, "Failed to find a path to the given destination");
5769 Ok(_) => panic!("Expected error"),
5774 fn total_fees_single_path() {
5776 paths: vec![Path { hops: vec![
5778 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5779 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5780 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5783 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5784 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5785 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5788 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5789 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5790 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5792 ], blinded_tail: None }],
5793 payment_params: None,
5796 assert_eq!(route.get_total_fees(), 250);
5797 assert_eq!(route.get_total_amount(), 225);
5801 fn total_fees_multi_path() {
5803 paths: vec![Path { hops: vec![
5805 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5806 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5807 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5810 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5811 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5812 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5814 ], blinded_tail: None }, Path { hops: vec![
5816 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5817 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5818 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5821 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5822 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5823 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5825 ], blinded_tail: None }],
5826 payment_params: None,
5829 assert_eq!(route.get_total_fees(), 200);
5830 assert_eq!(route.get_total_amount(), 300);
5834 fn total_empty_route_no_panic() {
5835 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5836 // would both panic if the route was completely empty. We test to ensure they return 0
5837 // here, even though its somewhat nonsensical as a route.
5838 let route = Route { paths: Vec::new(), payment_params: None };
5840 assert_eq!(route.get_total_fees(), 0);
5841 assert_eq!(route.get_total_amount(), 0);
5845 fn limits_total_cltv_delta() {
5846 let (secp_ctx, network, _, _, logger) = build_graph();
5847 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5848 let network_graph = network.read_only();
5850 let scorer = ln_test_utils::TestScorer::new();
5852 // Make sure that generally there is at least one route available
5853 let feasible_max_total_cltv_delta = 1008;
5854 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5855 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5856 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5857 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5858 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5859 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5860 assert_ne!(path.len(), 0);
5862 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5863 let fail_max_total_cltv_delta = 23;
5864 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5865 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5866 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5868 Err(LightningError { err, .. } ) => {
5869 assert_eq!(err, "Failed to find a path to the given destination");
5871 Ok(_) => panic!("Expected error"),
5876 fn avoids_recently_failed_paths() {
5877 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5878 // randomly inserting channels into it until we can't find a route anymore.
5879 let (secp_ctx, network, _, _, logger) = build_graph();
5880 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5881 let network_graph = network.read_only();
5883 let scorer = ln_test_utils::TestScorer::new();
5884 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5885 .with_max_path_count(1);
5886 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5887 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5889 // We should be able to find a route initially, and then after we fail a few random
5890 // channels eventually we won't be able to any longer.
5891 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).is_ok());
5893 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5894 for chan in route.paths[0].hops.iter() {
5895 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5897 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5898 % route.paths[0].hops.len();
5899 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
5905 fn limits_path_length() {
5906 let (secp_ctx, network, _, _, logger) = build_line_graph();
5907 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5908 let network_graph = network.read_only();
5910 let scorer = ln_test_utils::TestScorer::new();
5911 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5912 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5914 // First check we can actually create a long route on this graph.
5915 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
5916 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100,
5917 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5918 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5919 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5921 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5922 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
5923 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100,
5924 Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5926 Err(LightningError { err, .. } ) => {
5927 assert_eq!(err, "Failed to find a path to the given destination");
5929 Ok(_) => panic!("Expected error"),
5934 fn adds_and_limits_cltv_offset() {
5935 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5936 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5938 let scorer = ln_test_utils::TestScorer::new();
5940 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5941 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5942 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5943 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5944 assert_eq!(route.paths.len(), 1);
5946 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5948 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5949 let mut route_default = route.clone();
5950 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5951 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5952 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5953 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5954 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5956 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5957 let mut route_limited = route.clone();
5958 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5959 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5960 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5961 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5962 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5966 fn adds_plausible_cltv_offset() {
5967 let (secp_ctx, network, _, _, logger) = build_graph();
5968 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5969 let network_graph = network.read_only();
5970 let network_nodes = network_graph.nodes();
5971 let network_channels = network_graph.channels();
5972 let scorer = ln_test_utils::TestScorer::new();
5973 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5974 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5975 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5977 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100,
5978 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5979 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5981 let mut path_plausibility = vec![];
5983 for p in route.paths {
5984 // 1. Select random observation point
5985 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5986 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5988 prng.process_in_place(&mut random_bytes);
5989 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
5990 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
5992 // 2. Calculate what CLTV expiry delta we would observe there
5993 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5995 // 3. Starting from the observation point, find candidate paths
5996 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5997 candidates.push_back((observation_point, vec![]));
5999 let mut found_plausible_candidate = false;
6001 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6002 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6003 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6004 found_plausible_candidate = true;
6005 break 'candidate_loop;
6009 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6010 for channel_id in &cur_node.channels {
6011 if let Some(channel_info) = network_channels.get(&channel_id) {
6012 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6013 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6014 if cur_path_cltv_deltas.iter().sum::<u32>()
6015 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6016 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6017 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6018 candidates.push_back((*next_id, new_path_cltv_deltas));
6026 path_plausibility.push(found_plausible_candidate);
6028 assert!(path_plausibility.iter().all(|x| *x));
6032 fn builds_correct_path_from_hops() {
6033 let (secp_ctx, network, _, _, logger) = build_graph();
6034 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6035 let network_graph = network.read_only();
6037 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6038 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6040 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6041 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6042 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
6043 &network_graph, 100, Arc::clone(&logger), &random_seed_bytes).unwrap();
6044 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6045 assert_eq!(hops.len(), route.paths[0].hops.len());
6046 for (idx, hop_pubkey) in hops.iter().enumerate() {
6047 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6052 fn avoids_saturating_channels() {
6053 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6054 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6055 let decay_params = ProbabilisticScoringDecayParameters::default();
6056 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6058 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6059 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6060 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6061 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6062 short_channel_id: 4,
6065 cltv_expiry_delta: (4 << 4) | 1,
6066 htlc_minimum_msat: 0,
6067 htlc_maximum_msat: 250_000_000,
6069 fee_proportional_millionths: 0,
6070 excess_data: Vec::new()
6072 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6073 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6074 short_channel_id: 13,
6077 cltv_expiry_delta: (13 << 4) | 1,
6078 htlc_minimum_msat: 0,
6079 htlc_maximum_msat: 250_000_000,
6081 fee_proportional_millionths: 0,
6082 excess_data: Vec::new()
6085 let config = UserConfig::default();
6086 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6087 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6088 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6089 // 100,000 sats is less than the available liquidity on each channel, set above.
6090 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();
6091 assert_eq!(route.paths.len(), 2);
6092 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6093 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6096 #[cfg(not(feature = "no-std"))]
6097 pub(super) fn random_init_seed() -> u64 {
6098 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6099 use core::hash::{BuildHasher, Hasher};
6100 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6101 println!("Using seed of {}", seed);
6106 #[cfg(not(feature = "no-std"))]
6107 fn generate_routes() {
6108 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6110 let logger = ln_test_utils::TestLogger::new();
6111 let graph = match super::bench_utils::read_network_graph(&logger) {
6119 let params = ProbabilisticScoringFeeParameters::default();
6120 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6121 let features = super::Bolt11InvoiceFeatures::empty();
6123 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6127 #[cfg(not(feature = "no-std"))]
6128 fn generate_routes_mpp() {
6129 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6131 let logger = ln_test_utils::TestLogger::new();
6132 let graph = match super::bench_utils::read_network_graph(&logger) {
6140 let params = ProbabilisticScoringFeeParameters::default();
6141 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6142 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6144 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6148 #[cfg(not(feature = "no-std"))]
6149 fn generate_large_mpp_routes() {
6150 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6152 let logger = ln_test_utils::TestLogger::new();
6153 let graph = match super::bench_utils::read_network_graph(&logger) {
6161 let params = ProbabilisticScoringFeeParameters::default();
6162 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6163 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6165 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6169 fn honors_manual_penalties() {
6170 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6171 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6173 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6174 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6176 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6177 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6179 // First check set manual penalties are returned by the scorer.
6180 let usage = ChannelUsage {
6182 inflight_htlc_msat: 0,
6183 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6185 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6186 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6187 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
6189 // Then check we can get a normal route
6190 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6191 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6192 assert!(route.is_ok());
6194 // Then check that we can't get a route if we ban an intermediate node.
6195 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6196 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6197 assert!(route.is_err());
6199 // Finally make sure we can route again, when we remove the ban.
6200 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6201 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6202 assert!(route.is_ok());
6206 fn abide_by_route_hint_max_htlc() {
6207 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6208 // params in the final route.
6209 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6210 let netgraph = network_graph.read_only();
6211 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6212 let scorer = ln_test_utils::TestScorer::new();
6213 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6214 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6215 let config = UserConfig::default();
6217 let max_htlc_msat = 50_000;
6218 let route_hint_1 = RouteHint(vec![RouteHintHop {
6219 src_node_id: nodes[2],
6220 short_channel_id: 42,
6223 proportional_millionths: 0,
6225 cltv_expiry_delta: 10,
6226 htlc_minimum_msat: None,
6227 htlc_maximum_msat: Some(max_htlc_msat),
6229 let dest_node_id = ln_test_utils::pubkey(42);
6230 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6231 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6232 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6234 // Make sure we'll error if our route hints don't have enough liquidity according to their
6235 // htlc_maximum_msat.
6236 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6237 &payment_params, &netgraph, None, max_htlc_msat + 1, Arc::clone(&logger), &scorer, &(),
6240 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6241 } else { panic!(); }
6243 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6244 let mut route_hint_2 = route_hint_1.clone();
6245 route_hint_2.0[0].short_channel_id = 43;
6246 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6247 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6248 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6249 let route = get_route(&our_id, &payment_params, &netgraph, None, max_htlc_msat + 1,
6250 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6251 assert_eq!(route.paths.len(), 2);
6252 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6253 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6257 fn direct_channel_to_hints_with_max_htlc() {
6258 // Check that if we have a first hop channel peer that's connected to multiple provided route
6259 // hints, that we properly split the payment between the route hints if needed.
6260 let logger = Arc::new(ln_test_utils::TestLogger::new());
6261 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6262 let scorer = ln_test_utils::TestScorer::new();
6263 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6264 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6265 let config = UserConfig::default();
6267 let our_node_id = ln_test_utils::pubkey(42);
6268 let intermed_node_id = ln_test_utils::pubkey(43);
6269 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6271 let amt_msat = 900_000;
6272 let max_htlc_msat = 500_000;
6273 let route_hint_1 = RouteHint(vec![RouteHintHop {
6274 src_node_id: intermed_node_id,
6275 short_channel_id: 44,
6278 proportional_millionths: 0,
6280 cltv_expiry_delta: 10,
6281 htlc_minimum_msat: None,
6282 htlc_maximum_msat: Some(max_htlc_msat),
6284 src_node_id: intermed_node_id,
6285 short_channel_id: 45,
6288 proportional_millionths: 0,
6290 cltv_expiry_delta: 10,
6291 htlc_minimum_msat: None,
6292 // Check that later route hint max htlcs don't override earlier ones
6293 htlc_maximum_msat: Some(max_htlc_msat - 50),
6295 let mut route_hint_2 = route_hint_1.clone();
6296 route_hint_2.0[0].short_channel_id = 46;
6297 route_hint_2.0[1].short_channel_id = 47;
6298 let dest_node_id = ln_test_utils::pubkey(44);
6299 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6300 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6301 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6303 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6304 Some(&first_hop.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6305 &random_seed_bytes).unwrap();
6306 assert_eq!(route.paths.len(), 2);
6307 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6308 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6309 assert_eq!(route.get_total_amount(), amt_msat);
6311 // Re-run but with two first hop channels connected to the same route hint peers that must be
6313 let first_hops = vec![
6314 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6315 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6317 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6318 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6319 &random_seed_bytes).unwrap();
6320 assert_eq!(route.paths.len(), 2);
6321 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6322 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6323 assert_eq!(route.get_total_amount(), amt_msat);
6325 // Make sure this works for blinded route hints.
6326 let blinded_path = BlindedPath {
6327 introduction_node_id: intermed_node_id,
6328 blinding_point: ln_test_utils::pubkey(42),
6330 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6331 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6334 let blinded_payinfo = BlindedPayInfo {
6336 fee_proportional_millionths: 0,
6337 htlc_minimum_msat: 1,
6338 htlc_maximum_msat: max_htlc_msat,
6339 cltv_expiry_delta: 10,
6340 features: BlindedHopFeatures::empty(),
6342 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6343 let payment_params = PaymentParameters::blinded(vec![
6344 (blinded_payinfo.clone(), blinded_path.clone()),
6345 (blinded_payinfo.clone(), blinded_path.clone())])
6346 .with_bolt12_features(bolt12_features).unwrap();
6347 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6348 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6349 &random_seed_bytes).unwrap();
6350 assert_eq!(route.paths.len(), 2);
6351 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6352 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6353 assert_eq!(route.get_total_amount(), amt_msat);
6357 fn blinded_route_ser() {
6358 let blinded_path_1 = BlindedPath {
6359 introduction_node_id: ln_test_utils::pubkey(42),
6360 blinding_point: ln_test_utils::pubkey(43),
6362 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6363 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6366 let blinded_path_2 = BlindedPath {
6367 introduction_node_id: ln_test_utils::pubkey(46),
6368 blinding_point: ln_test_utils::pubkey(47),
6370 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6371 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6374 // (De)serialize a Route with 1 blinded path out of two total paths.
6375 let mut route = Route { paths: vec![Path {
6376 hops: vec![RouteHop {
6377 pubkey: ln_test_utils::pubkey(50),
6378 node_features: NodeFeatures::empty(),
6379 short_channel_id: 42,
6380 channel_features: ChannelFeatures::empty(),
6382 cltv_expiry_delta: 0,
6384 blinded_tail: Some(BlindedTail {
6385 hops: blinded_path_1.blinded_hops,
6386 blinding_point: blinded_path_1.blinding_point,
6387 excess_final_cltv_expiry_delta: 40,
6388 final_value_msat: 100,
6390 hops: vec![RouteHop {
6391 pubkey: ln_test_utils::pubkey(51),
6392 node_features: NodeFeatures::empty(),
6393 short_channel_id: 43,
6394 channel_features: ChannelFeatures::empty(),
6396 cltv_expiry_delta: 0,
6397 }], blinded_tail: None }],
6398 payment_params: None,
6400 let encoded_route = route.encode();
6401 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6402 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6403 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6405 // (De)serialize a Route with two paths, each containing a blinded tail.
6406 route.paths[1].blinded_tail = Some(BlindedTail {
6407 hops: blinded_path_2.blinded_hops,
6408 blinding_point: blinded_path_2.blinding_point,
6409 excess_final_cltv_expiry_delta: 41,
6410 final_value_msat: 101,
6412 let encoded_route = route.encode();
6413 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6414 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6415 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6419 fn blinded_path_inflight_processing() {
6420 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6421 // account for the blinded tail's final amount_msat.
6422 let mut inflight_htlcs = InFlightHtlcs::new();
6423 let blinded_path = BlindedPath {
6424 introduction_node_id: ln_test_utils::pubkey(43),
6425 blinding_point: ln_test_utils::pubkey(48),
6426 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
6429 hops: vec![RouteHop {
6430 pubkey: ln_test_utils::pubkey(42),
6431 node_features: NodeFeatures::empty(),
6432 short_channel_id: 42,
6433 channel_features: ChannelFeatures::empty(),
6435 cltv_expiry_delta: 0,
6438 pubkey: blinded_path.introduction_node_id,
6439 node_features: NodeFeatures::empty(),
6440 short_channel_id: 43,
6441 channel_features: ChannelFeatures::empty(),
6443 cltv_expiry_delta: 0,
6445 blinded_tail: Some(BlindedTail {
6446 hops: blinded_path.blinded_hops,
6447 blinding_point: blinded_path.blinding_point,
6448 excess_final_cltv_expiry_delta: 0,
6449 final_value_msat: 200,
6452 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
6453 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
6454 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
6458 fn blinded_path_cltv_shadow_offset() {
6459 // Make sure we add a shadow offset when sending to blinded paths.
6460 let blinded_path = BlindedPath {
6461 introduction_node_id: ln_test_utils::pubkey(43),
6462 blinding_point: ln_test_utils::pubkey(44),
6464 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
6465 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
6468 let mut route = Route { paths: vec![Path {
6469 hops: vec![RouteHop {
6470 pubkey: ln_test_utils::pubkey(42),
6471 node_features: NodeFeatures::empty(),
6472 short_channel_id: 42,
6473 channel_features: ChannelFeatures::empty(),
6475 cltv_expiry_delta: 0,
6478 pubkey: blinded_path.introduction_node_id,
6479 node_features: NodeFeatures::empty(),
6480 short_channel_id: 43,
6481 channel_features: ChannelFeatures::empty(),
6483 cltv_expiry_delta: 0,
6486 blinded_tail: Some(BlindedTail {
6487 hops: blinded_path.blinded_hops,
6488 blinding_point: blinded_path.blinding_point,
6489 excess_final_cltv_expiry_delta: 0,
6490 final_value_msat: 200,
6492 }], payment_params: None};
6494 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
6495 let (_, network_graph, _, _, _) = build_line_graph();
6496 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
6497 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
6498 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
6502 fn simple_blinded_route_hints() {
6503 do_simple_blinded_route_hints(1);
6504 do_simple_blinded_route_hints(2);
6505 do_simple_blinded_route_hints(3);
6508 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
6509 // Check that we can generate a route to a blinded path with the expected hops.
6510 let (secp_ctx, network, _, _, logger) = build_graph();
6511 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6512 let network_graph = network.read_only();
6514 let scorer = ln_test_utils::TestScorer::new();
6515 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6516 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6518 let mut blinded_path = BlindedPath {
6519 introduction_node_id: nodes[2],
6520 blinding_point: ln_test_utils::pubkey(42),
6521 blinded_hops: Vec::with_capacity(num_blinded_hops),
6523 for i in 0..num_blinded_hops {
6524 blinded_path.blinded_hops.push(
6525 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
6528 let blinded_payinfo = BlindedPayInfo {
6530 fee_proportional_millionths: 500,
6531 htlc_minimum_msat: 1000,
6532 htlc_maximum_msat: 100_000_000,
6533 cltv_expiry_delta: 15,
6534 features: BlindedHopFeatures::empty(),
6537 let final_amt_msat = 1001;
6538 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
6539 let route = get_route(&our_id, &payment_params, &network_graph, None, final_amt_msat , Arc::clone(&logger),
6540 &scorer, &(), &random_seed_bytes).unwrap();
6541 assert_eq!(route.paths.len(), 1);
6542 assert_eq!(route.paths[0].hops.len(), 2);
6544 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
6545 assert_eq!(tail.hops, blinded_path.blinded_hops);
6546 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
6547 assert_eq!(tail.final_value_msat, 1001);
6549 let final_hop = route.paths[0].hops.last().unwrap();
6550 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
6551 if tail.hops.len() > 1 {
6552 assert_eq!(final_hop.fee_msat,
6553 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
6554 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
6556 assert_eq!(final_hop.fee_msat, 0);
6557 assert_eq!(final_hop.cltv_expiry_delta, 0);
6562 fn blinded_path_routing_errors() {
6563 // Check that we can generate a route to a blinded path with the expected hops.
6564 let (secp_ctx, network, _, _, logger) = build_graph();
6565 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6566 let network_graph = network.read_only();
6568 let scorer = ln_test_utils::TestScorer::new();
6569 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6570 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6572 let mut invalid_blinded_path = BlindedPath {
6573 introduction_node_id: nodes[2],
6574 blinding_point: ln_test_utils::pubkey(42),
6576 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
6579 let blinded_payinfo = BlindedPayInfo {
6581 fee_proportional_millionths: 500,
6582 htlc_minimum_msat: 1000,
6583 htlc_maximum_msat: 100_000_000,
6584 cltv_expiry_delta: 15,
6585 features: BlindedHopFeatures::empty(),
6588 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
6589 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
6590 let payment_params = PaymentParameters::blinded(vec![
6591 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
6592 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
6593 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6594 &scorer, &(), &random_seed_bytes)
6596 Err(LightningError { err, .. }) => {
6597 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
6599 _ => panic!("Expected error")
6602 invalid_blinded_path.introduction_node_id = our_id;
6603 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
6604 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6605 &scorer, &(), &random_seed_bytes)
6607 Err(LightningError { err, .. }) => {
6608 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
6610 _ => panic!("Expected error")
6613 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
6614 invalid_blinded_path.blinded_hops.clear();
6615 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
6616 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6617 &scorer, &(), &random_seed_bytes)
6619 Err(LightningError { err, .. }) => {
6620 assert_eq!(err, "0-hop blinded path provided");
6622 _ => panic!("Expected error")
6627 fn matching_intro_node_paths_provided() {
6628 // Check that if multiple blinded paths with the same intro node are provided in payment
6629 // parameters, we'll return the correct paths in the resulting MPP route.
6630 let (secp_ctx, network, _, _, logger) = build_graph();
6631 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6632 let network_graph = network.read_only();
6634 let scorer = ln_test_utils::TestScorer::new();
6635 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6636 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6637 let config = UserConfig::default();
6639 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6640 let blinded_path_1 = BlindedPath {
6641 introduction_node_id: nodes[2],
6642 blinding_point: ln_test_utils::pubkey(42),
6644 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6645 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6648 let blinded_payinfo_1 = BlindedPayInfo {
6650 fee_proportional_millionths: 0,
6651 htlc_minimum_msat: 0,
6652 htlc_maximum_msat: 30_000,
6653 cltv_expiry_delta: 0,
6654 features: BlindedHopFeatures::empty(),
6657 let mut blinded_path_2 = blinded_path_1.clone();
6658 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
6659 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
6660 blinded_payinfo_2.htlc_maximum_msat = 70_000;
6662 let blinded_hints = vec![
6663 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
6664 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
6666 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
6667 .with_bolt12_features(bolt12_features.clone()).unwrap();
6669 let route = get_route(&our_id, &payment_params, &network_graph, None,
6670 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6671 assert_eq!(route.paths.len(), 2);
6672 let mut total_amount_paid_msat = 0;
6673 for path in route.paths.into_iter() {
6674 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6675 if let Some(bt) = &path.blinded_tail {
6676 assert_eq!(bt.blinding_point,
6677 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
6678 .map(|(_, bp)| bp.blinding_point).unwrap());
6679 } else { panic!(); }
6680 total_amount_paid_msat += path.final_value_msat();
6682 assert_eq!(total_amount_paid_msat, 100_000);
6686 fn direct_to_intro_node() {
6687 // This previously caused a debug panic in the router when asserting
6688 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
6689 // direct channels we failed to account for the fee charged for use of the blinded path.
6692 // node0 -1(1)2 - node1
6693 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
6694 // doesn't account for the blinded path fee.
6696 let secp_ctx = Secp256k1::new();
6697 let logger = Arc::new(ln_test_utils::TestLogger::new());
6698 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6699 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
6700 let scorer = ln_test_utils::TestScorer::new();
6701 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6702 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6704 let amt_msat = 10_000_000;
6705 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
6706 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
6707 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6708 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6709 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6710 short_channel_id: 1,
6713 cltv_expiry_delta: 42,
6714 htlc_minimum_msat: 1_000,
6715 htlc_maximum_msat: 10_000_000,
6717 fee_proportional_millionths: 0,
6718 excess_data: Vec::new()
6720 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6721 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6722 short_channel_id: 1,
6725 cltv_expiry_delta: 42,
6726 htlc_minimum_msat: 1_000,
6727 htlc_maximum_msat: 10_000_000,
6729 fee_proportional_millionths: 0,
6730 excess_data: Vec::new()
6732 let first_hops = vec![
6733 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6735 let blinded_path = BlindedPath {
6736 introduction_node_id: nodes[1],
6737 blinding_point: ln_test_utils::pubkey(42),
6739 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6740 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6743 let blinded_payinfo = BlindedPayInfo {
6744 fee_base_msat: 1000,
6745 fee_proportional_millionths: 0,
6746 htlc_minimum_msat: 1000,
6747 htlc_maximum_msat: MAX_VALUE_MSAT,
6748 cltv_expiry_delta: 0,
6749 features: BlindedHopFeatures::empty(),
6751 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
6753 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
6755 let netgraph = network_graph.read_only();
6756 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &payment_params, &netgraph,
6757 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6758 &random_seed_bytes) {
6759 assert_eq!(err, "Failed to find a path to the given destination");
6760 } else { panic!("Expected error") }
6762 // Sending an exact amount accounting for the blinded path fee works.
6763 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
6764 let route = get_route(&nodes[0], &payment_params, &netgraph,
6765 Some(&first_hops.iter().collect::<Vec<_>>()), amt_minus_blinded_path_fee,
6766 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6767 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
6768 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
6772 fn direct_to_matching_intro_nodes() {
6773 // This previously caused us to enter `unreachable` code in the following situation:
6774 // 1. We add a route candidate for intro_node contributing a high amount
6775 // 2. We add a first_hop<>intro_node route candidate for the same high amount
6776 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
6777 // amount, and update our route candidate for intro_node for the lower amount
6778 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
6779 // lower contribution amount, but fail (this was previously caused by failure to account for
6780 // blinded path fees when adding first_hop<>intro_node candidates)
6781 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
6782 // candidate still thinks its path is contributing the original higher amount. This caused us
6783 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
6785 let secp_ctx = Secp256k1::new();
6786 let logger = Arc::new(ln_test_utils::TestLogger::new());
6787 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6788 let scorer = ln_test_utils::TestScorer::new();
6789 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6790 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6791 let config = UserConfig::default();
6793 // Values are taken from the fuzz input that uncovered this panic.
6794 let amt_msat = 21_7020_5185_1403_2640;
6795 let (_, _, _, nodes) = get_nodes(&secp_ctx);
6796 let first_hops = vec![
6797 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
6798 18446744073709551615)];
6800 let blinded_path = BlindedPath {
6801 introduction_node_id: nodes[1],
6802 blinding_point: ln_test_utils::pubkey(42),
6804 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6805 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6808 let blinded_payinfo = BlindedPayInfo {
6809 fee_base_msat: 5046_2720,
6810 fee_proportional_millionths: 0,
6811 htlc_minimum_msat: 4503_5996_2737_0496,
6812 htlc_maximum_msat: 45_0359_9627_3704_9600,
6813 cltv_expiry_delta: 0,
6814 features: BlindedHopFeatures::empty(),
6816 let mut blinded_hints = vec![
6817 (blinded_payinfo.clone(), blinded_path.clone()),
6818 (blinded_payinfo.clone(), blinded_path.clone()),
6820 blinded_hints[1].0.fee_base_msat = 419_4304;
6821 blinded_hints[1].0.fee_proportional_millionths = 257;
6822 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
6823 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
6824 blinded_hints[1].0.cltv_expiry_delta = 0;
6826 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6827 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
6828 .with_bolt12_features(bolt12_features.clone()).unwrap();
6830 let netgraph = network_graph.read_only();
6831 let route = get_route(&nodes[0], &payment_params, &netgraph,
6832 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat,
6833 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6834 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
6835 assert_eq!(route.get_total_amount(), amt_msat);
6839 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
6840 pub(crate) mod bench_utils {
6844 use bitcoin::hashes::Hash;
6845 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
6847 use crate::chain::transaction::OutPoint;
6848 use crate::routing::scoring::ScoreUpdate;
6849 use crate::sign::{EntropySource, KeysManager};
6850 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
6851 use crate::ln::features::Bolt11InvoiceFeatures;
6852 use crate::routing::gossip::NetworkGraph;
6853 use crate::util::config::UserConfig;
6854 use crate::util::ser::ReadableArgs;
6855 use crate::util::test_utils::TestLogger;
6857 /// Tries to open a network graph file, or panics with a URL to fetch it.
6858 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
6859 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
6860 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
6861 .or_else(|_| { // Fall back to guessing based on the binary location
6862 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
6863 let mut path = std::env::current_exe().unwrap();
6864 path.pop(); // lightning-...
6866 path.pop(); // debug
6867 path.pop(); // target
6868 path.push("lightning");
6869 path.push("net_graph-2023-01-18.bin");
6872 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
6873 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
6874 let mut path = std::env::current_exe().unwrap();
6875 path.pop(); // bench...
6877 path.pop(); // debug
6878 path.pop(); // target
6879 path.pop(); // bench
6880 path.push("lightning");
6881 path.push("net_graph-2023-01-18.bin");
6884 .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");
6885 #[cfg(require_route_graph_test)]
6886 return Ok(res.unwrap());
6887 #[cfg(not(require_route_graph_test))]
6891 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
6892 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
6895 pub(crate) fn payer_pubkey() -> PublicKey {
6896 let secp_ctx = Secp256k1::new();
6897 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
6901 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
6903 channel_id: [0; 32],
6904 counterparty: ChannelCounterparty {
6905 features: channelmanager::provided_init_features(&UserConfig::default()),
6907 unspendable_punishment_reserve: 0,
6908 forwarding_info: None,
6909 outbound_htlc_minimum_msat: None,
6910 outbound_htlc_maximum_msat: None,
6912 funding_txo: Some(OutPoint {
6913 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
6916 short_channel_id: Some(1),
6917 inbound_scid_alias: None,
6918 outbound_scid_alias: None,
6919 channel_value_satoshis: 10_000_000_000,
6921 outbound_capacity_msat: 10_000_000_000,
6922 next_outbound_htlc_minimum_msat: 0,
6923 next_outbound_htlc_limit_msat: 10_000_000_000,
6924 inbound_capacity_msat: 0,
6925 unspendable_punishment_reserve: None,
6926 confirmations_required: None,
6927 confirmations: None,
6928 force_close_spend_delay: None,
6930 is_channel_ready: true,
6933 inbound_htlc_minimum_msat: None,
6934 inbound_htlc_maximum_msat: None,
6936 feerate_sat_per_1000_weight: None,
6937 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
6941 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
6942 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
6943 starting_amount: u64, route_count: usize,
6944 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
6945 let payer = payer_pubkey();
6946 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
6947 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6949 let nodes = graph.read_only().nodes().clone();
6950 let mut route_endpoints = Vec::new();
6951 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
6952 // with some routes we picked being un-routable.
6953 for _ in 0..route_count * 3 / 2 {
6955 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6956 let src = PublicKey::from_slice(nodes.unordered_keys()
6957 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6958 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6959 let dst = PublicKey::from_slice(nodes.unordered_keys()
6960 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6961 let params = PaymentParameters::from_node_id(dst, 42)
6962 .with_bolt11_features(features.clone()).unwrap();
6963 let first_hop = first_hop(src);
6964 let amt = starting_amount + seed % 1_000_000;
6966 get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]),
6967 amt, &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
6969 // ...and seed the scorer with success and failure data...
6970 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6971 let mut score_amt = seed % 1_000_000_000;
6973 // Generate fail/success paths for a wider range of potential amounts with
6974 // MPP enabled to give us a chance to apply penalties for more potential
6976 let mpp_features = channelmanager::provided_invoice_features(&UserConfig::default());
6977 let params = PaymentParameters::from_node_id(dst, 42)
6978 .with_bolt11_features(mpp_features).unwrap();
6980 let route_res = get_route(&payer, ¶ms, &graph.read_only(),
6981 Some(&[&first_hop]), score_amt, &TestLogger::new(), scorer,
6982 score_params, &random_seed_bytes);
6983 if let Ok(route) = route_res {
6984 for path in route.paths {
6985 if seed & 0x80 == 0 {
6986 scorer.payment_path_successful(&path);
6988 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
6989 scorer.payment_path_failed(&path, short_channel_id);
6991 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6995 // If we couldn't find a path with a higer amount, reduce and try again.
6999 route_endpoints.push((first_hop, params, amt));
7005 // Because we've changed channel scores, it's possible we'll take different routes to the
7006 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
7007 // requires a too-high CLTV delta.
7008 route_endpoints.retain(|(first_hop, params, amt)| {
7009 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
7010 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
7012 route_endpoints.truncate(route_count);
7013 assert_eq!(route_endpoints.len(), route_count);
7021 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
7022 use crate::sign::{EntropySource, KeysManager};
7023 use crate::ln::channelmanager;
7024 use crate::ln::features::Bolt11InvoiceFeatures;
7025 use crate::routing::gossip::NetworkGraph;
7026 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
7027 use crate::util::config::UserConfig;
7028 use crate::util::logger::{Logger, Record};
7029 use crate::util::test_utils::TestLogger;
7031 use criterion::Criterion;
7033 struct DummyLogger {}
7034 impl Logger for DummyLogger {
7035 fn log(&self, _record: &Record) {}
7038 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7039 let logger = TestLogger::new();
7040 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7041 let scorer = FixedPenaltyScorer::with_penalty(0);
7042 generate_routes(bench, &network_graph, scorer, &(), Bolt11InvoiceFeatures::empty(), 0,
7043 "generate_routes_with_zero_penalty_scorer");
7046 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7047 let logger = TestLogger::new();
7048 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7049 let scorer = FixedPenaltyScorer::with_penalty(0);
7050 generate_routes(bench, &network_graph, scorer, &(),
7051 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7052 "generate_mpp_routes_with_zero_penalty_scorer");
7055 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7056 let logger = TestLogger::new();
7057 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7058 let params = ProbabilisticScoringFeeParameters::default();
7059 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7060 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
7061 "generate_routes_with_probabilistic_scorer");
7064 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7065 let logger = TestLogger::new();
7066 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7067 let params = ProbabilisticScoringFeeParameters::default();
7068 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7069 generate_routes(bench, &network_graph, scorer, ¶ms,
7070 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7071 "generate_mpp_routes_with_probabilistic_scorer");
7074 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7075 let logger = TestLogger::new();
7076 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7077 let params = ProbabilisticScoringFeeParameters::default();
7078 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7079 generate_routes(bench, &network_graph, scorer, ¶ms,
7080 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
7081 "generate_large_mpp_routes_with_probabilistic_scorer");
7084 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
7085 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
7086 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
7087 bench_name: &'static str,
7089 let payer = bench_utils::payer_pubkey();
7090 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7091 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7093 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
7094 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
7096 // ...then benchmark finding paths between the nodes we learned.
7098 bench.bench_function(bench_name, |b| b.iter(|| {
7099 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
7100 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
7101 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());