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 RouteParameters {
439 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
440 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
441 Self { payment_params, final_value_msat }
445 impl Writeable for RouteParameters {
446 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
447 write_tlv_fields!(writer, {
448 (0, self.payment_params, required),
449 (2, self.final_value_msat, required),
450 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
451 // `RouteParameters` directly. For compatibility, we write it here.
452 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
458 impl Readable for RouteParameters {
459 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
460 _init_and_read_len_prefixed_tlv_fields!(reader, {
461 (0, payment_params, (required: ReadableArgs, 0)),
462 (2, final_value_msat, required),
463 (4, final_cltv_delta, option),
465 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
466 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
467 if final_cltv_expiry_delta == &0 {
468 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
473 final_value_msat: final_value_msat.0.unwrap(),
478 /// Maximum total CTLV difference we allow for a full payment path.
479 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
481 /// Maximum number of paths we allow an (MPP) payment to have.
482 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
483 // limits, but for now more than 10 paths likely carries too much one-path failure.
484 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
486 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
488 // The median hop CLTV expiry delta currently seen in the network.
489 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
491 // During routing, we only consider paths shorter than our maximum length estimate.
492 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
493 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
494 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
496 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
497 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
498 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
499 // (payment_secret and total_msat) = 93 bytes for the final hop.
500 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
501 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
502 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
504 /// Information used to route a payment.
505 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
506 pub struct PaymentParameters {
507 /// Information about the payee, such as their features and route hints for their channels.
510 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
511 pub expiry_time: Option<u64>,
513 /// The maximum total CLTV delta we accept for the route.
514 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
515 pub max_total_cltv_expiry_delta: u32,
517 /// The maximum number of paths that may be used by (MPP) payments.
518 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
519 pub max_path_count: u8,
521 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
522 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
523 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
524 /// increasing failure probability for those paths.
526 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
527 /// restriction have been found. While paths which meet this criteria will be searched for, it
528 /// is ultimately up to the scorer to select them over other paths.
530 /// A value of 0 will allow payments up to and including a channel's total announced usable
531 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
534 pub max_channel_saturation_power_of_half: u8,
536 /// A list of SCIDs which this payment was previously attempted over and which caused the
537 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
539 pub previously_failed_channels: Vec<u64>,
542 impl Writeable for PaymentParameters {
543 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
544 let mut clear_hints = &vec![];
545 let mut blinded_hints = &vec![];
547 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
548 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
550 write_tlv_fields!(writer, {
551 (0, self.payee.node_id(), option),
552 (1, self.max_total_cltv_expiry_delta, required),
553 (2, self.payee.features(), option),
554 (3, self.max_path_count, required),
555 (4, *clear_hints, required_vec),
556 (5, self.max_channel_saturation_power_of_half, required),
557 (6, self.expiry_time, option),
558 (7, self.previously_failed_channels, required_vec),
559 (8, *blinded_hints, optional_vec),
560 (9, self.payee.final_cltv_expiry_delta(), option),
566 impl ReadableArgs<u32> for PaymentParameters {
567 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
568 _init_and_read_len_prefixed_tlv_fields!(reader, {
569 (0, payee_pubkey, option),
570 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
571 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
572 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
573 (4, clear_route_hints, required_vec),
574 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
575 (6, expiry_time, option),
576 (7, previously_failed_channels, optional_vec),
577 (8, blinded_route_hints, optional_vec),
578 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
580 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
581 let payee = if blinded_route_hints.len() != 0 {
582 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
584 route_hints: blinded_route_hints,
585 features: features.and_then(|f: Features| f.bolt12()),
589 route_hints: clear_route_hints,
590 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
591 features: features.and_then(|f| f.bolt11()),
592 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
596 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
597 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
599 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
601 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
607 impl PaymentParameters {
608 /// Creates a payee with the node id of the given `pubkey`.
610 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
612 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
614 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
616 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
617 max_path_count: DEFAULT_MAX_PATH_COUNT,
618 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
619 previously_failed_channels: Vec::new(),
623 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
625 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
628 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
629 /// whether your router will be allowed to find a multi-part route for this payment. If you
630 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
631 /// [`RecipientOnionFields::secret_only`].
633 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
634 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
635 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
636 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
637 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
640 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
641 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
642 /// [`PaymentParameters::expiry_time`].
643 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
644 Self::blinded(invoice.payment_paths().to_vec())
645 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
646 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
649 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
650 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
652 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
654 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
655 max_path_count: DEFAULT_MAX_PATH_COUNT,
656 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
657 previously_failed_channels: Vec::new(),
661 /// Includes the payee's features. Errors if the parameters were not initialized with
662 /// [`PaymentParameters::from_bolt12_invoice`].
664 /// This is not exported to bindings users since bindings don't support move semantics
665 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
667 Payee::Clear { .. } => Err(()),
668 Payee::Blinded { route_hints, .. } =>
669 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
673 /// Includes the payee's features. Errors if the parameters were initialized with
674 /// [`PaymentParameters::from_bolt12_invoice`].
676 /// This is not exported to bindings users since bindings don't support move semantics
677 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
679 Payee::Blinded { .. } => Err(()),
680 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
682 payee: Payee::Clear {
683 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
689 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
690 /// [`PaymentParameters::from_bolt12_invoice`].
692 /// This is not exported to bindings users since bindings don't support move semantics
693 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
695 Payee::Blinded { .. } => Err(()),
696 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
698 payee: Payee::Clear {
699 route_hints, node_id, features, final_cltv_expiry_delta,
705 /// Includes a payment expiration in seconds relative to the UNIX epoch.
707 /// This is not exported to bindings users since bindings don't support move semantics
708 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
709 Self { expiry_time: Some(expiry_time), ..self }
712 /// Includes a limit for the total CLTV expiry delta which is considered during routing
714 /// This is not exported to bindings users since bindings don't support move semantics
715 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
716 Self { max_total_cltv_expiry_delta, ..self }
719 /// Includes a limit for the maximum number of payment paths that may be used.
721 /// This is not exported to bindings users since bindings don't support move semantics
722 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
723 Self { max_path_count, ..self }
726 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
727 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
729 /// This is not exported to bindings users since bindings don't support move semantics
730 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
731 Self { max_channel_saturation_power_of_half, ..self }
735 /// The recipient of a payment, differing based on whether they've hidden their identity with route
737 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
739 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
740 /// will be included in the final [`Route`].
742 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
744 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
745 /// Features supported by the payee.
747 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
749 features: Option<Bolt12InvoiceFeatures>,
751 /// The recipient included these route hints in their BOLT11 invoice.
753 /// The node id of the payee.
755 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
756 route_hints: Vec<RouteHint>,
757 /// Features supported by the payee.
759 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
760 /// does not contain any features.
762 /// [`for_keysend`]: PaymentParameters::for_keysend
763 features: Option<Bolt11InvoiceFeatures>,
764 /// The minimum CLTV delta at the end of the route. This value must not be zero.
765 final_cltv_expiry_delta: u32,
770 fn node_id(&self) -> Option<PublicKey> {
772 Self::Clear { node_id, .. } => Some(*node_id),
776 fn node_features(&self) -> Option<NodeFeatures> {
778 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
779 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
782 fn supports_basic_mpp(&self) -> bool {
784 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
785 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
788 fn features(&self) -> Option<FeaturesRef> {
790 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
791 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
794 fn final_cltv_expiry_delta(&self) -> Option<u32> {
796 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
800 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
802 Self::Blinded { route_hints, .. } => &route_hints[..],
803 Self::Clear { .. } => &[]
807 fn unblinded_route_hints(&self) -> &[RouteHint] {
809 Self::Blinded { .. } => &[],
810 Self::Clear { route_hints, .. } => &route_hints[..]
815 enum FeaturesRef<'a> {
816 Bolt11(&'a Bolt11InvoiceFeatures),
817 Bolt12(&'a Bolt12InvoiceFeatures),
820 Bolt11(Bolt11InvoiceFeatures),
821 Bolt12(Bolt12InvoiceFeatures),
825 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
827 Self::Bolt12(f) => Some(f),
831 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
833 Self::Bolt11(f) => Some(f),
839 impl<'a> Writeable for FeaturesRef<'a> {
840 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
842 Self::Bolt11(f) => Ok(f.write(w)?),
843 Self::Bolt12(f) => Ok(f.write(w)?),
848 impl ReadableArgs<bool> for Features {
849 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
850 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
851 Ok(Self::Bolt12(Readable::read(reader)?))
855 /// A list of hops along a payment path terminating with a channel to the recipient.
856 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
857 pub struct RouteHint(pub Vec<RouteHintHop>);
859 impl Writeable for RouteHint {
860 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
861 (self.0.len() as u64).write(writer)?;
862 for hop in self.0.iter() {
869 impl Readable for RouteHint {
870 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
871 let hop_count: u64 = Readable::read(reader)?;
872 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
873 for _ in 0..hop_count {
874 hops.push(Readable::read(reader)?);
880 /// A channel descriptor for a hop along a payment path.
881 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
882 pub struct RouteHintHop {
883 /// The node_id of the non-target end of the route
884 pub src_node_id: PublicKey,
885 /// The short_channel_id of this channel
886 pub short_channel_id: u64,
887 /// The fees which must be paid to use this channel
888 pub fees: RoutingFees,
889 /// The difference in CLTV values between this node and the next node.
890 pub cltv_expiry_delta: u16,
891 /// The minimum value, in msat, which must be relayed to the next hop.
892 pub htlc_minimum_msat: Option<u64>,
893 /// The maximum value in msat available for routing with a single HTLC.
894 pub htlc_maximum_msat: Option<u64>,
897 impl_writeable_tlv_based!(RouteHintHop, {
898 (0, src_node_id, required),
899 (1, htlc_minimum_msat, option),
900 (2, short_channel_id, required),
901 (3, htlc_maximum_msat, option),
903 (6, cltv_expiry_delta, required),
906 #[derive(Eq, PartialEq)]
907 struct RouteGraphNode {
909 lowest_fee_to_node: u64,
910 total_cltv_delta: u32,
911 // The maximum value a yet-to-be-constructed payment path might flow through this node.
912 // This value is upper-bounded by us by:
913 // - how much is needed for a path being constructed
914 // - how much value can channels following this node (up to the destination) can contribute,
915 // considering their capacity and fees
916 value_contribution_msat: u64,
917 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
918 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
919 path_htlc_minimum_msat: u64,
920 /// All penalties incurred from this hop on the way to the destination, as calculated using
922 path_penalty_msat: u64,
923 /// The number of hops walked up to this node.
924 path_length_to_node: u8,
927 impl cmp::Ord for RouteGraphNode {
928 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
929 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
930 .saturating_add(other.path_penalty_msat);
931 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
932 .saturating_add(self.path_penalty_msat);
933 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
937 impl cmp::PartialOrd for RouteGraphNode {
938 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
939 Some(self.cmp(other))
943 /// A wrapper around the various hop representations.
945 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
946 #[derive(Clone, Debug)]
947 enum CandidateRouteHop<'a> {
948 /// A hop from the payer, where the outbound liquidity is known.
950 details: &'a ChannelDetails,
952 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
954 info: DirectedChannelInfo<'a>,
955 short_channel_id: u64,
957 /// A hop to the payee found in the BOLT 11 payment invoice, though not necessarily a direct
960 hint: &'a RouteHintHop,
962 /// The payee's identity is concealed behind blinded paths provided in a BOLT 12 invoice.
964 hint: &'a (BlindedPayInfo, BlindedPath),
967 /// Similar to [`Self::Blinded`], but the path here has 1 blinded hop. `BlindedPayInfo` provided
968 /// for 1-hop blinded paths is ignored because it is meant to apply to the hops *between* the
969 /// introduction node and the destination. Useful for tracking that we need to include a blinded
970 /// path at the end of our [`Route`].
972 hint: &'a (BlindedPayInfo, BlindedPath),
977 impl<'a> CandidateRouteHop<'a> {
978 fn short_channel_id(&self) -> Option<u64> {
980 CandidateRouteHop::FirstHop { details } => Some(details.get_outbound_payment_scid().unwrap()),
981 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
982 CandidateRouteHop::PrivateHop { hint } => Some(hint.short_channel_id),
983 CandidateRouteHop::Blinded { .. } => None,
984 CandidateRouteHop::OneHopBlinded { .. } => None,
988 // NOTE: This may alloc memory so avoid calling it in a hot code path.
989 fn features(&self) -> ChannelFeatures {
991 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
992 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
993 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
994 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
995 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
999 fn cltv_expiry_delta(&self) -> u32 {
1001 CandidateRouteHop::FirstHop { .. } => 0,
1002 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1003 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
1004 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1005 CandidateRouteHop::OneHopBlinded { .. } => 0,
1009 fn htlc_minimum_msat(&self) -> u64 {
1011 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_minimum_msat,
1012 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1013 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
1014 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1015 CandidateRouteHop::OneHopBlinded { .. } => 0,
1019 fn fees(&self) -> RoutingFees {
1021 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1022 base_msat: 0, proportional_millionths: 0,
1024 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1025 CandidateRouteHop::PrivateHop { hint } => hint.fees,
1026 CandidateRouteHop::Blinded { hint, .. } => {
1028 base_msat: hint.0.fee_base_msat,
1029 proportional_millionths: hint.0.fee_proportional_millionths
1032 CandidateRouteHop::OneHopBlinded { .. } =>
1033 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1037 fn effective_capacity(&self) -> EffectiveCapacity {
1039 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
1040 liquidity_msat: details.next_outbound_htlc_limit_msat,
1042 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1043 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }} =>
1044 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1045 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }} =>
1046 EffectiveCapacity::Infinite,
1047 CandidateRouteHop::Blinded { hint, .. } =>
1048 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1049 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1053 fn id(&self, channel_direction: bool /* src_node_id < target_node_id */) -> CandidateHopId {
1055 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1056 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1057 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), channel_direction)),
1060 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1062 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1070 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1071 enum CandidateHopId {
1072 /// Contains (scid, src_node_id < target_node_id)
1074 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1079 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1080 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1082 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1083 EffectiveCapacity::Infinite => u64::max_value(),
1084 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1085 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1086 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1087 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1088 // expected to have been generated from up-to-date capacity information.
1089 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1090 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1091 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1095 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1096 -> bool where I1::Item: PartialEq<I2::Item> {
1098 let a = iter_a.next();
1099 let b = iter_b.next();
1100 if a.is_none() && b.is_none() { return true; }
1101 if a.is_none() || b.is_none() { return false; }
1102 if a.unwrap().ne(&b.unwrap()) { return false; }
1106 /// It's useful to keep track of the hops associated with the fees required to use them,
1107 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1108 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1109 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1111 struct PathBuildingHop<'a> {
1112 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
1113 // is a larger refactor and will require careful performance analysis.
1115 candidate: CandidateRouteHop<'a>,
1118 /// All the fees paid *after* this channel on the way to the destination
1119 next_hops_fee_msat: u64,
1120 /// Fee paid for the use of the current channel (see candidate.fees()).
1121 /// The value will be actually deducted from the counterparty balance on the previous link.
1122 hop_use_fee_msat: u64,
1123 /// Used to compare channels when choosing the for routing.
1124 /// Includes paying for the use of a hop and the following hops, as well as
1125 /// an estimated cost of reaching this hop.
1126 /// Might get stale when fees are recomputed. Primarily for internal use.
1127 total_fee_msat: u64,
1128 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1129 /// walk and may be invalid thereafter.
1130 path_htlc_minimum_msat: u64,
1131 /// All penalties incurred from this channel on the way to the destination, as calculated using
1132 /// channel scoring.
1133 path_penalty_msat: u64,
1134 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1135 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1136 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1137 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1138 /// avoid processing them again.
1139 was_processed: bool,
1140 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1141 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1142 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1143 // value_contribution_msat, which requires tracking it here. See comments below where it is
1144 // used for more info.
1145 value_contribution_msat: u64,
1148 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1149 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1150 let mut debug_struct = f.debug_struct("PathBuildingHop");
1152 .field("node_id", &self.node_id)
1153 .field("short_channel_id", &self.candidate.short_channel_id())
1154 .field("total_fee_msat", &self.total_fee_msat)
1155 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1156 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1157 .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)))
1158 .field("path_penalty_msat", &self.path_penalty_msat)
1159 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1160 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1161 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1162 let debug_struct = debug_struct
1163 .field("value_contribution_msat", &self.value_contribution_msat);
1164 debug_struct.finish()
1168 // Instantiated with a list of hops with correct data in them collected during path finding,
1169 // an instance of this struct should be further modified only via given methods.
1171 struct PaymentPath<'a> {
1172 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1175 impl<'a> PaymentPath<'a> {
1176 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1177 fn get_value_msat(&self) -> u64 {
1178 self.hops.last().unwrap().0.fee_msat
1181 fn get_path_penalty_msat(&self) -> u64 {
1182 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1185 fn get_total_fee_paid_msat(&self) -> u64 {
1186 if self.hops.len() < 1 {
1190 // Can't use next_hops_fee_msat because it gets outdated.
1191 for (i, (hop, _)) in self.hops.iter().enumerate() {
1192 if i != self.hops.len() - 1 {
1193 result += hop.fee_msat;
1199 fn get_cost_msat(&self) -> u64 {
1200 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1203 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1204 // to change fees may result in an inconsistency.
1206 // Sometimes we call this function right after constructing a path which is inconsistent in
1207 // that it the value being transferred has decreased while we were doing path finding, leading
1208 // to the fees being paid not lining up with the actual limits.
1210 // Note that this function is not aware of the available_liquidity limit, and thus does not
1211 // support increasing the value being transferred beyond what was selected during the initial
1213 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
1214 let mut total_fee_paid_msat = 0 as u64;
1215 for i in (0..self.hops.len()).rev() {
1216 let last_hop = i == self.hops.len() - 1;
1218 // For non-last-hop, this value will represent the fees paid on the current hop. It
1219 // will consist of the fees for the use of the next hop, and extra fees to match
1220 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1221 let mut cur_hop_fees_msat = 0;
1223 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1226 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1227 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1228 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1229 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1230 // set it too high just to maliciously take more fees by exploiting this
1231 // match htlc_minimum_msat logic.
1232 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1233 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1234 // Note that there is a risk that *previous hops* (those closer to us, as we go
1235 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1237 // This might make us end up with a broken route, although this should be super-rare
1238 // in practice, both because of how healthy channels look like, and how we pick
1239 // channels in add_entry.
1240 // Also, this can't be exploited more heavily than *announce a free path and fail
1242 cur_hop_transferred_amount_msat += extra_fees_msat;
1243 total_fee_paid_msat += extra_fees_msat;
1244 cur_hop_fees_msat += extra_fees_msat;
1248 // Final hop is a special case: it usually has just value_msat (by design), but also
1249 // it still could overpay for the htlc_minimum_msat.
1250 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1252 // Propagate updated fees for the use of the channels to one hop back, where they
1253 // will be actually paid (fee_msat). The last hop is handled above separately.
1254 cur_hop.fee_msat = cur_hop_fees_msat;
1257 // Fee for the use of the current hop which will be deducted on the previous hop.
1258 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1259 // this channel is free for us.
1261 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1262 cur_hop.hop_use_fee_msat = new_fee;
1263 total_fee_paid_msat += new_fee;
1265 // It should not be possible because this function is called only to reduce the
1266 // value. In that case, compute_fee was already called with the same fees for
1267 // larger amount and there was no overflow.
1276 /// Calculate the fees required to route the given amount over a channel with the given fees.
1277 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1278 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1279 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1283 /// Calculate the fees required to route the given amount over a channel with the given fees,
1284 /// saturating to [`u64::max_value`].
1285 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1286 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1287 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1288 .saturating_add(channel_fees.base_msat as u64)
1291 /// The default `features` we assume for a node in a route, when no `features` are known about that
1294 /// Default features are:
1295 /// * variable_length_onion_optional
1296 fn default_node_features() -> NodeFeatures {
1297 let mut features = NodeFeatures::empty();
1298 features.set_variable_length_onion_optional();
1302 struct LoggedPayeePubkey(Option<PublicKey>);
1303 impl fmt::Display for LoggedPayeePubkey {
1304 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1307 "payee node id ".fmt(f)?;
1311 "blinded payee".fmt(f)
1317 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1318 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1319 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1321 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1322 "blinded route hint with introduction node id ".fmt(f)?;
1323 hint.1.introduction_node_id.fmt(f)?;
1324 " and blinding point ".fmt(f)?;
1325 hint.1.blinding_point.fmt(f)
1327 CandidateRouteHop::FirstHop { .. } => {
1328 "first hop with SCID ".fmt(f)?;
1329 self.0.short_channel_id().unwrap().fmt(f)
1331 CandidateRouteHop::PrivateHop { .. } => {
1332 "route hint with SCID ".fmt(f)?;
1333 self.0.short_channel_id().unwrap().fmt(f)
1337 self.0.short_channel_id().unwrap().fmt(f)
1344 fn sort_first_hop_channels(
1345 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1346 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1348 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1349 // most like to use.
1351 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1352 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1355 // Second, because simply always sorting in descending order would always use our largest
1356 // available outbound capacity, needlessly fragmenting our available channel capacities,
1357 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1358 // which have enough, but not too much, capacity for the payment.
1360 // Available outbound balances factor in liquidity already reserved for previously found paths.
1361 channels.sort_unstable_by(|chan_a, chan_b| {
1362 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1363 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1364 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1365 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1366 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1367 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1368 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1369 // Sort in descending order
1370 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1372 // Sort in ascending order
1373 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1378 /// Finds a route from us (payer) to the given target node (payee).
1380 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1381 /// in the given [`RouteParameters::payment_params`].
1382 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1384 /// Private routing paths between a public node and the target may be included in the `payee` field
1385 /// of [`RouteParameters::payment_params`].
1387 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1388 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1389 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1391 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1392 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1393 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1397 /// Panics if first_hops contains channels without `short_channel_id`s;
1398 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1400 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1401 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1402 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1403 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1404 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1405 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1406 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1407 ) -> Result<Route, LightningError>
1408 where L::Target: Logger, GL::Target: Logger {
1409 let graph_lock = network_graph.read_only();
1410 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
1411 route_params.final_value_msat, logger, scorer, score_params,
1412 random_seed_bytes)?;
1413 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1417 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1418 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
1419 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, logger: L, scorer: &S, score_params: &S::ScoreParams,
1420 _random_seed_bytes: &[u8; 32]
1421 ) -> Result<Route, LightningError>
1422 where L::Target: Logger {
1423 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1424 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1425 // so use a dummy id for this in the blinded case.
1426 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1427 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1428 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1429 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1430 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1432 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1433 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1436 if final_value_msat > MAX_VALUE_MSAT {
1437 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1440 if final_value_msat == 0 {
1441 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1444 match &payment_params.payee {
1445 Payee::Clear { route_hints, node_id, .. } => {
1446 for route in route_hints.iter() {
1447 for hop in &route.0 {
1448 if hop.src_node_id == *node_id {
1449 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1454 Payee::Blinded { route_hints, .. } => {
1455 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1456 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});
1458 for (_, blinded_path) in route_hints.iter() {
1459 if blinded_path.blinded_hops.len() == 0 {
1460 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1461 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1462 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1463 } else if blinded_path.blinded_hops.len() == 1 &&
1464 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1465 && p.introduction_node_id != blinded_path.introduction_node_id)
1467 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1472 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1473 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1474 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});
1477 // The general routing idea is the following:
1478 // 1. Fill first/last hops communicated by the caller.
1479 // 2. Attempt to construct a path from payer to payee for transferring
1480 // any ~sufficient (described later) value.
1481 // If succeed, remember which channels were used and how much liquidity they have available,
1482 // so that future paths don't rely on the same liquidity.
1483 // 3. Proceed to the next step if:
1484 // - we hit the recommended target value;
1485 // - OR if we could not construct a new path. Any next attempt will fail too.
1486 // Otherwise, repeat step 2.
1487 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1488 // (not recommended value).
1489 // 5. If yes, proceed. If not, fail routing.
1490 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1491 // transferred up to the transfer target value.
1492 // 7. Reduce the value of the last path until we are sending only the target value.
1493 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1494 // them so that we're not sending two HTLCs along the same path.
1496 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1497 // distance from the payee
1499 // We are not a faithful Dijkstra's implementation because we can change values which impact
1500 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1501 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1502 // the value we are currently attempting to send over a path, we simply reduce the value being
1503 // sent along the path for any hops after that channel. This may imply that later fees (which
1504 // we've already tabulated) are lower because a smaller value is passing through the channels
1505 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1506 // channels which were selected earlier (and which may still be used for other paths without a
1507 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1510 // One potentially problematic case for this algorithm would be if there are many
1511 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1512 // graph walking), we may never find a path which is not liquidity-limited and has lower
1513 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1514 // Because we only consider paths with at least 5% of the total value being sent, the damage
1515 // from such a case should be limited, however this could be further reduced in the future by
1516 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1517 // limits for the purposes of fee calculation.
1519 // Alternatively, we could store more detailed path information in the heap (targets, below)
1520 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1521 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1522 // and practically (as we would need to store dynamically-allocated path information in heap
1523 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1524 // results of such an algorithm would likely be biased towards lower-value paths.
1526 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1527 // outside of our current search value, running a path search more times to gather candidate
1528 // paths at different values. While this may be acceptable, further path searches may increase
1529 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1530 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1531 // the same time, remaining generic across different payment values.
1533 let network_channels = network_graph.channels();
1534 let network_nodes = network_graph.nodes();
1536 if payment_params.max_path_count == 0 {
1537 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1540 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1541 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1543 let allow_mpp = if payment_params.max_path_count == 1 {
1545 } else if payment_params.payee.supports_basic_mpp() {
1547 } else if let Some(payee) = payee_node_id_opt {
1548 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1549 |info| info.features.supports_basic_mpp()))
1552 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1553 LoggedPayeePubkey(payment_params.payee.node_id()), if allow_mpp { "with" } else { "without" },
1554 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1557 // Prepare the data we'll use for payee-to-payer search by
1558 // inserting first hops suggested by the caller as targets.
1559 // Our search will then attempt to reach them while traversing from the payee node.
1560 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1561 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1562 if let Some(hops) = first_hops {
1564 if chan.get_outbound_payment_scid().is_none() {
1565 panic!("first_hops should be filled in with usable channels, not pending ones");
1567 if chan.counterparty.node_id == *our_node_pubkey {
1568 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1571 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1572 .or_insert(Vec::new())
1575 if first_hop_targets.is_empty() {
1576 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1580 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1581 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1582 // adding duplicate entries when we find a better path to a given node.
1583 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1585 // Map from node_id to information about the best current path to that node, including feerate
1587 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1589 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1590 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1591 // htlc_minimum with extra fees while still finding a cheaper path.
1592 let mut hit_minimum_limit;
1594 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1595 // We start with a path_value of the exact amount we want, and if that generates a route we may
1596 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1597 // amount we want in total across paths, selecting the best subset at the end.
1598 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1599 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1600 let mut path_value_msat = final_value_msat;
1602 // Routing Fragmentation Mitigation heuristic:
1604 // Routing fragmentation across many payment paths increases the overall routing
1605 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1606 // Taking too many smaller paths also increases the chance of payment failure.
1607 // Thus to avoid this effect, we require from our collected links to provide
1608 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1609 // This requirement is currently set to be 1/max_path_count of the payment
1610 // value to ensure we only ever return routes that do not violate this limit.
1611 let minimal_value_contribution_msat: u64 = if allow_mpp {
1612 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1617 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1618 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1619 // drop the requirement by setting this to 0.
1620 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1622 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1623 // determine if the channel can be used by additional MPP paths or to inform path finding
1624 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1625 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1627 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1628 HashMap::with_capacity(network_nodes.len());
1630 // Keeping track of how much value we already collected across other paths. Helps to decide
1631 // when we want to stop looking for new paths.
1632 let mut already_collected_value_msat = 0;
1634 for (_, channels) in first_hop_targets.iter_mut() {
1635 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1639 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1640 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1642 // Remember how many candidates we ignored to allow for some logging afterwards.
1643 let mut num_ignored_value_contribution = 0;
1644 let mut num_ignored_path_length_limit = 0;
1645 let mut num_ignored_cltv_delta_limit = 0;
1646 let mut num_ignored_previously_failed = 0;
1648 macro_rules! add_entry {
1649 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1650 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1651 // since that value has to be transferred over this channel.
1652 // Returns whether this channel caused an update to `targets`.
1653 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1654 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1655 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1656 // We "return" whether we updated the path at the end, and how much we can route via
1657 // this channel, via this:
1658 let mut did_add_update_path_to_src_node = None;
1659 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1660 // practice these cases should be caught earlier:
1661 // - for regular channels at channel announcement (TODO)
1662 // - for first and last hops early in get_route
1663 if $src_node_id != $dest_node_id {
1664 let scid_opt = $candidate.short_channel_id();
1665 let effective_capacity = $candidate.effective_capacity();
1666 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1668 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1669 // It may be misleading because we might later choose to reduce the value transferred
1670 // over these channels, and the channel which was insufficient might become sufficient.
1671 // Worst case: we drop a good channel here because it can't cover the high following
1672 // fees caused by one expensive channel, but then this channel could have been used
1673 // if the amount being transferred over this path is lower.
1674 // We do this for now, but this is a subject for removal.
1675 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1676 let used_liquidity_msat = used_liquidities
1677 .get(&$candidate.id($src_node_id < $dest_node_id))
1678 .map_or(0, |used_liquidity_msat| {
1679 available_value_contribution_msat = available_value_contribution_msat
1680 .saturating_sub(*used_liquidity_msat);
1681 *used_liquidity_msat
1684 // Verify the liquidity offered by this channel complies to the minimal contribution.
1685 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1686 // Do not consider candidate hops that would exceed the maximum path length.
1687 let path_length_to_node = $next_hops_path_length + 1;
1688 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1690 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1691 // In order to already account for some of the privacy enhancing random CLTV
1692 // expiry delta offset we add on top later, we subtract a rough estimate
1693 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1694 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1695 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1696 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1697 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1698 .saturating_add($candidate.cltv_expiry_delta());
1699 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1701 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1702 // Includes paying fees for the use of the following channels.
1703 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1704 Some(result) => result,
1705 // Can't overflow due to how the values were computed right above.
1706 None => unreachable!(),
1708 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1709 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1710 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1712 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1713 let may_overpay_to_meet_path_minimum_msat =
1714 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1715 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1716 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1717 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1719 let payment_failed_on_this_channel = scid_opt.map_or(false,
1720 |scid| payment_params.previously_failed_channels.contains(&scid));
1722 let should_log_candidate = match $candidate {
1723 CandidateRouteHop::FirstHop { .. } => true,
1724 CandidateRouteHop::PrivateHop { .. } => true,
1725 CandidateRouteHop::Blinded { .. } => true,
1729 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1730 // bother considering this channel. If retrying with recommended_value_msat may
1731 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1732 // around again with a higher amount.
1733 if !contributes_sufficient_value {
1734 if should_log_candidate {
1735 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
1737 num_ignored_value_contribution += 1;
1738 } else if exceeds_max_path_length {
1739 if should_log_candidate {
1740 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
1742 num_ignored_path_length_limit += 1;
1743 } else if exceeds_cltv_delta_limit {
1744 if should_log_candidate {
1745 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
1747 num_ignored_cltv_delta_limit += 1;
1748 } else if payment_failed_on_this_channel {
1749 if should_log_candidate {
1750 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
1752 num_ignored_previously_failed += 1;
1753 } else if may_overpay_to_meet_path_minimum_msat {
1754 hit_minimum_limit = true;
1755 } else if over_path_minimum_msat {
1756 // Note that low contribution here (limited by available_liquidity_msat)
1757 // might violate htlc_minimum_msat on the hops which are next along the
1758 // payment path (upstream to the payee). To avoid that, we recompute
1759 // path fees knowing the final path contribution after constructing it.
1760 let path_htlc_minimum_msat = cmp::max(
1761 compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1762 .saturating_add($next_hops_path_htlc_minimum_msat),
1763 $candidate.htlc_minimum_msat());
1764 let hm_entry = dist.entry($src_node_id);
1765 let old_entry = hm_entry.or_insert_with(|| {
1766 // If there was previously no known way to access the source node
1767 // (recall it goes payee-to-payer) of short_channel_id, first add a
1768 // semi-dummy record just to compute the fees to reach the source node.
1769 // This will affect our decision on selecting short_channel_id
1770 // as a way to reach the $dest_node_id.
1772 node_id: $dest_node_id.clone(),
1773 candidate: $candidate.clone(),
1775 next_hops_fee_msat: u64::max_value(),
1776 hop_use_fee_msat: u64::max_value(),
1777 total_fee_msat: u64::max_value(),
1778 path_htlc_minimum_msat,
1779 path_penalty_msat: u64::max_value(),
1780 was_processed: false,
1781 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1782 value_contribution_msat,
1786 #[allow(unused_mut)] // We only use the mut in cfg(test)
1787 let mut should_process = !old_entry.was_processed;
1788 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1790 // In test/fuzzing builds, we do extra checks to make sure the skipping
1791 // of already-seen nodes only happens in cases we expect (see below).
1792 if !should_process { should_process = true; }
1796 let mut hop_use_fee_msat = 0;
1797 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1799 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1800 // will have the same effective-fee
1801 if $src_node_id != our_node_id {
1802 // Note that `u64::max_value` means we'll always fail the
1803 // `old_entry.total_fee_msat > total_fee_msat` check below
1804 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1805 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1808 let channel_usage = ChannelUsage {
1809 amount_msat: amount_to_transfer_over_msat,
1810 inflight_htlc_msat: used_liquidity_msat,
1813 let channel_penalty_msat = scid_opt.map_or(0,
1814 |scid| scorer.channel_penalty_msat(scid, &$src_node_id, &$dest_node_id,
1815 channel_usage, score_params));
1816 let path_penalty_msat = $next_hops_path_penalty_msat
1817 .saturating_add(channel_penalty_msat);
1818 let new_graph_node = RouteGraphNode {
1819 node_id: $src_node_id,
1820 lowest_fee_to_node: total_fee_msat,
1821 total_cltv_delta: hop_total_cltv_delta,
1822 value_contribution_msat,
1823 path_htlc_minimum_msat,
1825 path_length_to_node,
1828 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1829 // if this way is cheaper than the already known
1830 // (considering the cost to "reach" this channel from the route destination,
1831 // the cost of using this channel,
1832 // and the cost of routing to the source node of this channel).
1833 // Also, consider that htlc_minimum_msat_difference, because we might end up
1834 // paying it. Consider the following exploit:
1835 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1836 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1837 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1838 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1840 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1841 // but it may require additional tracking - we don't want to double-count
1842 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1843 // can't use something that may decrease on future hops.
1844 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1845 .saturating_add(old_entry.path_penalty_msat);
1846 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1847 .saturating_add(path_penalty_msat);
1849 if !old_entry.was_processed && new_cost < old_cost {
1850 targets.push(new_graph_node);
1851 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1852 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1853 old_entry.total_fee_msat = total_fee_msat;
1854 old_entry.node_id = $dest_node_id.clone();
1855 old_entry.candidate = $candidate.clone();
1856 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1857 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1858 old_entry.path_penalty_msat = path_penalty_msat;
1859 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1861 old_entry.value_contribution_msat = value_contribution_msat;
1863 did_add_update_path_to_src_node = Some(value_contribution_msat);
1864 } else if old_entry.was_processed && new_cost < old_cost {
1865 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1867 // If we're skipping processing a node which was previously
1868 // processed even though we found another path to it with a
1869 // cheaper fee, check that it was because the second path we
1870 // found (which we are processing now) has a lower value
1871 // contribution due to an HTLC minimum limit.
1873 // e.g. take a graph with two paths from node 1 to node 2, one
1874 // through channel A, and one through channel B. Channel A and
1875 // B are both in the to-process heap, with their scores set by
1876 // a higher htlc_minimum than fee.
1877 // Channel A is processed first, and the channels onwards from
1878 // node 1 are added to the to-process heap. Thereafter, we pop
1879 // Channel B off of the heap, note that it has a much more
1880 // restrictive htlc_maximum_msat, and recalculate the fees for
1881 // all of node 1's channels using the new, reduced, amount.
1883 // This would be bogus - we'd be selecting a higher-fee path
1884 // with a lower htlc_maximum_msat instead of the one we'd
1885 // already decided to use.
1886 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1888 value_contribution_msat + path_penalty_msat <
1889 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1897 did_add_update_path_to_src_node
1901 let default_node_features = default_node_features();
1903 // Find ways (channels with destination) to reach a given node and store them
1904 // in the corresponding data structures (routing graph etc).
1905 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1906 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1907 // This data can later be helpful to optimize routing (pay lower fees).
1908 macro_rules! add_entries_to_cheapest_to_target_node {
1909 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1910 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1911 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1912 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1913 let was_processed = elem.was_processed;
1914 elem.was_processed = true;
1917 // Entries are added to dist in add_entry!() when there is a channel from a node.
1918 // Because there are no channels from payee, it will not have a dist entry at this point.
1919 // If we're processing any other node, it is always be the result of a channel from it.
1920 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
1925 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1926 for details in first_channels {
1927 let candidate = CandidateRouteHop::FirstHop { details };
1928 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1929 $next_hops_value_contribution,
1930 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1931 $next_hops_cltv_delta, $next_hops_path_length);
1935 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1938 &default_node_features
1941 if !features.requires_unknown_bits() {
1942 for chan_id in $node.channels.iter() {
1943 let chan = network_channels.get(chan_id).unwrap();
1944 if !chan.features.requires_unknown_bits() {
1945 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1946 if first_hops.is_none() || *source != our_node_id {
1947 if directed_channel.direction().enabled {
1948 let candidate = CandidateRouteHop::PublicHop {
1949 info: directed_channel,
1950 short_channel_id: *chan_id,
1952 add_entry!(candidate, *source, $node_id,
1953 $fee_to_target_msat,
1954 $next_hops_value_contribution,
1955 $next_hops_path_htlc_minimum_msat,
1956 $next_hops_path_penalty_msat,
1957 $next_hops_cltv_delta, $next_hops_path_length);
1968 let mut payment_paths = Vec::<PaymentPath>::new();
1970 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1971 'paths_collection: loop {
1972 // For every new path, start from scratch, except for used_liquidities, which
1973 // helps to avoid reusing previously selected paths in future iterations.
1976 hit_minimum_limit = false;
1978 // If first hop is a private channel and the only way to reach the payee, this is the only
1979 // place where it could be added.
1980 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
1981 for details in first_channels {
1982 let candidate = CandidateRouteHop::FirstHop { details };
1983 let added = add_entry!(candidate, our_node_id, payee, 0, path_value_msat,
1984 0, 0u64, 0, 0).is_some();
1985 log_trace!(logger, "{} direct route to payee via {}",
1986 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
1990 // Add the payee as a target, so that the payee-to-payer
1991 // search algorithm knows what to start with.
1992 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
1993 // The payee is not in our network graph, so nothing to add here.
1994 // There is still a chance of reaching them via last_hops though,
1995 // so don't yet fail the payment here.
1996 // If not, targets.pop() will not even let us enter the loop in step 2.
1999 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
2004 // If a caller provided us with last hops, add them to routing targets. Since this happens
2005 // earlier than general path finding, they will be somewhat prioritized, although currently
2006 // it matters only if the fees are exactly the same.
2007 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2008 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2009 let have_intro_node_in_graph =
2010 // Only add the hops in this route to our candidate set if either
2011 // we have a direct channel to the first hop or the first hop is
2012 // in the regular network graph.
2013 first_hop_targets.get(&intro_node_id).is_some() ||
2014 network_nodes.get(&intro_node_id).is_some();
2015 if !have_intro_node_in_graph { continue }
2016 let candidate = if hint.1.blinded_hops.len() == 1 {
2017 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
2018 } else { CandidateRouteHop::Blinded { hint, hint_idx } };
2019 let mut path_contribution_msat = path_value_msat;
2020 if let Some(hop_used_msat) = add_entry!(candidate, intro_node_id, maybe_dummy_payee_node_id,
2021 0, path_contribution_msat, 0, 0_u64, 0, 0)
2023 path_contribution_msat = hop_used_msat;
2025 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2026 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2028 for details in first_channels {
2029 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2030 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2034 add_entry!(first_hop_candidate, our_node_id, intro_node_id, blinded_path_fee,
2035 path_contribution_msat, candidate.htlc_minimum_msat(), 0_u64,
2036 candidate.cltv_expiry_delta(),
2037 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2041 for route in payment_params.payee.unblinded_route_hints().iter()
2042 .filter(|route| !route.0.is_empty())
2044 let first_hop_in_route = &(route.0)[0];
2045 let have_hop_src_in_graph =
2046 // Only add the hops in this route to our candidate set if either
2047 // we have a direct channel to the first hop or the first hop is
2048 // in the regular network graph.
2049 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
2050 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
2051 if have_hop_src_in_graph {
2052 // We start building the path from reverse, i.e., from payee
2053 // to the first RouteHintHop in the path.
2054 let hop_iter = route.0.iter().rev();
2055 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2056 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2057 let mut hop_used = true;
2058 let mut aggregate_next_hops_fee_msat: u64 = 0;
2059 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2060 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2061 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2062 let mut aggregate_next_hops_path_length: u8 = 0;
2063 let mut aggregate_path_contribution_msat = path_value_msat;
2065 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2066 let source = NodeId::from_pubkey(&hop.src_node_id);
2067 let target = NodeId::from_pubkey(&prev_hop_id);
2068 let candidate = network_channels
2069 .get(&hop.short_channel_id)
2070 .and_then(|channel| channel.as_directed_to(&target))
2071 .map(|(info, _)| CandidateRouteHop::PublicHop {
2073 short_channel_id: hop.short_channel_id,
2075 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
2077 if let Some(hop_used_msat) = add_entry!(candidate, source, target,
2078 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2079 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2080 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2082 aggregate_path_contribution_msat = hop_used_msat;
2084 // If this hop was not used then there is no use checking the preceding
2085 // hops in the RouteHint. We can break by just searching for a direct
2086 // channel between last checked hop and first_hop_targets.
2090 let used_liquidity_msat = used_liquidities
2091 .get(&candidate.id(source < target)).copied()
2093 let channel_usage = ChannelUsage {
2094 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2095 inflight_htlc_msat: used_liquidity_msat,
2096 effective_capacity: candidate.effective_capacity(),
2098 let channel_penalty_msat = scorer.channel_penalty_msat(
2099 hop.short_channel_id, &source, &target, channel_usage, score_params
2101 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2102 .saturating_add(channel_penalty_msat);
2104 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2105 .saturating_add(hop.cltv_expiry_delta as u32);
2107 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2110 // Searching for a direct channel between last checked hop and first_hop_targets
2111 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&prev_hop_id)) {
2112 sort_first_hop_channels(first_channels, &used_liquidities,
2113 recommended_value_msat, our_node_pubkey);
2114 for details in first_channels {
2115 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2116 add_entry!(first_hop_candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
2117 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2118 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2119 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2127 // In the next values of the iterator, the aggregate fees already reflects
2128 // the sum of value sent from payer (final_value_msat) and routing fees
2129 // for the last node in the RouteHint. We need to just add the fees to
2130 // route through the current node so that the preceding node (next iteration)
2132 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2133 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2134 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2136 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
2137 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
2138 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
2139 .checked_add(hop_htlc_minimum_msat_inc);
2140 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
2142 if idx == route.0.len() - 1 {
2143 // The last hop in this iterator is the first hop in
2144 // overall RouteHint.
2145 // If this hop connects to a node with which we have a direct channel,
2146 // ignore the network graph and, if the last hop was added, add our
2147 // direct channel to the candidate set.
2149 // Note that we *must* check if the last hop was added as `add_entry`
2150 // always assumes that the third argument is a node to which we have a
2152 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2153 sort_first_hop_channels(first_channels, &used_liquidities,
2154 recommended_value_msat, our_node_pubkey);
2155 for details in first_channels {
2156 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2157 add_entry!(first_hop_candidate, our_node_id,
2158 NodeId::from_pubkey(&hop.src_node_id),
2159 aggregate_next_hops_fee_msat,
2160 aggregate_path_contribution_msat,
2161 aggregate_next_hops_path_htlc_minimum_msat,
2162 aggregate_next_hops_path_penalty_msat,
2163 aggregate_next_hops_cltv_delta,
2164 aggregate_next_hops_path_length);
2172 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2174 // At this point, targets are filled with the data from first and
2175 // last hops communicated by the caller, and the payment receiver.
2176 let mut found_new_path = false;
2179 // If this loop terminates due the exhaustion of targets, two situations are possible:
2180 // - not enough outgoing liquidity:
2181 // 0 < already_collected_value_msat < final_value_msat
2182 // - enough outgoing liquidity:
2183 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2184 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2185 // paths_collection will be stopped because found_new_path==false.
2186 // This is not necessarily a routing failure.
2187 '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() {
2189 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2190 // traversing the graph and arrange the path out of what we found.
2191 if node_id == our_node_id {
2192 let mut new_entry = dist.remove(&our_node_id).unwrap();
2193 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2196 let mut features_set = false;
2197 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
2198 for details in first_channels {
2199 if let Some(scid) = ordered_hops.last().unwrap().0.candidate.short_channel_id() {
2200 if details.get_outbound_payment_scid().unwrap() == scid {
2201 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2202 features_set = true;
2209 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
2210 if let Some(node_info) = node.announcement_info.as_ref() {
2211 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2213 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2216 // We can fill in features for everything except hops which were
2217 // provided via the invoice we're paying. We could guess based on the
2218 // recipient's features but for now we simply avoid guessing at all.
2222 // Means we succesfully traversed from the payer to the payee, now
2223 // save this path for the payment route. Also, update the liquidity
2224 // remaining on the used hops, so that we take them into account
2225 // while looking for more paths.
2226 if ordered_hops.last().unwrap().0.node_id == maybe_dummy_payee_node_id {
2230 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
2231 Some(payment_hop) => payment_hop,
2232 // We can't arrive at None because, if we ever add an entry to targets,
2233 // we also fill in the entry in dist (see add_entry!).
2234 None => unreachable!(),
2236 // We "propagate" the fees one hop backward (topologically) here,
2237 // so that fees paid for a HTLC forwarding on the current channel are
2238 // associated with the previous channel (where they will be subtracted).
2239 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2240 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2242 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2243 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2245 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2246 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2248 let mut payment_path = PaymentPath {hops: ordered_hops};
2250 // We could have possibly constructed a slightly inconsistent path: since we reduce
2251 // value being transferred along the way, we could have violated htlc_minimum_msat
2252 // on some channels we already passed (assuming dest->source direction). Here, we
2253 // recompute the fees again, so that if that's the case, we match the currently
2254 // underpaid htlc_minimum_msat with fees.
2255 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2256 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
2257 payment_path.update_value_and_recompute_fees(value_contribution_msat);
2259 // Since a path allows to transfer as much value as
2260 // the smallest channel it has ("bottleneck"), we should recompute
2261 // the fees so sender HTLC don't overpay fees when traversing
2262 // larger channels than the bottleneck. This may happen because
2263 // when we were selecting those channels we were not aware how much value
2264 // this path will transfer, and the relative fee for them
2265 // might have been computed considering a larger value.
2266 // Remember that we used these channels so that we don't rely
2267 // on the same liquidity in future paths.
2268 let mut prevented_redundant_path_selection = false;
2269 let prev_hop_iter = core::iter::once(&our_node_id)
2270 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
2271 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
2272 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2273 let used_liquidity_msat = used_liquidities
2274 .entry(hop.candidate.id(*prev_hop < hop.node_id))
2275 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2276 .or_insert(spent_on_hop_msat);
2277 let hop_capacity = hop.candidate.effective_capacity();
2278 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2279 if *used_liquidity_msat == hop_max_msat {
2280 // If this path used all of this channel's available liquidity, we know
2281 // this path will not be selected again in the next loop iteration.
2282 prevented_redundant_path_selection = true;
2284 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2286 if !prevented_redundant_path_selection {
2287 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2288 // we'll probably end up picking the same path again on the next iteration.
2289 // Decrease the available liquidity of a hop in the middle of the path.
2290 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2291 let exhausted = u64::max_value();
2292 log_trace!(logger, "Disabling route candidate {} for future path building iterations to
2293 avoid duplicates.", LoggedCandidateHop(victim_candidate));
2294 *used_liquidities.entry(victim_candidate.id(false)).or_default() = exhausted;
2295 *used_liquidities.entry(victim_candidate.id(true)).or_default() = exhausted;
2298 // Track the total amount all our collected paths allow to send so that we know
2299 // when to stop looking for more paths
2300 already_collected_value_msat += value_contribution_msat;
2302 payment_paths.push(payment_path);
2303 found_new_path = true;
2304 break 'path_construction;
2307 // If we found a path back to the payee, we shouldn't try to process it again. This is
2308 // the equivalent of the `elem.was_processed` check in
2309 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2310 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2312 // Otherwise, since the current target node is not us,
2313 // keep "unrolling" the payment graph from payee to payer by
2314 // finding a way to reach the current target from the payer side.
2315 match network_nodes.get(&node_id) {
2318 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2319 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2320 total_cltv_delta, path_length_to_node);
2326 if !found_new_path && channel_saturation_pow_half != 0 {
2327 channel_saturation_pow_half = 0;
2328 continue 'paths_collection;
2330 // If we don't support MPP, no use trying to gather more value ever.
2331 break 'paths_collection;
2335 // Stop either when the recommended value is reached or if no new path was found in this
2337 // In the latter case, making another path finding attempt won't help,
2338 // because we deterministically terminated the search due to low liquidity.
2339 if !found_new_path && channel_saturation_pow_half != 0 {
2340 channel_saturation_pow_half = 0;
2341 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2342 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2343 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2344 break 'paths_collection;
2345 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2346 // Further, if this was our first walk of the graph, and we weren't limited by an
2347 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2348 // limited by an htlc_minimum_msat value, find another path with a higher value,
2349 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2350 // still keeping a lower total fee than this path.
2351 if !hit_minimum_limit {
2352 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2353 break 'paths_collection;
2355 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
2356 path_value_msat = recommended_value_msat;
2360 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2361 num_ignored_cltv_delta_limit + num_ignored_previously_failed;
2362 if num_ignored_total > 0 {
2363 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);
2367 if payment_paths.len() == 0 {
2368 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2371 if already_collected_value_msat < final_value_msat {
2372 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2376 let mut selected_route = payment_paths;
2378 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2379 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2381 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2382 // the value they contribute towards the payment amount.
2383 // We sort in descending order as we will remove from the front in `retain`, next.
2384 selected_route.sort_unstable_by(|a, b|
2385 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2386 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2389 // We should make sure that at least 1 path left.
2390 let mut paths_left = selected_route.len();
2391 selected_route.retain(|path| {
2392 if paths_left == 1 {
2395 let path_value_msat = path.get_value_msat();
2396 if path_value_msat <= overpaid_value_msat {
2397 overpaid_value_msat -= path_value_msat;
2403 debug_assert!(selected_route.len() > 0);
2405 if overpaid_value_msat != 0 {
2407 // Now, subtract the remaining overpaid value from the most-expensive path.
2408 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2409 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2410 selected_route.sort_unstable_by(|a, b| {
2411 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2412 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2413 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2415 let expensive_payment_path = selected_route.first_mut().unwrap();
2417 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2418 // can't go negative.
2419 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2420 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2424 // Sort by the path itself and combine redundant paths.
2425 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2426 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2428 selected_route.sort_unstable_by_key(|path| {
2429 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2430 debug_assert!(path.hops.len() <= key.len());
2431 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id(true)).zip(key.iter_mut()) {
2436 for idx in 0..(selected_route.len() - 1) {
2437 if idx + 1 >= selected_route.len() { break; }
2438 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id)),
2439 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id))) {
2440 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2441 selected_route[idx].update_value_and_recompute_fees(new_value);
2442 selected_route.remove(idx + 1);
2446 let mut paths = Vec::new();
2447 for payment_path in selected_route {
2448 let mut hops = Vec::with_capacity(payment_path.hops.len());
2449 for (hop, node_features) in payment_path.hops.iter()
2450 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2452 hops.push(RouteHop {
2453 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)})?,
2454 node_features: node_features.clone(),
2455 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2456 channel_features: hop.candidate.features(),
2457 fee_msat: hop.fee_msat,
2458 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2461 let mut final_cltv_delta = final_cltv_expiry_delta;
2462 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2463 if let Some(blinded_path) = h.candidate.blinded_path() {
2464 final_cltv_delta = h.candidate.cltv_expiry_delta();
2466 hops: blinded_path.blinded_hops.clone(),
2467 blinding_point: blinded_path.blinding_point,
2468 excess_final_cltv_expiry_delta: 0,
2469 final_value_msat: h.fee_msat,
2473 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2474 // applicable for the previous hop.
2475 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2476 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2479 paths.push(Path { hops, blinded_tail });
2481 // Make sure we would never create a route with more paths than we allow.
2482 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2484 if let Some(node_features) = payment_params.payee.node_features() {
2485 for path in paths.iter_mut() {
2486 path.hops.last_mut().unwrap().node_features = node_features.clone();
2490 let route = Route { paths, payment_params: Some(payment_params.clone()) };
2491 log_info!(logger, "Got route: {}", log_route!(route));
2495 // When an adversarial intermediary node observes a payment, it may be able to infer its
2496 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2497 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2498 // payment path by adding a randomized 'shadow route' offset to the final hop.
2499 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2500 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2502 let network_channels = network_graph.channels();
2503 let network_nodes = network_graph.nodes();
2505 for path in route.paths.iter_mut() {
2506 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2508 // Remember the last three nodes of the random walk and avoid looping back on them.
2509 // Init with the last three nodes from the actual path, if possible.
2510 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2511 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2512 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2514 // Choose the last publicly known node as the starting point for the random walk.
2515 let mut cur_hop: Option<NodeId> = None;
2516 let mut path_nonce = [0u8; 12];
2517 if let Some(starting_hop) = path.hops.iter().rev()
2518 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2519 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2520 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2523 // Init PRNG with the path-dependant nonce, which is static for private paths.
2524 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2525 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2527 // Pick a random path length in [1 .. 3]
2528 prng.process_in_place(&mut random_path_bytes);
2529 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2531 for random_hop in 0..random_walk_length {
2532 // If we don't find a suitable offset in the public network graph, we default to
2533 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2534 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2536 if let Some(cur_node_id) = cur_hop {
2537 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2538 // Randomly choose the next unvisited hop.
2539 prng.process_in_place(&mut random_path_bytes);
2540 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2541 .checked_rem(cur_node.channels.len())
2542 .and_then(|index| cur_node.channels.get(index))
2543 .and_then(|id| network_channels.get(id)) {
2544 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2545 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2546 nodes_to_avoid[random_hop] = *next_id;
2547 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2548 cur_hop = Some(*next_id);
2555 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2556 .checked_add(random_hop_offset)
2557 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2560 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2561 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2562 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2564 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2565 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2566 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2567 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2568 max_path_offset = cmp::max(
2569 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2570 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2571 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2573 // Add 'shadow' CLTV offset to the final hop
2574 if let Some(tail) = path.blinded_tail.as_mut() {
2575 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2576 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2578 if let Some(last_hop) = path.hops.last_mut() {
2579 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2580 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2585 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2586 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2588 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2589 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2590 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2591 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2592 ) -> Result<Route, LightningError>
2593 where L::Target: Logger, GL::Target: Logger {
2594 let graph_lock = network_graph.read_only();
2595 let mut route = build_route_from_hops_internal(
2596 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
2597 route_params.final_value_msat, logger, random_seed_bytes)?;
2598 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2602 fn build_route_from_hops_internal<L: Deref>(
2603 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
2604 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, logger: L,
2605 random_seed_bytes: &[u8; 32]
2606 ) -> Result<Route, LightningError> where L::Target: Logger {
2609 our_node_id: NodeId,
2610 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2613 impl ScoreLookUp for HopScorer {
2614 type ScoreParams = ();
2615 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2616 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2618 let mut cur_id = self.our_node_id;
2619 for i in 0..self.hop_ids.len() {
2620 if let Some(next_id) = self.hop_ids[i] {
2621 if cur_id == *source && next_id == *target {
2633 impl<'a> Writeable for HopScorer {
2635 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2640 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2641 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2644 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2645 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2646 for i in 0..hops.len() {
2647 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2650 let scorer = HopScorer { our_node_id, hop_ids };
2652 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
2653 logger, &scorer, &(), random_seed_bytes)
2658 use crate::blinded_path::{BlindedHop, BlindedPath};
2659 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2660 use crate::routing::utxo::UtxoResult;
2661 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2662 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2663 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
2664 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2665 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2666 use crate::chain::transaction::OutPoint;
2667 use crate::sign::EntropySource;
2668 use crate::ln::ChannelId;
2669 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2670 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2671 use crate::ln::channelmanager;
2672 use crate::offers::invoice::BlindedPayInfo;
2673 use crate::util::config::UserConfig;
2674 use crate::util::test_utils as ln_test_utils;
2675 use crate::util::chacha20::ChaCha20;
2676 use crate::util::ser::{Readable, Writeable};
2678 use crate::util::ser::Writer;
2680 use bitcoin::hashes::Hash;
2681 use bitcoin::network::constants::Network;
2682 use bitcoin::blockdata::constants::genesis_block;
2683 use bitcoin::blockdata::script::Builder;
2684 use bitcoin::blockdata::opcodes;
2685 use bitcoin::blockdata::transaction::TxOut;
2689 use bitcoin::secp256k1::{PublicKey,SecretKey};
2690 use bitcoin::secp256k1::Secp256k1;
2692 use crate::io::Cursor;
2693 use crate::prelude::*;
2694 use crate::sync::Arc;
2696 use core::convert::TryInto;
2698 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2699 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2700 channelmanager::ChannelDetails {
2701 channel_id: ChannelId::new_zero(),
2702 counterparty: channelmanager::ChannelCounterparty {
2705 unspendable_punishment_reserve: 0,
2706 forwarding_info: None,
2707 outbound_htlc_minimum_msat: None,
2708 outbound_htlc_maximum_msat: None,
2710 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2713 outbound_scid_alias: None,
2714 inbound_scid_alias: None,
2715 channel_value_satoshis: 0,
2717 outbound_capacity_msat,
2718 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2719 next_outbound_htlc_minimum_msat: 0,
2720 inbound_capacity_msat: 42,
2721 unspendable_punishment_reserve: None,
2722 confirmations_required: None,
2723 confirmations: None,
2724 force_close_spend_delay: None,
2725 is_outbound: true, is_channel_ready: true,
2726 is_usable: true, is_public: true,
2727 inbound_htlc_minimum_msat: None,
2728 inbound_htlc_maximum_msat: None,
2730 feerate_sat_per_1000_weight: None,
2731 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
2736 fn simple_route_test() {
2737 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2738 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2739 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2740 let scorer = ln_test_utils::TestScorer::new();
2741 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2742 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2744 // Simple route to 2 via 1
2746 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) {
2747 assert_eq!(err, "Cannot send a payment of 0 msat");
2748 } else { panic!(); }
2750 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2751 assert_eq!(route.paths[0].hops.len(), 2);
2753 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2754 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2755 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2756 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2757 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2758 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2760 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2761 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2762 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2763 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2764 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2765 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2769 fn invalid_first_hop_test() {
2770 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2771 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2772 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2773 let scorer = ln_test_utils::TestScorer::new();
2774 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2775 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2777 // Simple route to 2 via 1
2779 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2781 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2782 get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2783 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2784 } else { panic!(); }
2786 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2787 assert_eq!(route.paths[0].hops.len(), 2);
2791 fn htlc_minimum_test() {
2792 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2793 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2794 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2795 let scorer = ln_test_utils::TestScorer::new();
2796 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2797 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2799 // Simple route to 2 via 1
2801 // Disable other paths
2802 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2803 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2804 short_channel_id: 12,
2806 flags: 2, // to disable
2807 cltv_expiry_delta: 0,
2808 htlc_minimum_msat: 0,
2809 htlc_maximum_msat: MAX_VALUE_MSAT,
2811 fee_proportional_millionths: 0,
2812 excess_data: Vec::new()
2814 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2815 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2816 short_channel_id: 3,
2818 flags: 2, // to disable
2819 cltv_expiry_delta: 0,
2820 htlc_minimum_msat: 0,
2821 htlc_maximum_msat: MAX_VALUE_MSAT,
2823 fee_proportional_millionths: 0,
2824 excess_data: Vec::new()
2826 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2827 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2828 short_channel_id: 13,
2830 flags: 2, // to disable
2831 cltv_expiry_delta: 0,
2832 htlc_minimum_msat: 0,
2833 htlc_maximum_msat: MAX_VALUE_MSAT,
2835 fee_proportional_millionths: 0,
2836 excess_data: Vec::new()
2838 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2839 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2840 short_channel_id: 6,
2842 flags: 2, // to disable
2843 cltv_expiry_delta: 0,
2844 htlc_minimum_msat: 0,
2845 htlc_maximum_msat: MAX_VALUE_MSAT,
2847 fee_proportional_millionths: 0,
2848 excess_data: Vec::new()
2850 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2851 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2852 short_channel_id: 7,
2854 flags: 2, // to disable
2855 cltv_expiry_delta: 0,
2856 htlc_minimum_msat: 0,
2857 htlc_maximum_msat: MAX_VALUE_MSAT,
2859 fee_proportional_millionths: 0,
2860 excess_data: Vec::new()
2863 // Check against amount_to_transfer_over_msat.
2864 // Set minimal HTLC of 200_000_000 msat.
2865 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2866 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2867 short_channel_id: 2,
2870 cltv_expiry_delta: 0,
2871 htlc_minimum_msat: 200_000_000,
2872 htlc_maximum_msat: MAX_VALUE_MSAT,
2874 fee_proportional_millionths: 0,
2875 excess_data: Vec::new()
2878 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2880 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2881 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2882 short_channel_id: 4,
2885 cltv_expiry_delta: 0,
2886 htlc_minimum_msat: 0,
2887 htlc_maximum_msat: 199_999_999,
2889 fee_proportional_millionths: 0,
2890 excess_data: Vec::new()
2893 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2894 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) {
2895 assert_eq!(err, "Failed to find a path to the given destination");
2896 } else { panic!(); }
2898 // Lift the restriction on the first hop.
2899 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2900 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2901 short_channel_id: 2,
2904 cltv_expiry_delta: 0,
2905 htlc_minimum_msat: 0,
2906 htlc_maximum_msat: MAX_VALUE_MSAT,
2908 fee_proportional_millionths: 0,
2909 excess_data: Vec::new()
2912 // A payment above the minimum should pass
2913 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 199_999_999, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2914 assert_eq!(route.paths[0].hops.len(), 2);
2918 fn htlc_minimum_overpay_test() {
2919 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2920 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2921 let config = UserConfig::default();
2922 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
2923 let scorer = ln_test_utils::TestScorer::new();
2924 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2925 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2927 // A route to node#2 via two paths.
2928 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2929 // Thus, they can't send 60 without overpaying.
2930 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2931 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2932 short_channel_id: 2,
2935 cltv_expiry_delta: 0,
2936 htlc_minimum_msat: 35_000,
2937 htlc_maximum_msat: 40_000,
2939 fee_proportional_millionths: 0,
2940 excess_data: Vec::new()
2942 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2943 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2944 short_channel_id: 12,
2947 cltv_expiry_delta: 0,
2948 htlc_minimum_msat: 35_000,
2949 htlc_maximum_msat: 40_000,
2951 fee_proportional_millionths: 0,
2952 excess_data: Vec::new()
2956 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2957 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2958 short_channel_id: 13,
2961 cltv_expiry_delta: 0,
2962 htlc_minimum_msat: 0,
2963 htlc_maximum_msat: MAX_VALUE_MSAT,
2965 fee_proportional_millionths: 0,
2966 excess_data: Vec::new()
2968 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2969 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2970 short_channel_id: 4,
2973 cltv_expiry_delta: 0,
2974 htlc_minimum_msat: 0,
2975 htlc_maximum_msat: MAX_VALUE_MSAT,
2977 fee_proportional_millionths: 0,
2978 excess_data: Vec::new()
2981 // Disable other paths
2982 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2983 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2984 short_channel_id: 1,
2986 flags: 2, // to disable
2987 cltv_expiry_delta: 0,
2988 htlc_minimum_msat: 0,
2989 htlc_maximum_msat: MAX_VALUE_MSAT,
2991 fee_proportional_millionths: 0,
2992 excess_data: Vec::new()
2995 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2996 // Overpay fees to hit htlc_minimum_msat.
2997 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
2998 // TODO: this could be better balanced to overpay 10k and not 15k.
2999 assert_eq!(overpaid_fees, 15_000);
3001 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3002 // while taking even more fee to match htlc_minimum_msat.
3003 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3004 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3005 short_channel_id: 12,
3008 cltv_expiry_delta: 0,
3009 htlc_minimum_msat: 65_000,
3010 htlc_maximum_msat: 80_000,
3012 fee_proportional_millionths: 0,
3013 excess_data: Vec::new()
3015 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3016 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3017 short_channel_id: 2,
3020 cltv_expiry_delta: 0,
3021 htlc_minimum_msat: 0,
3022 htlc_maximum_msat: MAX_VALUE_MSAT,
3024 fee_proportional_millionths: 0,
3025 excess_data: Vec::new()
3027 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3028 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3029 short_channel_id: 4,
3032 cltv_expiry_delta: 0,
3033 htlc_minimum_msat: 0,
3034 htlc_maximum_msat: MAX_VALUE_MSAT,
3036 fee_proportional_millionths: 100_000,
3037 excess_data: Vec::new()
3040 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3041 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3042 assert_eq!(route.paths.len(), 1);
3043 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3044 let fees = route.paths[0].hops[0].fee_msat;
3045 assert_eq!(fees, 5_000);
3047 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3048 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3049 // the other channel.
3050 assert_eq!(route.paths.len(), 1);
3051 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3052 let fees = route.paths[0].hops[0].fee_msat;
3053 assert_eq!(fees, 5_000);
3057 fn disable_channels_test() {
3058 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3059 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3060 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3061 let scorer = ln_test_utils::TestScorer::new();
3062 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3063 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3065 // // Disable channels 4 and 12 by flags=2
3066 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3067 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3068 short_channel_id: 4,
3070 flags: 2, // to disable
3071 cltv_expiry_delta: 0,
3072 htlc_minimum_msat: 0,
3073 htlc_maximum_msat: MAX_VALUE_MSAT,
3075 fee_proportional_millionths: 0,
3076 excess_data: Vec::new()
3078 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3079 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3080 short_channel_id: 12,
3082 flags: 2, // to disable
3083 cltv_expiry_delta: 0,
3084 htlc_minimum_msat: 0,
3085 htlc_maximum_msat: MAX_VALUE_MSAT,
3087 fee_proportional_millionths: 0,
3088 excess_data: Vec::new()
3091 // If all the channels require some features we don't understand, route should fail
3092 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) {
3093 assert_eq!(err, "Failed to find a path to the given destination");
3094 } else { panic!(); }
3096 // If we specify a channel to node7, that overrides our local channel view and that gets used
3097 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3098 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();
3099 assert_eq!(route.paths[0].hops.len(), 2);
3101 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3102 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3103 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3104 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3105 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3106 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3108 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3109 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3110 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3111 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3112 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3113 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3117 fn disable_node_test() {
3118 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3119 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3120 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3121 let scorer = ln_test_utils::TestScorer::new();
3122 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3123 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3125 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3126 let mut unknown_features = NodeFeatures::empty();
3127 unknown_features.set_unknown_feature_required();
3128 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3129 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3130 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3132 // If all nodes require some features we don't understand, route should fail
3133 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) {
3134 assert_eq!(err, "Failed to find a path to the given destination");
3135 } else { panic!(); }
3137 // If we specify a channel to node7, that overrides our local channel view and that gets used
3138 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3139 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();
3140 assert_eq!(route.paths[0].hops.len(), 2);
3142 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3143 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3144 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3145 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3146 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3147 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3149 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3150 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3151 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3152 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3153 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3154 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3156 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3157 // naively) assume that the user checked the feature bits on the invoice, which override
3158 // the node_announcement.
3162 fn our_chans_test() {
3163 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3164 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3165 let scorer = ln_test_utils::TestScorer::new();
3166 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3167 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3169 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3170 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3171 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3172 assert_eq!(route.paths[0].hops.len(), 3);
3174 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3175 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3176 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3177 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3178 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3179 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3181 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3182 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3183 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3184 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3185 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3186 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3188 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3189 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3190 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3191 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3192 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3193 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3195 // If we specify a channel to node7, that overrides our local channel view and that gets used
3196 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3197 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3198 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();
3199 assert_eq!(route.paths[0].hops.len(), 2);
3201 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3202 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3203 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3204 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3205 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3206 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3208 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3209 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3210 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3211 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3212 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3213 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3216 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3217 let zero_fees = RoutingFees {
3219 proportional_millionths: 0,
3221 vec![RouteHint(vec![RouteHintHop {
3222 src_node_id: nodes[3],
3223 short_channel_id: 8,
3225 cltv_expiry_delta: (8 << 4) | 1,
3226 htlc_minimum_msat: None,
3227 htlc_maximum_msat: None,
3229 ]), RouteHint(vec![RouteHintHop {
3230 src_node_id: nodes[4],
3231 short_channel_id: 9,
3234 proportional_millionths: 0,
3236 cltv_expiry_delta: (9 << 4) | 1,
3237 htlc_minimum_msat: None,
3238 htlc_maximum_msat: None,
3239 }]), RouteHint(vec![RouteHintHop {
3240 src_node_id: nodes[5],
3241 short_channel_id: 10,
3243 cltv_expiry_delta: (10 << 4) | 1,
3244 htlc_minimum_msat: None,
3245 htlc_maximum_msat: None,
3249 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3250 let zero_fees = RoutingFees {
3252 proportional_millionths: 0,
3254 vec![RouteHint(vec![RouteHintHop {
3255 src_node_id: nodes[2],
3256 short_channel_id: 5,
3259 proportional_millionths: 0,
3261 cltv_expiry_delta: (5 << 4) | 1,
3262 htlc_minimum_msat: None,
3263 htlc_maximum_msat: None,
3265 src_node_id: nodes[3],
3266 short_channel_id: 8,
3268 cltv_expiry_delta: (8 << 4) | 1,
3269 htlc_minimum_msat: None,
3270 htlc_maximum_msat: None,
3272 ]), RouteHint(vec![RouteHintHop {
3273 src_node_id: nodes[4],
3274 short_channel_id: 9,
3277 proportional_millionths: 0,
3279 cltv_expiry_delta: (9 << 4) | 1,
3280 htlc_minimum_msat: None,
3281 htlc_maximum_msat: None,
3282 }]), RouteHint(vec![RouteHintHop {
3283 src_node_id: nodes[5],
3284 short_channel_id: 10,
3286 cltv_expiry_delta: (10 << 4) | 1,
3287 htlc_minimum_msat: None,
3288 htlc_maximum_msat: None,
3293 fn partial_route_hint_test() {
3294 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3295 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3296 let scorer = ln_test_utils::TestScorer::new();
3297 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3298 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3300 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3301 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3302 // RouteHint may be partially used by the algo to build the best path.
3304 // First check that last hop can't have its source as the payee.
3305 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3306 src_node_id: nodes[6],
3307 short_channel_id: 8,
3310 proportional_millionths: 0,
3312 cltv_expiry_delta: (8 << 4) | 1,
3313 htlc_minimum_msat: None,
3314 htlc_maximum_msat: None,
3317 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3318 invalid_last_hops.push(invalid_last_hop);
3320 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(invalid_last_hops).unwrap();
3321 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) {
3322 assert_eq!(err, "Route hint cannot have the payee as the source.");
3323 } else { panic!(); }
3326 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3327 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3328 assert_eq!(route.paths[0].hops.len(), 5);
3330 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3331 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3332 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3333 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3334 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3335 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3337 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3338 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3339 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3340 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3341 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3342 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3344 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3345 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3346 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3347 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3348 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3349 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3351 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3352 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3353 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3354 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3355 // If we have a peer in the node map, we'll use their features here since we don't have
3356 // a way of figuring out their features from the invoice:
3357 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3358 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3360 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3361 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3362 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3363 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3364 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3365 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3368 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3369 let zero_fees = RoutingFees {
3371 proportional_millionths: 0,
3373 vec![RouteHint(vec![RouteHintHop {
3374 src_node_id: nodes[3],
3375 short_channel_id: 8,
3377 cltv_expiry_delta: (8 << 4) | 1,
3378 htlc_minimum_msat: None,
3379 htlc_maximum_msat: None,
3380 }]), RouteHint(vec![
3382 ]), RouteHint(vec![RouteHintHop {
3383 src_node_id: nodes[5],
3384 short_channel_id: 10,
3386 cltv_expiry_delta: (10 << 4) | 1,
3387 htlc_minimum_msat: None,
3388 htlc_maximum_msat: None,
3393 fn ignores_empty_last_hops_test() {
3394 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3395 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3396 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3397 let scorer = ln_test_utils::TestScorer::new();
3398 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3399 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3401 // Test handling of an empty RouteHint passed in Invoice.
3403 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3404 assert_eq!(route.paths[0].hops.len(), 5);
3406 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3407 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3408 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3409 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3410 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3411 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3413 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3414 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3415 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3416 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3417 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3418 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3420 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3421 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3422 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3423 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3424 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3425 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3427 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3428 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3429 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3430 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3431 // If we have a peer in the node map, we'll use their features here since we don't have
3432 // a way of figuring out their features from the invoice:
3433 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3434 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3436 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3437 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3438 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3439 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3440 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3441 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3444 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3446 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3447 let zero_fees = RoutingFees {
3449 proportional_millionths: 0,
3451 vec![RouteHint(vec![RouteHintHop {
3452 src_node_id: hint_hops[0],
3453 short_channel_id: 0xff00,
3456 proportional_millionths: 0,
3458 cltv_expiry_delta: (5 << 4) | 1,
3459 htlc_minimum_msat: None,
3460 htlc_maximum_msat: None,
3462 src_node_id: hint_hops[1],
3463 short_channel_id: 0xff01,
3465 cltv_expiry_delta: (8 << 4) | 1,
3466 htlc_minimum_msat: None,
3467 htlc_maximum_msat: None,
3472 fn multi_hint_last_hops_test() {
3473 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3474 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3475 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3476 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3477 let scorer = ln_test_utils::TestScorer::new();
3478 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3479 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3480 // Test through channels 2, 3, 0xff00, 0xff01.
3481 // Test shows that multiple hop hints are considered.
3483 // Disabling channels 6 & 7 by flags=2
3484 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3485 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3486 short_channel_id: 6,
3488 flags: 2, // to disable
3489 cltv_expiry_delta: 0,
3490 htlc_minimum_msat: 0,
3491 htlc_maximum_msat: MAX_VALUE_MSAT,
3493 fee_proportional_millionths: 0,
3494 excess_data: Vec::new()
3496 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3497 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3498 short_channel_id: 7,
3500 flags: 2, // to disable
3501 cltv_expiry_delta: 0,
3502 htlc_minimum_msat: 0,
3503 htlc_maximum_msat: MAX_VALUE_MSAT,
3505 fee_proportional_millionths: 0,
3506 excess_data: Vec::new()
3509 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3510 assert_eq!(route.paths[0].hops.len(), 4);
3512 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3513 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3514 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3515 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3516 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3517 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3519 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3520 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3521 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3522 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3523 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3524 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3526 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3527 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3528 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3529 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3530 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3531 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3533 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3534 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3535 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3536 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3537 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3538 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3542 fn private_multi_hint_last_hops_test() {
3543 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3544 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3546 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3547 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3549 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3550 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3551 let scorer = ln_test_utils::TestScorer::new();
3552 // Test through channels 2, 3, 0xff00, 0xff01.
3553 // Test shows that multiple hop hints are considered.
3555 // Disabling channels 6 & 7 by flags=2
3556 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3557 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3558 short_channel_id: 6,
3560 flags: 2, // to disable
3561 cltv_expiry_delta: 0,
3562 htlc_minimum_msat: 0,
3563 htlc_maximum_msat: MAX_VALUE_MSAT,
3565 fee_proportional_millionths: 0,
3566 excess_data: Vec::new()
3568 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3569 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3570 short_channel_id: 7,
3572 flags: 2, // to disable
3573 cltv_expiry_delta: 0,
3574 htlc_minimum_msat: 0,
3575 htlc_maximum_msat: MAX_VALUE_MSAT,
3577 fee_proportional_millionths: 0,
3578 excess_data: Vec::new()
3581 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &[42u8; 32]).unwrap();
3582 assert_eq!(route.paths[0].hops.len(), 4);
3584 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3585 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3586 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3587 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3588 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3589 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3591 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3592 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3593 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3594 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3595 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3596 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3598 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3599 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3600 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3601 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3602 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3603 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3605 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3606 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3607 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3608 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3609 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3610 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3613 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3614 let zero_fees = RoutingFees {
3616 proportional_millionths: 0,
3618 vec![RouteHint(vec![RouteHintHop {
3619 src_node_id: nodes[4],
3620 short_channel_id: 11,
3622 cltv_expiry_delta: (11 << 4) | 1,
3623 htlc_minimum_msat: None,
3624 htlc_maximum_msat: None,
3626 src_node_id: nodes[3],
3627 short_channel_id: 8,
3629 cltv_expiry_delta: (8 << 4) | 1,
3630 htlc_minimum_msat: None,
3631 htlc_maximum_msat: None,
3632 }]), RouteHint(vec![RouteHintHop {
3633 src_node_id: nodes[4],
3634 short_channel_id: 9,
3637 proportional_millionths: 0,
3639 cltv_expiry_delta: (9 << 4) | 1,
3640 htlc_minimum_msat: None,
3641 htlc_maximum_msat: None,
3642 }]), RouteHint(vec![RouteHintHop {
3643 src_node_id: nodes[5],
3644 short_channel_id: 10,
3646 cltv_expiry_delta: (10 << 4) | 1,
3647 htlc_minimum_msat: None,
3648 htlc_maximum_msat: None,
3653 fn last_hops_with_public_channel_test() {
3654 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3655 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3656 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
3657 let scorer = ln_test_utils::TestScorer::new();
3658 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3659 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3660 // This test shows that public routes can be present in the invoice
3661 // which would be handled in the same manner.
3663 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3664 assert_eq!(route.paths[0].hops.len(), 5);
3666 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3667 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3668 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3669 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3670 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3671 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3673 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3674 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3675 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3676 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3677 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3678 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3680 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3681 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3682 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3683 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3684 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3685 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3687 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3688 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3689 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3690 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3691 // If we have a peer in the node map, we'll use their features here since we don't have
3692 // a way of figuring out their features from the invoice:
3693 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3694 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3696 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3697 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3698 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3699 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3700 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3701 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3705 fn our_chans_last_hop_connect_test() {
3706 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3707 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3708 let scorer = ln_test_utils::TestScorer::new();
3709 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3710 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3712 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3713 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3714 let mut last_hops = last_hops(&nodes);
3715 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3716 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();
3717 assert_eq!(route.paths[0].hops.len(), 2);
3719 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3720 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3721 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3722 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3723 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3724 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3726 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3727 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3728 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3729 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3730 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3731 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3733 last_hops[0].0[0].fees.base_msat = 1000;
3735 // Revert to via 6 as the fee on 8 goes up
3736 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops).unwrap();
3737 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3738 assert_eq!(route.paths[0].hops.len(), 4);
3740 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3741 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3742 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
3743 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3744 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3745 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3747 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3748 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3749 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3750 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
3751 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3752 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3754 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
3755 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3756 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3757 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3758 // If we have a peer in the node map, we'll use their features here since we don't have
3759 // a way of figuring out their features from the invoice:
3760 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3761 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3763 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3764 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3765 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3766 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3767 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3768 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3770 // ...but still use 8 for larger payments as 6 has a variable feerate
3771 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3772 assert_eq!(route.paths[0].hops.len(), 5);
3774 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3775 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3776 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3777 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3778 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3779 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3781 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3782 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3783 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3784 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3785 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3786 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3788 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3789 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3790 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3791 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3792 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3793 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3795 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3796 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3797 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
3798 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3799 // If we have a peer in the node map, we'll use their features here since we don't have
3800 // a way of figuring out their features from the invoice:
3801 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3802 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3804 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3805 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3806 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
3807 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3808 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3809 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3812 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> {
3813 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3814 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3815 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3817 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3818 let last_hops = RouteHint(vec![RouteHintHop {
3819 src_node_id: middle_node_id,
3820 short_channel_id: 8,
3823 proportional_millionths: last_hop_fee_prop,
3825 cltv_expiry_delta: (8 << 4) | 1,
3826 htlc_minimum_msat: None,
3827 htlc_maximum_msat: last_hop_htlc_max,
3829 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
3830 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3831 let scorer = ln_test_utils::TestScorer::new();
3832 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3833 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3834 let logger = ln_test_utils::TestLogger::new();
3835 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3836 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3837 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, &logger, &scorer, &(), &random_seed_bytes);
3842 fn unannounced_path_test() {
3843 // We should be able to send a payment to a destination without any help of a routing graph
3844 // if we have a channel with a common counterparty that appears in the first and last hop
3846 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3848 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3849 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3850 assert_eq!(route.paths[0].hops.len(), 2);
3852 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
3853 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3854 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
3855 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3856 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
3857 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3859 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
3860 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3861 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
3862 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3863 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3864 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3868 fn overflow_unannounced_path_test_liquidity_underflow() {
3869 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3870 // the last-hop had a fee which overflowed a u64, we'd panic.
3871 // This was due to us adding the first-hop from us unconditionally, causing us to think
3872 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3873 // In this test, we previously hit a subtraction underflow due to having less available
3874 // liquidity at the last hop than 0.
3875 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());
3879 fn overflow_unannounced_path_test_feerate_overflow() {
3880 // This tests for the same case as above, except instead of hitting a subtraction
3881 // underflow, we hit a case where the fee charged at a hop overflowed.
3882 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());
3886 fn available_amount_while_routing_test() {
3887 // Tests whether we choose the correct available channel amount while routing.
3889 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
3890 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3891 let scorer = ln_test_utils::TestScorer::new();
3892 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3893 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3894 let config = UserConfig::default();
3895 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3897 // We will use a simple single-path route from
3898 // our node to node2 via node0: channels {1, 3}.
3900 // First disable all other paths.
3901 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3902 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3903 short_channel_id: 2,
3906 cltv_expiry_delta: 0,
3907 htlc_minimum_msat: 0,
3908 htlc_maximum_msat: 100_000,
3910 fee_proportional_millionths: 0,
3911 excess_data: Vec::new()
3913 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3914 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3915 short_channel_id: 12,
3918 cltv_expiry_delta: 0,
3919 htlc_minimum_msat: 0,
3920 htlc_maximum_msat: 100_000,
3922 fee_proportional_millionths: 0,
3923 excess_data: Vec::new()
3926 // Make the first channel (#1) very permissive,
3927 // and we will be testing all limits on the second channel.
3928 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3929 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3930 short_channel_id: 1,
3933 cltv_expiry_delta: 0,
3934 htlc_minimum_msat: 0,
3935 htlc_maximum_msat: 1_000_000_000,
3937 fee_proportional_millionths: 0,
3938 excess_data: Vec::new()
3941 // First, let's see if routing works if we have absolutely no idea about the available amount.
3942 // In this case, it should be set to 250_000 sats.
3943 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3944 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3945 short_channel_id: 3,
3948 cltv_expiry_delta: 0,
3949 htlc_minimum_msat: 0,
3950 htlc_maximum_msat: 250_000_000,
3952 fee_proportional_millionths: 0,
3953 excess_data: Vec::new()
3957 // Attempt to route more than available results in a failure.
3958 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3959 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3960 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3961 } else { panic!(); }
3965 // Now, attempt to route an exact amount we have should be fine.
3966 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000_000, Arc::clone(&logger), &scorer, &(),&random_seed_bytes).unwrap();
3967 assert_eq!(route.paths.len(), 1);
3968 let path = route.paths.last().unwrap();
3969 assert_eq!(path.hops.len(), 2);
3970 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3971 assert_eq!(path.final_value_msat(), 250_000_000);
3974 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3975 // Disable channel #1 and use another first hop.
3976 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3977 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3978 short_channel_id: 1,
3981 cltv_expiry_delta: 0,
3982 htlc_minimum_msat: 0,
3983 htlc_maximum_msat: 1_000_000_000,
3985 fee_proportional_millionths: 0,
3986 excess_data: Vec::new()
3989 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3990 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3993 // Attempt to route more than available results in a failure.
3994 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3995 &our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3996 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3997 } else { panic!(); }
4001 // Now, attempt to route an exact amount we have should be fine.
4002 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();
4003 assert_eq!(route.paths.len(), 1);
4004 let path = route.paths.last().unwrap();
4005 assert_eq!(path.hops.len(), 2);
4006 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4007 assert_eq!(path.final_value_msat(), 200_000_000);
4010 // Enable channel #1 back.
4011 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4012 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4013 short_channel_id: 1,
4016 cltv_expiry_delta: 0,
4017 htlc_minimum_msat: 0,
4018 htlc_maximum_msat: 1_000_000_000,
4020 fee_proportional_millionths: 0,
4021 excess_data: Vec::new()
4025 // Now let's see if routing works if we know only htlc_maximum_msat.
4026 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4027 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4028 short_channel_id: 3,
4031 cltv_expiry_delta: 0,
4032 htlc_minimum_msat: 0,
4033 htlc_maximum_msat: 15_000,
4035 fee_proportional_millionths: 0,
4036 excess_data: Vec::new()
4040 // Attempt to route more than available results in a failure.
4041 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4042 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4043 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4044 } else { panic!(); }
4048 // Now, attempt to route an exact amount we have should be fine.
4049 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4050 assert_eq!(route.paths.len(), 1);
4051 let path = route.paths.last().unwrap();
4052 assert_eq!(path.hops.len(), 2);
4053 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4054 assert_eq!(path.final_value_msat(), 15_000);
4057 // Now let's see if routing works if we know only capacity from the UTXO.
4059 // We can't change UTXO capacity on the fly, so we'll disable
4060 // the existing channel and add another one with the capacity we need.
4061 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4062 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4063 short_channel_id: 3,
4066 cltv_expiry_delta: 0,
4067 htlc_minimum_msat: 0,
4068 htlc_maximum_msat: MAX_VALUE_MSAT,
4070 fee_proportional_millionths: 0,
4071 excess_data: Vec::new()
4074 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4075 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4076 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4077 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4078 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4080 *chain_monitor.utxo_ret.lock().unwrap() =
4081 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4082 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4084 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4085 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4086 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4087 short_channel_id: 333,
4090 cltv_expiry_delta: (3 << 4) | 1,
4091 htlc_minimum_msat: 0,
4092 htlc_maximum_msat: 15_000,
4094 fee_proportional_millionths: 0,
4095 excess_data: Vec::new()
4097 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4098 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4099 short_channel_id: 333,
4102 cltv_expiry_delta: (3 << 4) | 2,
4103 htlc_minimum_msat: 0,
4104 htlc_maximum_msat: 15_000,
4106 fee_proportional_millionths: 0,
4107 excess_data: Vec::new()
4111 // Attempt to route more than available results in a failure.
4112 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4113 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4114 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4115 } else { panic!(); }
4119 // Now, attempt to route an exact amount we have should be fine.
4120 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4121 assert_eq!(route.paths.len(), 1);
4122 let path = route.paths.last().unwrap();
4123 assert_eq!(path.hops.len(), 2);
4124 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4125 assert_eq!(path.final_value_msat(), 15_000);
4128 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4129 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4130 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4131 short_channel_id: 333,
4134 cltv_expiry_delta: 0,
4135 htlc_minimum_msat: 0,
4136 htlc_maximum_msat: 10_000,
4138 fee_proportional_millionths: 0,
4139 excess_data: Vec::new()
4143 // Attempt to route more than available results in a failure.
4144 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4145 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4146 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4147 } else { panic!(); }
4151 // Now, attempt to route an exact amount we have should be fine.
4152 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4153 assert_eq!(route.paths.len(), 1);
4154 let path = route.paths.last().unwrap();
4155 assert_eq!(path.hops.len(), 2);
4156 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4157 assert_eq!(path.final_value_msat(), 10_000);
4162 fn available_liquidity_last_hop_test() {
4163 // Check that available liquidity properly limits the path even when only
4164 // one of the latter hops is limited.
4165 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4166 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4167 let scorer = ln_test_utils::TestScorer::new();
4168 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4169 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4170 let config = UserConfig::default();
4171 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4173 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4174 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4175 // Total capacity: 50 sats.
4177 // Disable other potential paths.
4178 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4179 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4180 short_channel_id: 2,
4183 cltv_expiry_delta: 0,
4184 htlc_minimum_msat: 0,
4185 htlc_maximum_msat: 100_000,
4187 fee_proportional_millionths: 0,
4188 excess_data: Vec::new()
4190 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4191 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4192 short_channel_id: 7,
4195 cltv_expiry_delta: 0,
4196 htlc_minimum_msat: 0,
4197 htlc_maximum_msat: 100_000,
4199 fee_proportional_millionths: 0,
4200 excess_data: Vec::new()
4205 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4206 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4207 short_channel_id: 12,
4210 cltv_expiry_delta: 0,
4211 htlc_minimum_msat: 0,
4212 htlc_maximum_msat: 100_000,
4214 fee_proportional_millionths: 0,
4215 excess_data: Vec::new()
4217 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4218 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4219 short_channel_id: 13,
4222 cltv_expiry_delta: 0,
4223 htlc_minimum_msat: 0,
4224 htlc_maximum_msat: 100_000,
4226 fee_proportional_millionths: 0,
4227 excess_data: Vec::new()
4230 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4231 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4232 short_channel_id: 6,
4235 cltv_expiry_delta: 0,
4236 htlc_minimum_msat: 0,
4237 htlc_maximum_msat: 50_000,
4239 fee_proportional_millionths: 0,
4240 excess_data: Vec::new()
4242 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4243 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4244 short_channel_id: 11,
4247 cltv_expiry_delta: 0,
4248 htlc_minimum_msat: 0,
4249 htlc_maximum_msat: 100_000,
4251 fee_proportional_millionths: 0,
4252 excess_data: Vec::new()
4255 // Attempt to route more than available results in a failure.
4256 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4257 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4258 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4259 } else { panic!(); }
4263 // Now, attempt to route 49 sats (just a bit below the capacity).
4264 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4265 assert_eq!(route.paths.len(), 1);
4266 let mut total_amount_paid_msat = 0;
4267 for path in &route.paths {
4268 assert_eq!(path.hops.len(), 4);
4269 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4270 total_amount_paid_msat += path.final_value_msat();
4272 assert_eq!(total_amount_paid_msat, 49_000);
4276 // Attempt to route an exact amount is also fine
4277 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4278 assert_eq!(route.paths.len(), 1);
4279 let mut total_amount_paid_msat = 0;
4280 for path in &route.paths {
4281 assert_eq!(path.hops.len(), 4);
4282 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4283 total_amount_paid_msat += path.final_value_msat();
4285 assert_eq!(total_amount_paid_msat, 50_000);
4290 fn ignore_fee_first_hop_test() {
4291 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4292 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4293 let scorer = ln_test_utils::TestScorer::new();
4294 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4295 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4296 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4298 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4299 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4300 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4301 short_channel_id: 1,
4304 cltv_expiry_delta: 0,
4305 htlc_minimum_msat: 0,
4306 htlc_maximum_msat: 100_000,
4307 fee_base_msat: 1_000_000,
4308 fee_proportional_millionths: 0,
4309 excess_data: Vec::new()
4311 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4312 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4313 short_channel_id: 3,
4316 cltv_expiry_delta: 0,
4317 htlc_minimum_msat: 0,
4318 htlc_maximum_msat: 50_000,
4320 fee_proportional_millionths: 0,
4321 excess_data: Vec::new()
4325 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4326 assert_eq!(route.paths.len(), 1);
4327 let mut total_amount_paid_msat = 0;
4328 for path in &route.paths {
4329 assert_eq!(path.hops.len(), 2);
4330 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4331 total_amount_paid_msat += path.final_value_msat();
4333 assert_eq!(total_amount_paid_msat, 50_000);
4338 fn simple_mpp_route_test() {
4339 let (secp_ctx, _, _, _, _) = build_graph();
4340 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4341 let config = UserConfig::default();
4342 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4343 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4344 do_simple_mpp_route_test(clear_payment_params);
4346 // MPP to a 1-hop blinded path for nodes[2]
4347 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
4348 let blinded_path = BlindedPath {
4349 introduction_node_id: nodes[2],
4350 blinding_point: ln_test_utils::pubkey(42),
4351 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4353 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4355 fee_proportional_millionths: 0,
4356 htlc_minimum_msat: 0,
4357 htlc_maximum_msat: 0,
4358 cltv_expiry_delta: 0,
4359 features: BlindedHopFeatures::empty(),
4361 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4362 .with_bolt12_features(bolt12_features.clone()).unwrap();
4363 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4365 // MPP to 3 2-hop blinded paths
4366 let mut blinded_path_node_0 = blinded_path.clone();
4367 blinded_path_node_0.introduction_node_id = nodes[0];
4368 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4369 let mut node_0_payinfo = blinded_payinfo.clone();
4370 node_0_payinfo.htlc_maximum_msat = 50_000;
4372 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4373 blinded_path_node_7.introduction_node_id = nodes[7];
4374 let mut node_7_payinfo = blinded_payinfo.clone();
4375 node_7_payinfo.htlc_maximum_msat = 60_000;
4377 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4378 blinded_path_node_1.introduction_node_id = nodes[1];
4379 let mut node_1_payinfo = blinded_payinfo.clone();
4380 node_1_payinfo.htlc_maximum_msat = 180_000;
4382 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4384 (node_0_payinfo, blinded_path_node_0),
4385 (node_7_payinfo, blinded_path_node_7),
4386 (node_1_payinfo, blinded_path_node_1)
4388 .with_bolt12_features(bolt12_features).unwrap();
4389 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4393 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4394 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4395 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4396 let scorer = ln_test_utils::TestScorer::new();
4397 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4398 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4400 // We need a route consisting of 3 paths:
4401 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4402 // To achieve this, the amount being transferred should be around
4403 // the total capacity of these 3 paths.
4405 // First, we set limits on these (previously unlimited) channels.
4406 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4408 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4409 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4410 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4411 short_channel_id: 1,
4414 cltv_expiry_delta: 0,
4415 htlc_minimum_msat: 0,
4416 htlc_maximum_msat: 100_000,
4418 fee_proportional_millionths: 0,
4419 excess_data: Vec::new()
4421 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4422 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4423 short_channel_id: 3,
4426 cltv_expiry_delta: 0,
4427 htlc_minimum_msat: 0,
4428 htlc_maximum_msat: 50_000,
4430 fee_proportional_millionths: 0,
4431 excess_data: Vec::new()
4434 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4435 // (total limit 60).
4436 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4437 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4438 short_channel_id: 12,
4441 cltv_expiry_delta: 0,
4442 htlc_minimum_msat: 0,
4443 htlc_maximum_msat: 60_000,
4445 fee_proportional_millionths: 0,
4446 excess_data: Vec::new()
4448 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4449 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4450 short_channel_id: 13,
4453 cltv_expiry_delta: 0,
4454 htlc_minimum_msat: 0,
4455 htlc_maximum_msat: 60_000,
4457 fee_proportional_millionths: 0,
4458 excess_data: Vec::new()
4461 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4462 // (total capacity 180 sats).
4463 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4464 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4465 short_channel_id: 2,
4468 cltv_expiry_delta: 0,
4469 htlc_minimum_msat: 0,
4470 htlc_maximum_msat: 200_000,
4472 fee_proportional_millionths: 0,
4473 excess_data: Vec::new()
4475 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4476 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4477 short_channel_id: 4,
4480 cltv_expiry_delta: 0,
4481 htlc_minimum_msat: 0,
4482 htlc_maximum_msat: 180_000,
4484 fee_proportional_millionths: 0,
4485 excess_data: Vec::new()
4489 // Attempt to route more than available results in a failure.
4490 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4491 &our_id, &payment_params, &network_graph.read_only(), None, 300_000,
4492 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4493 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4494 } else { panic!(); }
4498 // Attempt to route while setting max_path_count to 0 results in a failure.
4499 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4500 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4501 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100,
4502 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4503 assert_eq!(err, "Can't find a route with no paths allowed.");
4504 } else { panic!(); }
4508 // Attempt to route while setting max_path_count to 3 results in a failure.
4509 // This is the case because the minimal_value_contribution_msat would require each path
4510 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4511 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4512 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4513 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000,
4514 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4515 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4516 } else { panic!(); }
4520 // Now, attempt to route 250 sats (just a bit below the capacity).
4521 // Our algorithm should provide us with these 3 paths.
4522 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4523 250_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4524 assert_eq!(route.paths.len(), 3);
4525 let mut total_amount_paid_msat = 0;
4526 for path in &route.paths {
4527 if let Some(bt) = &path.blinded_tail {
4528 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4530 assert_eq!(path.hops.len(), 2);
4531 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4533 total_amount_paid_msat += path.final_value_msat();
4535 assert_eq!(total_amount_paid_msat, 250_000);
4539 // Attempt to route an exact amount is also fine
4540 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4541 290_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4542 assert_eq!(route.paths.len(), 3);
4543 let mut total_amount_paid_msat = 0;
4544 for path in &route.paths {
4545 if payment_params.payee.blinded_route_hints().len() != 0 {
4546 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
4547 if let Some(bt) = &path.blinded_tail {
4548 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4549 if bt.hops.len() > 1 {
4550 assert_eq!(path.hops.last().unwrap().pubkey,
4551 payment_params.payee.blinded_route_hints().iter()
4552 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
4553 .map(|(_, p)| p.introduction_node_id).unwrap());
4555 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4558 assert_eq!(path.hops.len(), 2);
4559 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4561 total_amount_paid_msat += path.final_value_msat();
4563 assert_eq!(total_amount_paid_msat, 290_000);
4568 fn long_mpp_route_test() {
4569 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4570 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4571 let scorer = ln_test_utils::TestScorer::new();
4572 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4573 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4574 let config = UserConfig::default();
4575 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4577 // We need a route consisting of 3 paths:
4578 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4579 // Note that these paths overlap (channels 5, 12, 13).
4580 // We will route 300 sats.
4581 // Each path will have 100 sats capacity, those channels which
4582 // are used twice will have 200 sats capacity.
4584 // Disable other potential paths.
4585 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4586 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4587 short_channel_id: 2,
4590 cltv_expiry_delta: 0,
4591 htlc_minimum_msat: 0,
4592 htlc_maximum_msat: 100_000,
4594 fee_proportional_millionths: 0,
4595 excess_data: Vec::new()
4597 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4598 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4599 short_channel_id: 7,
4602 cltv_expiry_delta: 0,
4603 htlc_minimum_msat: 0,
4604 htlc_maximum_msat: 100_000,
4606 fee_proportional_millionths: 0,
4607 excess_data: Vec::new()
4610 // Path via {node0, node2} is channels {1, 3, 5}.
4611 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4612 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4613 short_channel_id: 1,
4616 cltv_expiry_delta: 0,
4617 htlc_minimum_msat: 0,
4618 htlc_maximum_msat: 100_000,
4620 fee_proportional_millionths: 0,
4621 excess_data: Vec::new()
4623 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4624 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4625 short_channel_id: 3,
4628 cltv_expiry_delta: 0,
4629 htlc_minimum_msat: 0,
4630 htlc_maximum_msat: 100_000,
4632 fee_proportional_millionths: 0,
4633 excess_data: Vec::new()
4636 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4637 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4638 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4639 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4640 short_channel_id: 5,
4643 cltv_expiry_delta: 0,
4644 htlc_minimum_msat: 0,
4645 htlc_maximum_msat: 200_000,
4647 fee_proportional_millionths: 0,
4648 excess_data: Vec::new()
4651 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4652 // Add 100 sats to the capacities of {12, 13}, because these channels
4653 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4654 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4655 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4656 short_channel_id: 12,
4659 cltv_expiry_delta: 0,
4660 htlc_minimum_msat: 0,
4661 htlc_maximum_msat: 200_000,
4663 fee_proportional_millionths: 0,
4664 excess_data: Vec::new()
4666 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4667 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4668 short_channel_id: 13,
4671 cltv_expiry_delta: 0,
4672 htlc_minimum_msat: 0,
4673 htlc_maximum_msat: 200_000,
4675 fee_proportional_millionths: 0,
4676 excess_data: Vec::new()
4679 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4680 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4681 short_channel_id: 6,
4684 cltv_expiry_delta: 0,
4685 htlc_minimum_msat: 0,
4686 htlc_maximum_msat: 100_000,
4688 fee_proportional_millionths: 0,
4689 excess_data: Vec::new()
4691 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4692 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4693 short_channel_id: 11,
4696 cltv_expiry_delta: 0,
4697 htlc_minimum_msat: 0,
4698 htlc_maximum_msat: 100_000,
4700 fee_proportional_millionths: 0,
4701 excess_data: Vec::new()
4704 // Path via {node7, node2} is channels {12, 13, 5}.
4705 // We already limited them to 200 sats (they are used twice for 100 sats).
4706 // Nothing to do here.
4709 // Attempt to route more than available results in a failure.
4710 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4711 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4712 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4713 } else { panic!(); }
4717 // Now, attempt to route 300 sats (exact amount we can route).
4718 // Our algorithm should provide us with these 3 paths, 100 sats each.
4719 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4720 assert_eq!(route.paths.len(), 3);
4722 let mut total_amount_paid_msat = 0;
4723 for path in &route.paths {
4724 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4725 total_amount_paid_msat += path.final_value_msat();
4727 assert_eq!(total_amount_paid_msat, 300_000);
4733 fn mpp_cheaper_route_test() {
4734 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4735 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4736 let scorer = ln_test_utils::TestScorer::new();
4737 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4738 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4739 let config = UserConfig::default();
4740 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4742 // This test checks that if we have two cheaper paths and one more expensive path,
4743 // so that liquidity-wise any 2 of 3 combination is sufficient,
4744 // two cheaper paths will be taken.
4745 // These paths have equal available liquidity.
4747 // We need a combination of 3 paths:
4748 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4749 // Note that these paths overlap (channels 5, 12, 13).
4750 // Each path will have 100 sats capacity, those channels which
4751 // are used twice will have 200 sats capacity.
4753 // Disable other potential paths.
4754 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4755 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4756 short_channel_id: 2,
4759 cltv_expiry_delta: 0,
4760 htlc_minimum_msat: 0,
4761 htlc_maximum_msat: 100_000,
4763 fee_proportional_millionths: 0,
4764 excess_data: Vec::new()
4766 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4767 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4768 short_channel_id: 7,
4771 cltv_expiry_delta: 0,
4772 htlc_minimum_msat: 0,
4773 htlc_maximum_msat: 100_000,
4775 fee_proportional_millionths: 0,
4776 excess_data: Vec::new()
4779 // Path via {node0, node2} is channels {1, 3, 5}.
4780 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4781 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4782 short_channel_id: 1,
4785 cltv_expiry_delta: 0,
4786 htlc_minimum_msat: 0,
4787 htlc_maximum_msat: 100_000,
4789 fee_proportional_millionths: 0,
4790 excess_data: Vec::new()
4792 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4793 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4794 short_channel_id: 3,
4797 cltv_expiry_delta: 0,
4798 htlc_minimum_msat: 0,
4799 htlc_maximum_msat: 100_000,
4801 fee_proportional_millionths: 0,
4802 excess_data: Vec::new()
4805 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4806 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4807 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4808 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4809 short_channel_id: 5,
4812 cltv_expiry_delta: 0,
4813 htlc_minimum_msat: 0,
4814 htlc_maximum_msat: 200_000,
4816 fee_proportional_millionths: 0,
4817 excess_data: Vec::new()
4820 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4821 // Add 100 sats to the capacities of {12, 13}, because these channels
4822 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4823 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4824 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4825 short_channel_id: 12,
4828 cltv_expiry_delta: 0,
4829 htlc_minimum_msat: 0,
4830 htlc_maximum_msat: 200_000,
4832 fee_proportional_millionths: 0,
4833 excess_data: Vec::new()
4835 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4836 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4837 short_channel_id: 13,
4840 cltv_expiry_delta: 0,
4841 htlc_minimum_msat: 0,
4842 htlc_maximum_msat: 200_000,
4844 fee_proportional_millionths: 0,
4845 excess_data: Vec::new()
4848 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4849 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4850 short_channel_id: 6,
4853 cltv_expiry_delta: 0,
4854 htlc_minimum_msat: 0,
4855 htlc_maximum_msat: 100_000,
4856 fee_base_msat: 1_000,
4857 fee_proportional_millionths: 0,
4858 excess_data: Vec::new()
4860 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4861 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4862 short_channel_id: 11,
4865 cltv_expiry_delta: 0,
4866 htlc_minimum_msat: 0,
4867 htlc_maximum_msat: 100_000,
4869 fee_proportional_millionths: 0,
4870 excess_data: Vec::new()
4873 // Path via {node7, node2} is channels {12, 13, 5}.
4874 // We already limited them to 200 sats (they are used twice for 100 sats).
4875 // Nothing to do here.
4878 // Now, attempt to route 180 sats.
4879 // Our algorithm should provide us with these 2 paths.
4880 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4881 assert_eq!(route.paths.len(), 2);
4883 let mut total_value_transferred_msat = 0;
4884 let mut total_paid_msat = 0;
4885 for path in &route.paths {
4886 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4887 total_value_transferred_msat += path.final_value_msat();
4888 for hop in &path.hops {
4889 total_paid_msat += hop.fee_msat;
4892 // If we paid fee, this would be higher.
4893 assert_eq!(total_value_transferred_msat, 180_000);
4894 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4895 assert_eq!(total_fees_paid, 0);
4900 fn fees_on_mpp_route_test() {
4901 // This test makes sure that MPP algorithm properly takes into account
4902 // fees charged on the channels, by making the fees impactful:
4903 // if the fee is not properly accounted for, the behavior is different.
4904 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4905 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4906 let scorer = ln_test_utils::TestScorer::new();
4907 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4908 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4909 let config = UserConfig::default();
4910 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4912 // We need a route consisting of 2 paths:
4913 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4914 // We will route 200 sats, Each path will have 100 sats capacity.
4916 // This test is not particularly stable: e.g.,
4917 // there's a way to route via {node0, node2, node4}.
4918 // It works while pathfinding is deterministic, but can be broken otherwise.
4919 // It's fine to ignore this concern for now.
4921 // Disable other potential paths.
4922 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4923 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4924 short_channel_id: 2,
4927 cltv_expiry_delta: 0,
4928 htlc_minimum_msat: 0,
4929 htlc_maximum_msat: 100_000,
4931 fee_proportional_millionths: 0,
4932 excess_data: Vec::new()
4935 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4936 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4937 short_channel_id: 7,
4940 cltv_expiry_delta: 0,
4941 htlc_minimum_msat: 0,
4942 htlc_maximum_msat: 100_000,
4944 fee_proportional_millionths: 0,
4945 excess_data: Vec::new()
4948 // Path via {node0, node2} is channels {1, 3, 5}.
4949 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4950 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4951 short_channel_id: 1,
4954 cltv_expiry_delta: 0,
4955 htlc_minimum_msat: 0,
4956 htlc_maximum_msat: 100_000,
4958 fee_proportional_millionths: 0,
4959 excess_data: Vec::new()
4961 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4962 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4963 short_channel_id: 3,
4966 cltv_expiry_delta: 0,
4967 htlc_minimum_msat: 0,
4968 htlc_maximum_msat: 100_000,
4970 fee_proportional_millionths: 0,
4971 excess_data: Vec::new()
4974 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4975 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4976 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4977 short_channel_id: 5,
4980 cltv_expiry_delta: 0,
4981 htlc_minimum_msat: 0,
4982 htlc_maximum_msat: 100_000,
4984 fee_proportional_millionths: 0,
4985 excess_data: Vec::new()
4988 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4989 // All channels should be 100 sats capacity. But for the fee experiment,
4990 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4991 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4992 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4993 // so no matter how large are other channels,
4994 // the whole path will be limited by 100 sats with just these 2 conditions:
4995 // - channel 12 capacity is 250 sats
4996 // - fee for channel 6 is 150 sats
4997 // Let's test this by enforcing these 2 conditions and removing other limits.
4998 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4999 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5000 short_channel_id: 12,
5003 cltv_expiry_delta: 0,
5004 htlc_minimum_msat: 0,
5005 htlc_maximum_msat: 250_000,
5007 fee_proportional_millionths: 0,
5008 excess_data: Vec::new()
5010 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5011 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5012 short_channel_id: 13,
5015 cltv_expiry_delta: 0,
5016 htlc_minimum_msat: 0,
5017 htlc_maximum_msat: MAX_VALUE_MSAT,
5019 fee_proportional_millionths: 0,
5020 excess_data: Vec::new()
5023 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5024 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5025 short_channel_id: 6,
5028 cltv_expiry_delta: 0,
5029 htlc_minimum_msat: 0,
5030 htlc_maximum_msat: MAX_VALUE_MSAT,
5031 fee_base_msat: 150_000,
5032 fee_proportional_millionths: 0,
5033 excess_data: Vec::new()
5035 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5036 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5037 short_channel_id: 11,
5040 cltv_expiry_delta: 0,
5041 htlc_minimum_msat: 0,
5042 htlc_maximum_msat: MAX_VALUE_MSAT,
5044 fee_proportional_millionths: 0,
5045 excess_data: Vec::new()
5049 // Attempt to route more than available results in a failure.
5050 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5051 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5052 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5053 } else { panic!(); }
5057 // Now, attempt to route 200 sats (exact amount we can route).
5058 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5059 assert_eq!(route.paths.len(), 2);
5061 let mut total_amount_paid_msat = 0;
5062 for path in &route.paths {
5063 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5064 total_amount_paid_msat += path.final_value_msat();
5066 assert_eq!(total_amount_paid_msat, 200_000);
5067 assert_eq!(route.get_total_fees(), 150_000);
5072 fn mpp_with_last_hops() {
5073 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5074 // via a single last-hop route hint, we'd fail to route if we first collected routes
5075 // totaling close but not quite enough to fund the full payment.
5077 // This was because we considered last-hop hints to have exactly the sought payment amount
5078 // instead of the amount we were trying to collect, needlessly limiting our path searching
5079 // at the very first hop.
5081 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5082 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5083 // to only have the remaining to-collect amount in available liquidity.
5085 // This bug appeared in production in some specific channel configurations.
5086 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5087 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5088 let scorer = ln_test_utils::TestScorer::new();
5089 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5090 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5091 let config = UserConfig::default();
5092 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5093 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5094 src_node_id: nodes[2],
5095 short_channel_id: 42,
5096 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5097 cltv_expiry_delta: 42,
5098 htlc_minimum_msat: None,
5099 htlc_maximum_msat: None,
5100 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5102 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5103 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5104 // would first use the no-fee route and then fail to find a path along the second route as
5105 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5106 // under 5% of our payment amount.
5107 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5108 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5109 short_channel_id: 1,
5112 cltv_expiry_delta: (5 << 4) | 5,
5113 htlc_minimum_msat: 0,
5114 htlc_maximum_msat: 99_000,
5115 fee_base_msat: u32::max_value(),
5116 fee_proportional_millionths: u32::max_value(),
5117 excess_data: Vec::new()
5119 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5120 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5121 short_channel_id: 2,
5124 cltv_expiry_delta: (5 << 4) | 3,
5125 htlc_minimum_msat: 0,
5126 htlc_maximum_msat: 99_000,
5127 fee_base_msat: u32::max_value(),
5128 fee_proportional_millionths: u32::max_value(),
5129 excess_data: Vec::new()
5131 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5132 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5133 short_channel_id: 4,
5136 cltv_expiry_delta: (4 << 4) | 1,
5137 htlc_minimum_msat: 0,
5138 htlc_maximum_msat: MAX_VALUE_MSAT,
5140 fee_proportional_millionths: 0,
5141 excess_data: Vec::new()
5143 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5144 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5145 short_channel_id: 13,
5147 flags: 0|2, // Channel disabled
5148 cltv_expiry_delta: (13 << 4) | 1,
5149 htlc_minimum_msat: 0,
5150 htlc_maximum_msat: MAX_VALUE_MSAT,
5152 fee_proportional_millionths: 2000000,
5153 excess_data: Vec::new()
5156 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5158 let mut route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5159 assert_eq!(route.paths.len(), 2);
5160 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5161 // Paths are manually ordered ordered by SCID, so:
5162 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5163 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5164 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5165 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5166 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5167 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5168 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5169 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5170 assert_eq!(route.get_total_fees(), 1);
5171 assert_eq!(route.get_total_amount(), 100_000);
5175 fn drop_lowest_channel_mpp_route_test() {
5176 // This test checks that low-capacity channel is dropped when after
5177 // path finding we realize that we found more capacity than we need.
5178 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5179 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5180 let scorer = ln_test_utils::TestScorer::new();
5181 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5182 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5183 let config = UserConfig::default();
5184 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5185 .with_max_channel_saturation_power_of_half(0);
5187 // We need a route consisting of 3 paths:
5188 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5190 // The first and the second paths should be sufficient, but the third should be
5191 // cheaper, so that we select it but drop later.
5193 // First, we set limits on these (previously unlimited) channels.
5194 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5196 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5197 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5198 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5199 short_channel_id: 1,
5202 cltv_expiry_delta: 0,
5203 htlc_minimum_msat: 0,
5204 htlc_maximum_msat: 100_000,
5206 fee_proportional_millionths: 0,
5207 excess_data: Vec::new()
5209 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5210 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5211 short_channel_id: 3,
5214 cltv_expiry_delta: 0,
5215 htlc_minimum_msat: 0,
5216 htlc_maximum_msat: 50_000,
5218 fee_proportional_millionths: 0,
5219 excess_data: Vec::new()
5222 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5223 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5224 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5225 short_channel_id: 12,
5228 cltv_expiry_delta: 0,
5229 htlc_minimum_msat: 0,
5230 htlc_maximum_msat: 60_000,
5232 fee_proportional_millionths: 0,
5233 excess_data: Vec::new()
5235 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5236 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5237 short_channel_id: 13,
5240 cltv_expiry_delta: 0,
5241 htlc_minimum_msat: 0,
5242 htlc_maximum_msat: 60_000,
5244 fee_proportional_millionths: 0,
5245 excess_data: Vec::new()
5248 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5249 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5250 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5251 short_channel_id: 2,
5254 cltv_expiry_delta: 0,
5255 htlc_minimum_msat: 0,
5256 htlc_maximum_msat: 20_000,
5258 fee_proportional_millionths: 0,
5259 excess_data: Vec::new()
5261 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5262 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5263 short_channel_id: 4,
5266 cltv_expiry_delta: 0,
5267 htlc_minimum_msat: 0,
5268 htlc_maximum_msat: 20_000,
5270 fee_proportional_millionths: 0,
5271 excess_data: Vec::new()
5275 // Attempt to route more than available results in a failure.
5276 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5277 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5278 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5279 } else { panic!(); }
5283 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5284 // Our algorithm should provide us with these 3 paths.
5285 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5286 assert_eq!(route.paths.len(), 3);
5287 let mut total_amount_paid_msat = 0;
5288 for path in &route.paths {
5289 assert_eq!(path.hops.len(), 2);
5290 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5291 total_amount_paid_msat += path.final_value_msat();
5293 assert_eq!(total_amount_paid_msat, 125_000);
5297 // Attempt to route without the last small cheap channel
5298 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5299 assert_eq!(route.paths.len(), 2);
5300 let mut total_amount_paid_msat = 0;
5301 for path in &route.paths {
5302 assert_eq!(path.hops.len(), 2);
5303 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5304 total_amount_paid_msat += path.final_value_msat();
5306 assert_eq!(total_amount_paid_msat, 90_000);
5311 fn min_criteria_consistency() {
5312 // Test that we don't use an inconsistent metric between updating and walking nodes during
5313 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5314 // was updated with a different criterion from the heap sorting, resulting in loops in
5315 // calculated paths. We test for that specific case here.
5317 // We construct a network that looks like this:
5319 // node2 -1(3)2- node3
5323 // node1 -1(5)2- node4 -1(1)2- node6
5329 // We create a loop on the side of our real path - our destination is node 6, with a
5330 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5331 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5332 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5333 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5334 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5335 // "previous hop" being set to node 3, creating a loop in the path.
5336 let secp_ctx = Secp256k1::new();
5337 let logger = Arc::new(ln_test_utils::TestLogger::new());
5338 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5339 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5340 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5341 let scorer = ln_test_utils::TestScorer::new();
5342 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5343 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5344 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5346 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5347 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5348 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5349 short_channel_id: 6,
5352 cltv_expiry_delta: (6 << 4) | 0,
5353 htlc_minimum_msat: 0,
5354 htlc_maximum_msat: MAX_VALUE_MSAT,
5356 fee_proportional_millionths: 0,
5357 excess_data: Vec::new()
5359 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5361 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5362 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5363 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5364 short_channel_id: 5,
5367 cltv_expiry_delta: (5 << 4) | 0,
5368 htlc_minimum_msat: 0,
5369 htlc_maximum_msat: MAX_VALUE_MSAT,
5371 fee_proportional_millionths: 0,
5372 excess_data: Vec::new()
5374 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5376 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5377 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5378 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5379 short_channel_id: 4,
5382 cltv_expiry_delta: (4 << 4) | 0,
5383 htlc_minimum_msat: 0,
5384 htlc_maximum_msat: MAX_VALUE_MSAT,
5386 fee_proportional_millionths: 0,
5387 excess_data: Vec::new()
5389 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5391 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5392 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5393 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5394 short_channel_id: 3,
5397 cltv_expiry_delta: (3 << 4) | 0,
5398 htlc_minimum_msat: 0,
5399 htlc_maximum_msat: MAX_VALUE_MSAT,
5401 fee_proportional_millionths: 0,
5402 excess_data: Vec::new()
5404 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5406 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5407 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5408 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5409 short_channel_id: 2,
5412 cltv_expiry_delta: (2 << 4) | 0,
5413 htlc_minimum_msat: 0,
5414 htlc_maximum_msat: MAX_VALUE_MSAT,
5416 fee_proportional_millionths: 0,
5417 excess_data: Vec::new()
5420 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5421 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5422 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5423 short_channel_id: 1,
5426 cltv_expiry_delta: (1 << 4) | 0,
5427 htlc_minimum_msat: 100,
5428 htlc_maximum_msat: MAX_VALUE_MSAT,
5430 fee_proportional_millionths: 0,
5431 excess_data: Vec::new()
5433 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5436 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5437 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5438 assert_eq!(route.paths.len(), 1);
5439 assert_eq!(route.paths[0].hops.len(), 3);
5441 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5442 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5443 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5444 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5445 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5446 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5448 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5449 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5450 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5451 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5452 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5453 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5455 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5456 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5457 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5458 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5459 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5460 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5466 fn exact_fee_liquidity_limit() {
5467 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5468 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5469 // we calculated fees on a higher value, resulting in us ignoring such paths.
5470 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5471 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5472 let scorer = ln_test_utils::TestScorer::new();
5473 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5474 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5475 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5477 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5479 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5480 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5481 short_channel_id: 2,
5484 cltv_expiry_delta: 0,
5485 htlc_minimum_msat: 0,
5486 htlc_maximum_msat: 85_000,
5488 fee_proportional_millionths: 0,
5489 excess_data: Vec::new()
5492 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5493 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5494 short_channel_id: 12,
5497 cltv_expiry_delta: (4 << 4) | 1,
5498 htlc_minimum_msat: 0,
5499 htlc_maximum_msat: 270_000,
5501 fee_proportional_millionths: 1000000,
5502 excess_data: Vec::new()
5506 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5507 // 200% fee charged channel 13 in the 1-to-2 direction.
5508 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5509 assert_eq!(route.paths.len(), 1);
5510 assert_eq!(route.paths[0].hops.len(), 2);
5512 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5513 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5514 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5515 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5516 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5517 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5519 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5520 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5521 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5522 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5523 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5524 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5529 fn htlc_max_reduction_below_min() {
5530 // Test that if, while walking the graph, we reduce the value being sent to meet an
5531 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5532 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5533 // resulting in us thinking there is no possible path, even if other paths exist.
5534 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5535 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5536 let scorer = ln_test_utils::TestScorer::new();
5537 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5538 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5539 let config = UserConfig::default();
5540 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5542 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5543 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5544 // then try to send 90_000.
5545 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5546 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5547 short_channel_id: 2,
5550 cltv_expiry_delta: 0,
5551 htlc_minimum_msat: 0,
5552 htlc_maximum_msat: 80_000,
5554 fee_proportional_millionths: 0,
5555 excess_data: Vec::new()
5557 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5558 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5559 short_channel_id: 4,
5562 cltv_expiry_delta: (4 << 4) | 1,
5563 htlc_minimum_msat: 90_000,
5564 htlc_maximum_msat: MAX_VALUE_MSAT,
5566 fee_proportional_millionths: 0,
5567 excess_data: Vec::new()
5571 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5572 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5573 // expensive) channels 12-13 path.
5574 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5575 assert_eq!(route.paths.len(), 1);
5576 assert_eq!(route.paths[0].hops.len(), 2);
5578 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5579 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5580 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5581 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5582 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5583 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5585 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5586 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5587 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5588 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5589 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5590 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5595 fn multiple_direct_first_hops() {
5596 // Previously we'd only ever considered one first hop path per counterparty.
5597 // However, as we don't restrict users to one channel per peer, we really need to support
5598 // looking at all first hop paths.
5599 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5600 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5601 // route over multiple channels with the same first hop.
5602 let secp_ctx = Secp256k1::new();
5603 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5604 let logger = Arc::new(ln_test_utils::TestLogger::new());
5605 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5606 let scorer = ln_test_utils::TestScorer::new();
5607 let config = UserConfig::default();
5608 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5609 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5610 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5613 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5614 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5615 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5616 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5617 assert_eq!(route.paths.len(), 1);
5618 assert_eq!(route.paths[0].hops.len(), 1);
5620 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5621 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5622 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5625 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5626 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5627 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5628 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5629 assert_eq!(route.paths.len(), 2);
5630 assert_eq!(route.paths[0].hops.len(), 1);
5631 assert_eq!(route.paths[1].hops.len(), 1);
5633 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5634 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5636 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5637 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5639 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5640 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5644 // If we have a bunch of outbound channels to the same node, where most are not
5645 // sufficient to pay the full payment, but one is, we should default to just using the
5646 // one single channel that has sufficient balance, avoiding MPP.
5648 // If we have several options above the 3xpayment value threshold, we should pick the
5649 // smallest of them, avoiding further fragmenting our available outbound balance to
5651 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5652 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5653 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5654 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5655 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5656 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5657 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5658 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5659 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5660 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5661 assert_eq!(route.paths.len(), 1);
5662 assert_eq!(route.paths[0].hops.len(), 1);
5664 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5665 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5666 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5671 fn prefers_shorter_route_with_higher_fees() {
5672 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5673 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5674 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5676 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5677 let scorer = ln_test_utils::TestScorer::new();
5678 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5679 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5680 let route = get_route(
5681 &our_id, &payment_params, &network_graph.read_only(), None, 100,
5682 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5684 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5686 assert_eq!(route.get_total_fees(), 100);
5687 assert_eq!(route.get_total_amount(), 100);
5688 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5690 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5691 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5692 let scorer = FixedPenaltyScorer::with_penalty(100);
5693 let route = get_route(
5694 &our_id, &payment_params, &network_graph.read_only(), None, 100,
5695 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5697 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5699 assert_eq!(route.get_total_fees(), 300);
5700 assert_eq!(route.get_total_amount(), 100);
5701 assert_eq!(path, vec![2, 4, 7, 10]);
5704 struct BadChannelScorer {
5705 short_channel_id: u64,
5709 impl Writeable for BadChannelScorer {
5710 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5712 impl ScoreLookUp for BadChannelScorer {
5713 type ScoreParams = ();
5714 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5715 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5719 struct BadNodeScorer {
5724 impl Writeable for BadNodeScorer {
5725 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5728 impl ScoreLookUp for BadNodeScorer {
5729 type ScoreParams = ();
5730 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5731 if *target == self.node_id { u64::max_value() } else { 0 }
5736 fn avoids_routing_through_bad_channels_and_nodes() {
5737 let (secp_ctx, network, _, _, logger) = build_graph();
5738 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5739 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5740 let network_graph = network.read_only();
5742 // A path to nodes[6] exists when no penalties are applied to any channel.
5743 let scorer = ln_test_utils::TestScorer::new();
5744 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5745 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5746 let route = get_route(
5747 &our_id, &payment_params, &network_graph, None, 100,
5748 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5750 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5752 assert_eq!(route.get_total_fees(), 100);
5753 assert_eq!(route.get_total_amount(), 100);
5754 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5756 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5757 let scorer = BadChannelScorer { short_channel_id: 6 };
5758 let route = get_route(
5759 &our_id, &payment_params, &network_graph, None, 100,
5760 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5762 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5764 assert_eq!(route.get_total_fees(), 300);
5765 assert_eq!(route.get_total_amount(), 100);
5766 assert_eq!(path, vec![2, 4, 7, 10]);
5768 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5769 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5771 &our_id, &payment_params, &network_graph, None, 100,
5772 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5774 Err(LightningError { err, .. } ) => {
5775 assert_eq!(err, "Failed to find a path to the given destination");
5777 Ok(_) => panic!("Expected error"),
5782 fn total_fees_single_path() {
5784 paths: vec![Path { hops: vec![
5786 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5787 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5788 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5791 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5792 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5793 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5796 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5797 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5798 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5800 ], blinded_tail: None }],
5801 payment_params: None,
5804 assert_eq!(route.get_total_fees(), 250);
5805 assert_eq!(route.get_total_amount(), 225);
5809 fn total_fees_multi_path() {
5811 paths: vec![Path { hops: vec![
5813 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5814 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5815 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5818 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5819 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5820 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5822 ], blinded_tail: None }, Path { hops: vec![
5824 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5825 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5826 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5829 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5830 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5831 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5833 ], blinded_tail: None }],
5834 payment_params: None,
5837 assert_eq!(route.get_total_fees(), 200);
5838 assert_eq!(route.get_total_amount(), 300);
5842 fn total_empty_route_no_panic() {
5843 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5844 // would both panic if the route was completely empty. We test to ensure they return 0
5845 // here, even though its somewhat nonsensical as a route.
5846 let route = Route { paths: Vec::new(), payment_params: None };
5848 assert_eq!(route.get_total_fees(), 0);
5849 assert_eq!(route.get_total_amount(), 0);
5853 fn limits_total_cltv_delta() {
5854 let (secp_ctx, network, _, _, logger) = build_graph();
5855 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5856 let network_graph = network.read_only();
5858 let scorer = ln_test_utils::TestScorer::new();
5860 // Make sure that generally there is at least one route available
5861 let feasible_max_total_cltv_delta = 1008;
5862 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5863 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5864 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5865 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5866 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5867 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5868 assert_ne!(path.len(), 0);
5870 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5871 let fail_max_total_cltv_delta = 23;
5872 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5873 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5874 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5876 Err(LightningError { err, .. } ) => {
5877 assert_eq!(err, "Failed to find a path to the given destination");
5879 Ok(_) => panic!("Expected error"),
5884 fn avoids_recently_failed_paths() {
5885 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5886 // randomly inserting channels into it until we can't find a route anymore.
5887 let (secp_ctx, network, _, _, logger) = build_graph();
5888 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5889 let network_graph = network.read_only();
5891 let scorer = ln_test_utils::TestScorer::new();
5892 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5893 .with_max_path_count(1);
5894 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5895 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5897 // We should be able to find a route initially, and then after we fail a few random
5898 // channels eventually we won't be able to any longer.
5899 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).is_ok());
5901 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5902 for chan in route.paths[0].hops.iter() {
5903 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5905 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5906 % route.paths[0].hops.len();
5907 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
5913 fn limits_path_length() {
5914 let (secp_ctx, network, _, _, logger) = build_line_graph();
5915 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5916 let network_graph = network.read_only();
5918 let scorer = ln_test_utils::TestScorer::new();
5919 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5920 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5922 // First check we can actually create a long route on this graph.
5923 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
5924 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100,
5925 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5926 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5927 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5929 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5930 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
5931 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100,
5932 Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5934 Err(LightningError { err, .. } ) => {
5935 assert_eq!(err, "Failed to find a path to the given destination");
5937 Ok(_) => panic!("Expected error"),
5942 fn adds_and_limits_cltv_offset() {
5943 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5944 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5946 let scorer = ln_test_utils::TestScorer::new();
5948 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5949 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5950 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5951 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5952 assert_eq!(route.paths.len(), 1);
5954 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5956 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5957 let mut route_default = route.clone();
5958 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5959 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5960 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5961 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5962 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5964 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5965 let mut route_limited = route.clone();
5966 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5967 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5968 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5969 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5970 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5974 fn adds_plausible_cltv_offset() {
5975 let (secp_ctx, network, _, _, logger) = build_graph();
5976 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5977 let network_graph = network.read_only();
5978 let network_nodes = network_graph.nodes();
5979 let network_channels = network_graph.channels();
5980 let scorer = ln_test_utils::TestScorer::new();
5981 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5982 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5983 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5985 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100,
5986 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5987 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5989 let mut path_plausibility = vec![];
5991 for p in route.paths {
5992 // 1. Select random observation point
5993 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5994 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5996 prng.process_in_place(&mut random_bytes);
5997 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
5998 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6000 // 2. Calculate what CLTV expiry delta we would observe there
6001 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6003 // 3. Starting from the observation point, find candidate paths
6004 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6005 candidates.push_back((observation_point, vec![]));
6007 let mut found_plausible_candidate = false;
6009 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6010 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6011 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6012 found_plausible_candidate = true;
6013 break 'candidate_loop;
6017 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6018 for channel_id in &cur_node.channels {
6019 if let Some(channel_info) = network_channels.get(&channel_id) {
6020 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6021 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6022 if cur_path_cltv_deltas.iter().sum::<u32>()
6023 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6024 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6025 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6026 candidates.push_back((*next_id, new_path_cltv_deltas));
6034 path_plausibility.push(found_plausible_candidate);
6036 assert!(path_plausibility.iter().all(|x| *x));
6040 fn builds_correct_path_from_hops() {
6041 let (secp_ctx, network, _, _, logger) = build_graph();
6042 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6043 let network_graph = network.read_only();
6045 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6046 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6048 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6049 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6050 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
6051 &network_graph, 100, Arc::clone(&logger), &random_seed_bytes).unwrap();
6052 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6053 assert_eq!(hops.len(), route.paths[0].hops.len());
6054 for (idx, hop_pubkey) in hops.iter().enumerate() {
6055 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6060 fn avoids_saturating_channels() {
6061 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6062 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6063 let decay_params = ProbabilisticScoringDecayParameters::default();
6064 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6066 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6067 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6068 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6069 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6070 short_channel_id: 4,
6073 cltv_expiry_delta: (4 << 4) | 1,
6074 htlc_minimum_msat: 0,
6075 htlc_maximum_msat: 250_000_000,
6077 fee_proportional_millionths: 0,
6078 excess_data: Vec::new()
6080 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6081 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6082 short_channel_id: 13,
6085 cltv_expiry_delta: (13 << 4) | 1,
6086 htlc_minimum_msat: 0,
6087 htlc_maximum_msat: 250_000_000,
6089 fee_proportional_millionths: 0,
6090 excess_data: Vec::new()
6093 let config = UserConfig::default();
6094 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6095 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6096 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6097 // 100,000 sats is less than the available liquidity on each channel, set above.
6098 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();
6099 assert_eq!(route.paths.len(), 2);
6100 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6101 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6104 #[cfg(not(feature = "no-std"))]
6105 pub(super) fn random_init_seed() -> u64 {
6106 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6107 use core::hash::{BuildHasher, Hasher};
6108 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6109 println!("Using seed of {}", seed);
6114 #[cfg(not(feature = "no-std"))]
6115 fn generate_routes() {
6116 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6118 let logger = ln_test_utils::TestLogger::new();
6119 let graph = match super::bench_utils::read_network_graph(&logger) {
6127 let params = ProbabilisticScoringFeeParameters::default();
6128 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6129 let features = super::Bolt11InvoiceFeatures::empty();
6131 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6135 #[cfg(not(feature = "no-std"))]
6136 fn generate_routes_mpp() {
6137 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6139 let logger = ln_test_utils::TestLogger::new();
6140 let graph = match super::bench_utils::read_network_graph(&logger) {
6148 let params = ProbabilisticScoringFeeParameters::default();
6149 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6150 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6152 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6156 #[cfg(not(feature = "no-std"))]
6157 fn generate_large_mpp_routes() {
6158 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6160 let logger = ln_test_utils::TestLogger::new();
6161 let graph = match super::bench_utils::read_network_graph(&logger) {
6169 let params = ProbabilisticScoringFeeParameters::default();
6170 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6171 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6173 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6177 fn honors_manual_penalties() {
6178 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6179 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6181 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6182 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6184 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6185 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6187 // First check set manual penalties are returned by the scorer.
6188 let usage = ChannelUsage {
6190 inflight_htlc_msat: 0,
6191 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6193 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6194 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6195 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
6197 // Then check we can get a normal route
6198 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6199 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6200 assert!(route.is_ok());
6202 // Then check that we can't get a route if we ban an intermediate node.
6203 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6204 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6205 assert!(route.is_err());
6207 // Finally make sure we can route again, when we remove the ban.
6208 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6209 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6210 assert!(route.is_ok());
6214 fn abide_by_route_hint_max_htlc() {
6215 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6216 // params in the final route.
6217 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6218 let netgraph = network_graph.read_only();
6219 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6220 let scorer = ln_test_utils::TestScorer::new();
6221 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6222 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6223 let config = UserConfig::default();
6225 let max_htlc_msat = 50_000;
6226 let route_hint_1 = RouteHint(vec![RouteHintHop {
6227 src_node_id: nodes[2],
6228 short_channel_id: 42,
6231 proportional_millionths: 0,
6233 cltv_expiry_delta: 10,
6234 htlc_minimum_msat: None,
6235 htlc_maximum_msat: Some(max_htlc_msat),
6237 let dest_node_id = ln_test_utils::pubkey(42);
6238 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6239 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6240 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6242 // Make sure we'll error if our route hints don't have enough liquidity according to their
6243 // htlc_maximum_msat.
6244 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6245 &payment_params, &netgraph, None, max_htlc_msat + 1, Arc::clone(&logger), &scorer, &(),
6248 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6249 } else { panic!(); }
6251 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6252 let mut route_hint_2 = route_hint_1.clone();
6253 route_hint_2.0[0].short_channel_id = 43;
6254 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6255 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6256 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6257 let route = get_route(&our_id, &payment_params, &netgraph, None, max_htlc_msat + 1,
6258 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6259 assert_eq!(route.paths.len(), 2);
6260 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6261 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6265 fn direct_channel_to_hints_with_max_htlc() {
6266 // Check that if we have a first hop channel peer that's connected to multiple provided route
6267 // hints, that we properly split the payment between the route hints if needed.
6268 let logger = Arc::new(ln_test_utils::TestLogger::new());
6269 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6270 let scorer = ln_test_utils::TestScorer::new();
6271 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6272 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6273 let config = UserConfig::default();
6275 let our_node_id = ln_test_utils::pubkey(42);
6276 let intermed_node_id = ln_test_utils::pubkey(43);
6277 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6279 let amt_msat = 900_000;
6280 let max_htlc_msat = 500_000;
6281 let route_hint_1 = RouteHint(vec![RouteHintHop {
6282 src_node_id: intermed_node_id,
6283 short_channel_id: 44,
6286 proportional_millionths: 0,
6288 cltv_expiry_delta: 10,
6289 htlc_minimum_msat: None,
6290 htlc_maximum_msat: Some(max_htlc_msat),
6292 src_node_id: intermed_node_id,
6293 short_channel_id: 45,
6296 proportional_millionths: 0,
6298 cltv_expiry_delta: 10,
6299 htlc_minimum_msat: None,
6300 // Check that later route hint max htlcs don't override earlier ones
6301 htlc_maximum_msat: Some(max_htlc_msat - 50),
6303 let mut route_hint_2 = route_hint_1.clone();
6304 route_hint_2.0[0].short_channel_id = 46;
6305 route_hint_2.0[1].short_channel_id = 47;
6306 let dest_node_id = ln_test_utils::pubkey(44);
6307 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6308 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6309 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6311 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6312 Some(&first_hop.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6313 &random_seed_bytes).unwrap();
6314 assert_eq!(route.paths.len(), 2);
6315 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6316 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6317 assert_eq!(route.get_total_amount(), amt_msat);
6319 // Re-run but with two first hop channels connected to the same route hint peers that must be
6321 let first_hops = vec![
6322 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6323 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6325 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6326 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6327 &random_seed_bytes).unwrap();
6328 assert_eq!(route.paths.len(), 2);
6329 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6330 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6331 assert_eq!(route.get_total_amount(), amt_msat);
6333 // Make sure this works for blinded route hints.
6334 let blinded_path = BlindedPath {
6335 introduction_node_id: intermed_node_id,
6336 blinding_point: ln_test_utils::pubkey(42),
6338 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6339 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6342 let blinded_payinfo = BlindedPayInfo {
6344 fee_proportional_millionths: 0,
6345 htlc_minimum_msat: 1,
6346 htlc_maximum_msat: max_htlc_msat,
6347 cltv_expiry_delta: 10,
6348 features: BlindedHopFeatures::empty(),
6350 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6351 let payment_params = PaymentParameters::blinded(vec![
6352 (blinded_payinfo.clone(), blinded_path.clone()),
6353 (blinded_payinfo.clone(), blinded_path.clone())])
6354 .with_bolt12_features(bolt12_features).unwrap();
6355 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6356 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6357 &random_seed_bytes).unwrap();
6358 assert_eq!(route.paths.len(), 2);
6359 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6360 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6361 assert_eq!(route.get_total_amount(), amt_msat);
6365 fn blinded_route_ser() {
6366 let blinded_path_1 = BlindedPath {
6367 introduction_node_id: ln_test_utils::pubkey(42),
6368 blinding_point: ln_test_utils::pubkey(43),
6370 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6371 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6374 let blinded_path_2 = BlindedPath {
6375 introduction_node_id: ln_test_utils::pubkey(46),
6376 blinding_point: ln_test_utils::pubkey(47),
6378 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6379 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6382 // (De)serialize a Route with 1 blinded path out of two total paths.
6383 let mut route = Route { paths: vec![Path {
6384 hops: vec![RouteHop {
6385 pubkey: ln_test_utils::pubkey(50),
6386 node_features: NodeFeatures::empty(),
6387 short_channel_id: 42,
6388 channel_features: ChannelFeatures::empty(),
6390 cltv_expiry_delta: 0,
6392 blinded_tail: Some(BlindedTail {
6393 hops: blinded_path_1.blinded_hops,
6394 blinding_point: blinded_path_1.blinding_point,
6395 excess_final_cltv_expiry_delta: 40,
6396 final_value_msat: 100,
6398 hops: vec![RouteHop {
6399 pubkey: ln_test_utils::pubkey(51),
6400 node_features: NodeFeatures::empty(),
6401 short_channel_id: 43,
6402 channel_features: ChannelFeatures::empty(),
6404 cltv_expiry_delta: 0,
6405 }], blinded_tail: None }],
6406 payment_params: None,
6408 let encoded_route = route.encode();
6409 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6410 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6411 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6413 // (De)serialize a Route with two paths, each containing a blinded tail.
6414 route.paths[1].blinded_tail = Some(BlindedTail {
6415 hops: blinded_path_2.blinded_hops,
6416 blinding_point: blinded_path_2.blinding_point,
6417 excess_final_cltv_expiry_delta: 41,
6418 final_value_msat: 101,
6420 let encoded_route = route.encode();
6421 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6422 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6423 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6427 fn blinded_path_inflight_processing() {
6428 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6429 // account for the blinded tail's final amount_msat.
6430 let mut inflight_htlcs = InFlightHtlcs::new();
6431 let blinded_path = BlindedPath {
6432 introduction_node_id: ln_test_utils::pubkey(43),
6433 blinding_point: ln_test_utils::pubkey(48),
6434 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
6437 hops: vec![RouteHop {
6438 pubkey: ln_test_utils::pubkey(42),
6439 node_features: NodeFeatures::empty(),
6440 short_channel_id: 42,
6441 channel_features: ChannelFeatures::empty(),
6443 cltv_expiry_delta: 0,
6446 pubkey: blinded_path.introduction_node_id,
6447 node_features: NodeFeatures::empty(),
6448 short_channel_id: 43,
6449 channel_features: ChannelFeatures::empty(),
6451 cltv_expiry_delta: 0,
6453 blinded_tail: Some(BlindedTail {
6454 hops: blinded_path.blinded_hops,
6455 blinding_point: blinded_path.blinding_point,
6456 excess_final_cltv_expiry_delta: 0,
6457 final_value_msat: 200,
6460 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
6461 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
6462 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
6466 fn blinded_path_cltv_shadow_offset() {
6467 // Make sure we add a shadow offset when sending to blinded paths.
6468 let blinded_path = BlindedPath {
6469 introduction_node_id: ln_test_utils::pubkey(43),
6470 blinding_point: ln_test_utils::pubkey(44),
6472 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
6473 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
6476 let mut route = Route { paths: vec![Path {
6477 hops: vec![RouteHop {
6478 pubkey: ln_test_utils::pubkey(42),
6479 node_features: NodeFeatures::empty(),
6480 short_channel_id: 42,
6481 channel_features: ChannelFeatures::empty(),
6483 cltv_expiry_delta: 0,
6486 pubkey: blinded_path.introduction_node_id,
6487 node_features: NodeFeatures::empty(),
6488 short_channel_id: 43,
6489 channel_features: ChannelFeatures::empty(),
6491 cltv_expiry_delta: 0,
6494 blinded_tail: Some(BlindedTail {
6495 hops: blinded_path.blinded_hops,
6496 blinding_point: blinded_path.blinding_point,
6497 excess_final_cltv_expiry_delta: 0,
6498 final_value_msat: 200,
6500 }], payment_params: None};
6502 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
6503 let (_, network_graph, _, _, _) = build_line_graph();
6504 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
6505 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
6506 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
6510 fn simple_blinded_route_hints() {
6511 do_simple_blinded_route_hints(1);
6512 do_simple_blinded_route_hints(2);
6513 do_simple_blinded_route_hints(3);
6516 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
6517 // Check that we can generate a route to a blinded path with the expected hops.
6518 let (secp_ctx, network, _, _, logger) = build_graph();
6519 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6520 let network_graph = network.read_only();
6522 let scorer = ln_test_utils::TestScorer::new();
6523 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6524 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6526 let mut blinded_path = BlindedPath {
6527 introduction_node_id: nodes[2],
6528 blinding_point: ln_test_utils::pubkey(42),
6529 blinded_hops: Vec::with_capacity(num_blinded_hops),
6531 for i in 0..num_blinded_hops {
6532 blinded_path.blinded_hops.push(
6533 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
6536 let blinded_payinfo = BlindedPayInfo {
6538 fee_proportional_millionths: 500,
6539 htlc_minimum_msat: 1000,
6540 htlc_maximum_msat: 100_000_000,
6541 cltv_expiry_delta: 15,
6542 features: BlindedHopFeatures::empty(),
6545 let final_amt_msat = 1001;
6546 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
6547 let route = get_route(&our_id, &payment_params, &network_graph, None, final_amt_msat , Arc::clone(&logger),
6548 &scorer, &(), &random_seed_bytes).unwrap();
6549 assert_eq!(route.paths.len(), 1);
6550 assert_eq!(route.paths[0].hops.len(), 2);
6552 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
6553 assert_eq!(tail.hops, blinded_path.blinded_hops);
6554 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
6555 assert_eq!(tail.final_value_msat, 1001);
6557 let final_hop = route.paths[0].hops.last().unwrap();
6558 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
6559 if tail.hops.len() > 1 {
6560 assert_eq!(final_hop.fee_msat,
6561 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
6562 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
6564 assert_eq!(final_hop.fee_msat, 0);
6565 assert_eq!(final_hop.cltv_expiry_delta, 0);
6570 fn blinded_path_routing_errors() {
6571 // Check that we can generate a route to a blinded path with the expected hops.
6572 let (secp_ctx, network, _, _, logger) = build_graph();
6573 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6574 let network_graph = network.read_only();
6576 let scorer = ln_test_utils::TestScorer::new();
6577 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6578 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6580 let mut invalid_blinded_path = BlindedPath {
6581 introduction_node_id: nodes[2],
6582 blinding_point: ln_test_utils::pubkey(42),
6584 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
6587 let blinded_payinfo = BlindedPayInfo {
6589 fee_proportional_millionths: 500,
6590 htlc_minimum_msat: 1000,
6591 htlc_maximum_msat: 100_000_000,
6592 cltv_expiry_delta: 15,
6593 features: BlindedHopFeatures::empty(),
6596 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
6597 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
6598 let payment_params = PaymentParameters::blinded(vec![
6599 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
6600 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
6601 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6602 &scorer, &(), &random_seed_bytes)
6604 Err(LightningError { err, .. }) => {
6605 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
6607 _ => panic!("Expected error")
6610 invalid_blinded_path.introduction_node_id = our_id;
6611 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
6612 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6613 &scorer, &(), &random_seed_bytes)
6615 Err(LightningError { err, .. }) => {
6616 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
6618 _ => panic!("Expected error")
6621 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
6622 invalid_blinded_path.blinded_hops.clear();
6623 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
6624 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6625 &scorer, &(), &random_seed_bytes)
6627 Err(LightningError { err, .. }) => {
6628 assert_eq!(err, "0-hop blinded path provided");
6630 _ => panic!("Expected error")
6635 fn matching_intro_node_paths_provided() {
6636 // Check that if multiple blinded paths with the same intro node are provided in payment
6637 // parameters, we'll return the correct paths in the resulting MPP route.
6638 let (secp_ctx, network, _, _, logger) = build_graph();
6639 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6640 let network_graph = network.read_only();
6642 let scorer = ln_test_utils::TestScorer::new();
6643 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6644 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6645 let config = UserConfig::default();
6647 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6648 let blinded_path_1 = BlindedPath {
6649 introduction_node_id: nodes[2],
6650 blinding_point: ln_test_utils::pubkey(42),
6652 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6653 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6656 let blinded_payinfo_1 = BlindedPayInfo {
6658 fee_proportional_millionths: 0,
6659 htlc_minimum_msat: 0,
6660 htlc_maximum_msat: 30_000,
6661 cltv_expiry_delta: 0,
6662 features: BlindedHopFeatures::empty(),
6665 let mut blinded_path_2 = blinded_path_1.clone();
6666 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
6667 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
6668 blinded_payinfo_2.htlc_maximum_msat = 70_000;
6670 let blinded_hints = vec![
6671 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
6672 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
6674 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
6675 .with_bolt12_features(bolt12_features.clone()).unwrap();
6677 let route = get_route(&our_id, &payment_params, &network_graph, None,
6678 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6679 assert_eq!(route.paths.len(), 2);
6680 let mut total_amount_paid_msat = 0;
6681 for path in route.paths.into_iter() {
6682 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6683 if let Some(bt) = &path.blinded_tail {
6684 assert_eq!(bt.blinding_point,
6685 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
6686 .map(|(_, bp)| bp.blinding_point).unwrap());
6687 } else { panic!(); }
6688 total_amount_paid_msat += path.final_value_msat();
6690 assert_eq!(total_amount_paid_msat, 100_000);
6694 fn direct_to_intro_node() {
6695 // This previously caused a debug panic in the router when asserting
6696 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
6697 // direct channels we failed to account for the fee charged for use of the blinded path.
6700 // node0 -1(1)2 - node1
6701 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
6702 // doesn't account for the blinded path fee.
6704 let secp_ctx = Secp256k1::new();
6705 let logger = Arc::new(ln_test_utils::TestLogger::new());
6706 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6707 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
6708 let scorer = ln_test_utils::TestScorer::new();
6709 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6710 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6712 let amt_msat = 10_000_000;
6713 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
6714 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
6715 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6716 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6717 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6718 short_channel_id: 1,
6721 cltv_expiry_delta: 42,
6722 htlc_minimum_msat: 1_000,
6723 htlc_maximum_msat: 10_000_000,
6725 fee_proportional_millionths: 0,
6726 excess_data: Vec::new()
6728 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6729 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6730 short_channel_id: 1,
6733 cltv_expiry_delta: 42,
6734 htlc_minimum_msat: 1_000,
6735 htlc_maximum_msat: 10_000_000,
6737 fee_proportional_millionths: 0,
6738 excess_data: Vec::new()
6740 let first_hops = vec![
6741 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6743 let blinded_path = BlindedPath {
6744 introduction_node_id: nodes[1],
6745 blinding_point: ln_test_utils::pubkey(42),
6747 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6748 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6751 let blinded_payinfo = BlindedPayInfo {
6752 fee_base_msat: 1000,
6753 fee_proportional_millionths: 0,
6754 htlc_minimum_msat: 1000,
6755 htlc_maximum_msat: MAX_VALUE_MSAT,
6756 cltv_expiry_delta: 0,
6757 features: BlindedHopFeatures::empty(),
6759 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
6761 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
6763 let netgraph = network_graph.read_only();
6764 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &payment_params, &netgraph,
6765 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6766 &random_seed_bytes) {
6767 assert_eq!(err, "Failed to find a path to the given destination");
6768 } else { panic!("Expected error") }
6770 // Sending an exact amount accounting for the blinded path fee works.
6771 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
6772 let route = get_route(&nodes[0], &payment_params, &netgraph,
6773 Some(&first_hops.iter().collect::<Vec<_>>()), amt_minus_blinded_path_fee,
6774 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6775 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
6776 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
6780 fn direct_to_matching_intro_nodes() {
6781 // This previously caused us to enter `unreachable` code in the following situation:
6782 // 1. We add a route candidate for intro_node contributing a high amount
6783 // 2. We add a first_hop<>intro_node route candidate for the same high amount
6784 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
6785 // amount, and update our route candidate for intro_node for the lower amount
6786 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
6787 // lower contribution amount, but fail (this was previously caused by failure to account for
6788 // blinded path fees when adding first_hop<>intro_node candidates)
6789 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
6790 // candidate still thinks its path is contributing the original higher amount. This caused us
6791 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
6793 let secp_ctx = Secp256k1::new();
6794 let logger = Arc::new(ln_test_utils::TestLogger::new());
6795 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6796 let scorer = ln_test_utils::TestScorer::new();
6797 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6798 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6799 let config = UserConfig::default();
6801 // Values are taken from the fuzz input that uncovered this panic.
6802 let amt_msat = 21_7020_5185_1403_2640;
6803 let (_, _, _, nodes) = get_nodes(&secp_ctx);
6804 let first_hops = vec![
6805 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
6806 18446744073709551615)];
6808 let blinded_path = BlindedPath {
6809 introduction_node_id: nodes[1],
6810 blinding_point: ln_test_utils::pubkey(42),
6812 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6813 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6816 let blinded_payinfo = BlindedPayInfo {
6817 fee_base_msat: 5046_2720,
6818 fee_proportional_millionths: 0,
6819 htlc_minimum_msat: 4503_5996_2737_0496,
6820 htlc_maximum_msat: 45_0359_9627_3704_9600,
6821 cltv_expiry_delta: 0,
6822 features: BlindedHopFeatures::empty(),
6824 let mut blinded_hints = vec![
6825 (blinded_payinfo.clone(), blinded_path.clone()),
6826 (blinded_payinfo.clone(), blinded_path.clone()),
6828 blinded_hints[1].0.fee_base_msat = 419_4304;
6829 blinded_hints[1].0.fee_proportional_millionths = 257;
6830 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
6831 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
6832 blinded_hints[1].0.cltv_expiry_delta = 0;
6834 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6835 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
6836 .with_bolt12_features(bolt12_features.clone()).unwrap();
6838 let netgraph = network_graph.read_only();
6839 let route = get_route(&nodes[0], &payment_params, &netgraph,
6840 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat,
6841 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6842 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
6843 assert_eq!(route.get_total_amount(), amt_msat);
6847 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
6848 pub(crate) mod bench_utils {
6852 use bitcoin::hashes::Hash;
6853 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
6855 use crate::chain::transaction::OutPoint;
6856 use crate::routing::scoring::ScoreUpdate;
6857 use crate::sign::{EntropySource, KeysManager};
6858 use crate::ln::ChannelId;
6859 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
6860 use crate::ln::features::Bolt11InvoiceFeatures;
6861 use crate::routing::gossip::NetworkGraph;
6862 use crate::util::config::UserConfig;
6863 use crate::util::ser::ReadableArgs;
6864 use crate::util::test_utils::TestLogger;
6866 /// Tries to open a network graph file, or panics with a URL to fetch it.
6867 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
6868 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
6869 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
6870 .or_else(|_| { // Fall back to guessing based on the binary location
6871 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
6872 let mut path = std::env::current_exe().unwrap();
6873 path.pop(); // lightning-...
6875 path.pop(); // debug
6876 path.pop(); // target
6877 path.push("lightning");
6878 path.push("net_graph-2023-01-18.bin");
6881 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
6882 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
6883 let mut path = std::env::current_exe().unwrap();
6884 path.pop(); // bench...
6886 path.pop(); // debug
6887 path.pop(); // target
6888 path.pop(); // bench
6889 path.push("lightning");
6890 path.push("net_graph-2023-01-18.bin");
6893 .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");
6894 #[cfg(require_route_graph_test)]
6895 return Ok(res.unwrap());
6896 #[cfg(not(require_route_graph_test))]
6900 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
6901 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
6904 pub(crate) fn payer_pubkey() -> PublicKey {
6905 let secp_ctx = Secp256k1::new();
6906 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
6910 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
6912 channel_id: ChannelId::new_zero(),
6913 counterparty: ChannelCounterparty {
6914 features: channelmanager::provided_init_features(&UserConfig::default()),
6916 unspendable_punishment_reserve: 0,
6917 forwarding_info: None,
6918 outbound_htlc_minimum_msat: None,
6919 outbound_htlc_maximum_msat: None,
6921 funding_txo: Some(OutPoint {
6922 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
6925 short_channel_id: Some(1),
6926 inbound_scid_alias: None,
6927 outbound_scid_alias: None,
6928 channel_value_satoshis: 10_000_000_000,
6930 outbound_capacity_msat: 10_000_000_000,
6931 next_outbound_htlc_minimum_msat: 0,
6932 next_outbound_htlc_limit_msat: 10_000_000_000,
6933 inbound_capacity_msat: 0,
6934 unspendable_punishment_reserve: None,
6935 confirmations_required: None,
6936 confirmations: None,
6937 force_close_spend_delay: None,
6939 is_channel_ready: true,
6942 inbound_htlc_minimum_msat: None,
6943 inbound_htlc_maximum_msat: None,
6945 feerate_sat_per_1000_weight: None,
6946 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
6950 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
6951 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
6952 starting_amount: u64, route_count: usize,
6953 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
6954 let payer = payer_pubkey();
6955 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
6956 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6958 let nodes = graph.read_only().nodes().clone();
6959 let mut route_endpoints = Vec::new();
6960 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
6961 // with some routes we picked being un-routable.
6962 for _ in 0..route_count * 3 / 2 {
6964 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6965 let src = PublicKey::from_slice(nodes.unordered_keys()
6966 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6967 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6968 let dst = PublicKey::from_slice(nodes.unordered_keys()
6969 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6970 let params = PaymentParameters::from_node_id(dst, 42)
6971 .with_bolt11_features(features.clone()).unwrap();
6972 let first_hop = first_hop(src);
6973 let amt = starting_amount + seed % 1_000_000;
6975 get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]),
6976 amt, &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
6978 // ...and seed the scorer with success and failure data...
6979 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6980 let mut score_amt = seed % 1_000_000_000;
6982 // Generate fail/success paths for a wider range of potential amounts with
6983 // MPP enabled to give us a chance to apply penalties for more potential
6985 let mpp_features = channelmanager::provided_invoice_features(&UserConfig::default());
6986 let params = PaymentParameters::from_node_id(dst, 42)
6987 .with_bolt11_features(mpp_features).unwrap();
6989 let route_res = get_route(&payer, ¶ms, &graph.read_only(),
6990 Some(&[&first_hop]), score_amt, &TestLogger::new(), scorer,
6991 score_params, &random_seed_bytes);
6992 if let Ok(route) = route_res {
6993 for path in route.paths {
6994 if seed & 0x80 == 0 {
6995 scorer.payment_path_successful(&path);
6997 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
6998 scorer.payment_path_failed(&path, short_channel_id);
7000 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7004 // If we couldn't find a path with a higer amount, reduce and try again.
7008 route_endpoints.push((first_hop, params, amt));
7014 // Because we've changed channel scores, it's possible we'll take different routes to the
7015 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
7016 // requires a too-high CLTV delta.
7017 route_endpoints.retain(|(first_hop, params, amt)| {
7018 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
7019 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
7021 route_endpoints.truncate(route_count);
7022 assert_eq!(route_endpoints.len(), route_count);
7030 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
7031 use crate::sign::{EntropySource, KeysManager};
7032 use crate::ln::channelmanager;
7033 use crate::ln::features::Bolt11InvoiceFeatures;
7034 use crate::routing::gossip::NetworkGraph;
7035 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
7036 use crate::util::config::UserConfig;
7037 use crate::util::logger::{Logger, Record};
7038 use crate::util::test_utils::TestLogger;
7040 use criterion::Criterion;
7042 struct DummyLogger {}
7043 impl Logger for DummyLogger {
7044 fn log(&self, _record: &Record) {}
7047 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7048 let logger = TestLogger::new();
7049 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7050 let scorer = FixedPenaltyScorer::with_penalty(0);
7051 generate_routes(bench, &network_graph, scorer, &(), Bolt11InvoiceFeatures::empty(), 0,
7052 "generate_routes_with_zero_penalty_scorer");
7055 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7056 let logger = TestLogger::new();
7057 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7058 let scorer = FixedPenaltyScorer::with_penalty(0);
7059 generate_routes(bench, &network_graph, scorer, &(),
7060 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7061 "generate_mpp_routes_with_zero_penalty_scorer");
7064 pub fn generate_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, Bolt11InvoiceFeatures::empty(), 0,
7070 "generate_routes_with_probabilistic_scorer");
7073 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7074 let logger = TestLogger::new();
7075 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7076 let params = ProbabilisticScoringFeeParameters::default();
7077 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7078 generate_routes(bench, &network_graph, scorer, ¶ms,
7079 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7080 "generate_mpp_routes_with_probabilistic_scorer");
7083 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7084 let logger = TestLogger::new();
7085 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7086 let params = ProbabilisticScoringFeeParameters::default();
7087 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7088 generate_routes(bench, &network_graph, scorer, ¶ms,
7089 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
7090 "generate_large_mpp_routes_with_probabilistic_scorer");
7093 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
7094 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
7095 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
7096 bench_name: &'static str,
7098 let payer = bench_utils::payer_pubkey();
7099 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7100 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7102 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
7103 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
7105 // ...then benchmark finding paths between the nodes we learned.
7107 bench.bench_function(bench_name, |b| b.iter(|| {
7108 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
7109 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
7110 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());